update readme

This commit is contained in:
cebgcontract 2022-10-20 14:55:11 +08:00
parent 8d91c8186f
commit aae460cbaa
3 changed files with 115 additions and 101 deletions

2
README.md Normal file
View File

@ -0,0 +1,2 @@
## 整合web3.js和walletconnect, 打包成独立的js包, 供页面使用

View File

@ -1,89 +1,93 @@
import { Chain } from '../chain/Chain' import { Chain } from "../chain/Chain";
import { AVAILABLE_CHAINS, IChainData } from '../configs/config_chain' import { AVAILABLE_CHAINS, IChainData } from "../configs/config_chain";
import { AllChains } from '../configs/allchain' import { AllChains } from "../configs/allchain";
import { import {
ACTIVATE_PROXY_ABI, ACTIVATE_PROXY_ABI,
MYSTERY_BOX_ABI, MYSTERY_BOX_ABI,
MYSTERY_PROXY_ABI, MYSTERY_PROXY_ABI,
} from '../configs/contracts' } from "../configs/contracts";
import { singleton } from '../decorator/singleton.decorator' import { singleton } from "../decorator/singleton.decorator";
import { Blockchain } from './blockchain' import { Blockchain } from "./blockchain";
import { UserModule } from '../module/UserModule' import { UserModule } from "../module/UserModule";
import { getNonce } from '../api/User' import { getNonce } from "../api/User";
import { EventBus, SHOW_ERR_MSG } from '../utils/event-bus' import { EventBus, SHOW_ERR_MSG } from "../utils/event-bus";
@singleton @singleton
export default class ChainManager { export default class ChainManager {
bc: Blockchain bc: Blockchain;
instanceMap: Map<string, any> instanceMap: Map<string, any>;
public chainMap: Map<number, IChainData> = new Map() public chainMap: Map<number, IChainData> = new Map();
private _availableChains: Map<number, IChainData> = new Map() private _availableChains: Map<number, IChainData> = new Map();
constructor() { constructor() {
this.bc = new Blockchain() this.bc = new Blockchain();
this.instanceMap = new Map() this.instanceMap = new Map();
for (const data of AllChains) { for (const data of AllChains) {
this.chainMap.set(data.id, data) this.chainMap.set(data.id, data);
} }
} }
get availableChains() { get availableChains() {
if (this._availableChains.size === 0) { if (this._availableChains.size === 0) {
for (const id of AVAILABLE_CHAINS) { for (const id of AVAILABLE_CHAINS) {
const d = this.chainMap.get(id) const d = this.chainMap.get(id);
if (d) { if (d) {
this._availableChains.set(id, d) this._availableChains.set(id, d);
} }
} }
} }
return this._availableChains return this._availableChains;
} }
public async init() { public async init() {
if (this.bc.isWalletConnect) { if (this.bc.isWalletConnect) {
try { try {
await this.bc.connect() await this.bc.connect();
await this.getNance() await this.getNance();
} catch (err) { } catch (err) {
console.log('connect chain error: ', err) console.log("connect chain error: ", err);
} }
} }
} }
get isLogined() { get isLogined() {
return !!UserModule.token && !!UserModule.step return !!UserModule.token && !!UserModule.step;
} }
public async logout() { public async logout() {
await this.bc.disconnect() await this.bc.disconnect();
} }
public get currentChain() { public get currentChain() {
return this.bc.currentChain return this.bc.currentChain;
}
public get currentAccount() {
return UserModule.accountId;
} }
public async login() { public async login() {
if (!UserModule.step) { if (!UserModule.step) {
try { try {
await this.bc.connect(true) await this.bc.connect(true);
await this.checkNance() await this.checkNance();
} catch (err) { } catch (err) {
EventBus.$emit(SHOW_ERR_MSG, err.message) EventBus.$emit(SHOW_ERR_MSG, err.message);
await Promise.reject(err) await Promise.reject(err);
} }
} }
} }
public async checkNance() { public async checkNance() {
try { try {
let nonce = UserModule.nonce let nonce = UserModule.nonce;
if (!nonce) { if (!nonce) {
const preRequest: any = await getNonce({ const preRequest: any = await getNonce({
account: UserModule.accountId, account: UserModule.accountId,
net_id: UserModule.chainId, net_id: UserModule.chainId,
}) });
nonce = preRequest.nonce + '' nonce = preRequest.nonce + "";
UserModule.updateNonce(nonce) UserModule.updateNonce(nonce);
} }
await UserModule.Login({ await UserModule.Login({
@ -91,56 +95,56 @@ export default class ChainManager {
account: UserModule.accountId, account: UserModule.accountId,
chainId: UserModule.chainId, chainId: UserModule.chainId,
nonce, nonce,
}) });
UserModule.updateStep(1) UserModule.updateStep(1);
} catch (err) { } catch (err) {
console.log(err) console.log(err);
await Promise.reject(err) await Promise.reject(err);
} }
} }
public async getNance() { public async getNance() {
console.log('need get nance') console.log("need get nance");
try { try {
const preRequest: any = await getNonce({ const preRequest: any = await getNonce({
account: UserModule.accountId, account: UserModule.accountId,
net_id: UserModule.chainId, net_id: UserModule.chainId,
}) });
console.log('success get nonce: ', preRequest) console.log("success get nonce: ", preRequest);
// if need check sign and has nonce val, store it // if need check sign and has nonce val, store it
if (preRequest.state) { if (preRequest.state) {
UserModule.updateStep(1) UserModule.updateStep(1);
} else if (!preRequest.state && preRequest.nonce) { } else if (!preRequest.state && preRequest.nonce) {
if (UserModule.token) { if (UserModule.token) {
await UserModule.LogOut() await UserModule.LogOut();
} }
UserModule.updateStep(0) UserModule.updateStep(0);
} }
if (preRequest.nonce) { if (preRequest.nonce) {
UserModule.updateNonce(preRequest.nonce + '') UserModule.updateNonce(preRequest.nonce + "");
} }
} catch (err) { } catch (err) {
EventBus.$emit(SHOW_ERR_MSG, 'Error get login nonce') EventBus.$emit(SHOW_ERR_MSG, "Error get login nonce");
} }
} }
public async getInstance(address: string, chainId: number, abi?: any) { public async getInstance(address: string, chainId: number, abi?: any) {
const key = `${chainId}_${address}` const key = `${chainId}_${address}`;
if (!this.instanceMap.has(key)) { if (!this.instanceMap.has(key)) {
const chain = new Chain(this.chainMap.get(chainId)!.rpc) const chain = new Chain(this.chainMap.get(chainId)!.rpc);
const coinInstance = await chain.initContractInstance(address, abi) const coinInstance = await chain.initContractInstance(address, abi);
this.instanceMap.set(key, coinInstance) this.instanceMap.set(key, coinInstance);
} }
return this.instanceMap.get(key) return this.instanceMap.get(key);
} }
public async getBalance(address: string, chainId: number) { public async getBalance(address: string, chainId: number) {
const coinInstance = await this.getInstance(address, chainId) const coinInstance = await this.getInstance(address, chainId);
const balance = await coinInstance.methods const balance = await coinInstance.methods
.balanceOf(UserModule.accountId) .balanceOf(UserModule.accountId)
.call() .call();
console.log('balance: ', balance) console.log("balance: ", balance);
return balance return balance;
} }
/** /**
@ -154,13 +158,13 @@ export default class ChainManager {
const coinInstance = await this.getInstance( const coinInstance = await this.getInstance(
address, address,
chainId, chainId,
MYSTERY_BOX_ABI, MYSTERY_BOX_ABI
) );
const balance = await coinInstance.methods const balance = await coinInstance.methods
.balanceOf(UserModule.accountId) .balanceOf(UserModule.accountId)
.call() .call();
console.log('nft balance: ', balance) console.log("nft balance: ", balance);
return balance return balance;
} }
/** /**
@ -174,16 +178,16 @@ export default class ChainManager {
address: string, address: string,
chainId: number, chainId: number,
start = 0, start = 0,
page = 8, page = 8
) { ) {
const nftInstance = await this.getInstance( const nftInstance = await this.getInstance(
address, address,
chainId, chainId,
MYSTERY_BOX_ABI, MYSTERY_BOX_ABI
) );
return nftInstance.methods return nftInstance.methods
.userTokens(UserModule.accountId, start, page) .userTokens(UserModule.accountId, start, page)
.call() .call();
} }
/** /**
@ -196,20 +200,20 @@ export default class ChainManager {
public async getNftIdOfIndex( public async getNftIdOfIndex(
address: string, address: string,
chainId: number, chainId: number,
index: number, index: number
) { ) {
const nftInstance = await this.getInstance( const nftInstance = await this.getInstance(
address, address,
chainId, chainId,
MYSTERY_BOX_ABI, MYSTERY_BOX_ABI
) );
const nftId = await nftInstance.methods const nftId = await nftInstance.methods
.tokenOfOwnerByIndex(UserModule.accountId, index) .tokenOfOwnerByIndex(UserModule.accountId, index)
.call() .call();
console.log( console.log(
`address: ${address}, chainId: ${chainId}, index: ${index}, token: ${nftId}`, `address: ${address}, chainId: ${chainId}, index: ${index}, token: ${nftId}`
) );
return nftId return nftId;
} }
/** /**
@ -226,16 +230,16 @@ export default class ChainManager {
boxId: string, boxId: string,
tokenIds: number[], tokenIds: number[],
nonce: string, nonce: string,
signature: string, signature: string
) { ) {
const proxyInstance = await this.bc.getContractInstance( const proxyInstance = await this.bc.getContractInstance(
address, address,
MYSTERY_PROXY_ABI, MYSTERY_PROXY_ABI
) );
// get transactionHash and upload to server for verify // get transactionHash and upload to server for verify
return proxyInstance.methods return proxyInstance.methods
.openBox(boxId, tokenIds, nonce, signature) .openBox(boxId, tokenIds, nonce, signature)
.send({ gas: 1000000 }) .send({ gas: 1000000 });
} }
/** /**
@ -254,19 +258,19 @@ export default class ChainManager {
nftNew: string, nftNew: string,
nftType: number, nftType: number,
nonce: string, nonce: string,
signature: string, signature: string
) { ) {
const nftProxyInstance = await this.bc.getContractInstance( const nftProxyInstance = await this.bc.getContractInstance(
address, address,
ACTIVATE_PROXY_ABI, ACTIVATE_PROXY_ABI
) );
const gas = await nftProxyInstance.methods const gas = await nftProxyInstance.methods
.activateOne(nftOld, nftNew, nftType, nonce, signature) .activateOne(nftOld, nftNew, nftType, nonce, signature)
.estimateGas({ gas: 1000000 }) .estimateGas({ gas: 1000000 });
console.log('nftProxyInstance activateOne need gas: ', gas) console.log("nftProxyInstance activateOne need gas: ", gas);
return nftProxyInstance.methods return nftProxyInstance.methods
.activateOne(nftOld, nftNew, nftType, nonce, signature) .activateOne(nftOld, nftNew, nftType, nonce, signature)
.send({ gas: (gas * 1.1) | 0 }) .send({ gas: (gas * 1.1) | 0 });
} }
public async transferToAccount({ public async transferToAccount({
@ -275,27 +279,27 @@ export default class ChainManager {
chainId, chainId,
address, address,
}: { }: {
to: string to: string;
amount: number amount: number;
chainId: number chainId: number;
address: string address: string;
}) { }) {
const self = this const self = this;
if (chainId !== this.bc.currentChain) { if (chainId !== this.bc.currentChain) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
this.bc.switchEthereumChain(chainId, function () { this.bc.switchEthereumChain(chainId, function () {
self.bc self.bc
.transferToAccount(to, amount, address) .transferToAccount(to, amount, address)
.then((res) => { .then((res) => {
resolve && resolve(res) resolve && resolve(res);
}) })
.catch((err) => { .catch((err) => {
reject && reject(err) reject && reject(err);
}) });
}) });
}) });
} else { } else {
return this.bc.transferToAccount(to, amount, address) return this.bc.transferToAccount(to, amount, address);
} }
} }
} }

View File

@ -1,27 +1,35 @@
import ChainManager from './chain/ChainManager' import ChainManager from "./chain/ChainManager";
import { singleton } from './decorator/singleton.decorator' import { singleton } from "./decorator/singleton.decorator";
import { UserModule } from './module/UserModule' import { UserModule } from "./module/UserModule";
@singleton @singleton
export class JCChain { export class JCChain {
chainManager = new ChainManager() chainManager = new ChainManager();
public login() { public login() {
return this.chainManager.login() return this.chainManager.login();
} }
public selectWalletAndLogin(walletType: number) { public selectWalletAndLogin(walletType: number) {
this.chainManager.bc.walletType = walletType this.chainManager.bc.walletType = walletType;
return this.chainManager.login() return this.chainManager.login();
} }
logout() { logout() {
return this.chainManager.logout() return this.chainManager.logout();
} }
get logined() { get logined() {
return !!UserModule.token return !!UserModule.token;
}
get account() {
return UserModule.accountId;
}
get chainId() {
return UserModule.chainId;
} }
} }
export * from './utils/event-bus' export * from "./utils/event-bus";