内置钱包几个链交互方法增加钱包余额的判断

This commit is contained in:
cebgcontract 2022-11-15 17:04:12 +08:00
parent 611da1d3b3
commit 062f2e4852
5 changed files with 187 additions and 67 deletions

15
src/JCWallet.d.ts vendored Normal file
View File

@ -0,0 +1,15 @@
interface Window {
debug: boolean;
ethSigUtil: any;
cc: any;
Stream: any;
jc: {
wallet: JCWallet;
};
jcwallet: JCWallet;
}
declare namespace jc {
export const wallet: JCWallet;
}
declare let window: Window;

View File

@ -21,7 +21,6 @@ import { WALLET_STORAGE_KEY_NAME } from "./config/constants";
import { DEFALUT_TOKENS } from "./config/chain_config"; import { DEFALUT_TOKENS } from "./config/chain_config";
import { import {
loadInternalWallet, loadInternalWallet,
newAccount,
newMnemonic, newMnemonic,
restoreWalletByMnemonic, restoreWalletByMnemonic,
} from "./manage/WalletManage"; } from "./manage/WalletManage";
@ -32,6 +31,7 @@ import { ZWalletConnect } from "./comp/ZWalletConnect";
import { getJCErc721Info, getTypeByAddress, UNKNOW } from "./util/chain.util"; import { getJCErc721Info, getTypeByAddress, UNKNOW } from "./util/chain.util";
import { JCStandard } from "./standards/JCStandard"; import { JCStandard } from "./standards/JCStandard";
import { NativeSvr } from "./services/NativeSvr"; import { NativeSvr } from "./services/NativeSvr";
import { ChainCommon } from "./standards/ChainCommon";
var global = var global =
(typeof globalThis !== "undefined" && globalThis) || (typeof globalThis !== "undefined" && globalThis) ||
@ -39,17 +39,7 @@ var global =
(typeof global !== "undefined" && global) || (typeof global !== "undefined" && global) ||
{}; {};
declare global { window.debug = false;
interface Window {
jc: {
wallet: JCWallet;
};
jcwallet: JCWallet;
ethSigUtil: any;
cc: any;
Stream: any;
}
}
export interface IChainData { export interface IChainData {
name: string; name: string;
@ -76,6 +66,7 @@ export default class JCWallet {
public erc20Standard: ERC20Standard; public erc20Standard: ERC20Standard;
public erc721Standard: ERC721Standard; public erc721Standard: ERC721Standard;
public erc1155Standard: ERC1155Standard; public erc1155Standard: ERC1155Standard;
public chainCommon: ChainCommon;
public jcStandard: JCStandard; public jcStandard: JCStandard;
public nativeSvr: NativeSvr; public nativeSvr: NativeSvr;
public wConnect: ZWalletConnect; public wConnect: ZWalletConnect;
@ -133,18 +124,23 @@ export default class JCWallet {
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);
console.log("init JCStandard"); console.log("init JCStandard");
start = Date.now(); this.createAccount();
this.wallet = this.web3.eth.accounts.wallet.load( // this.wallet = this.web3.eth.accounts.wallet.load(
this.password, // this.password,
WALLET_STORAGE_KEY_NAME // WALLET_STORAGE_KEY_NAME
); // );
console.log(`load wallet cost: ${(Date.now() - start) / 1000}`); // console.log(`load wallet cost: ${(Date.now() - start) / 1000}`);
console.log(JSON.stringify(this.wallet[0])); console.log(JSON.stringify(this.wallet[0]));
if (!this.wallet || this.wallet.length === 0) { console.log(
// this.createAccount(); "this.web3.eth.defaultAccount: " +
this.newWallet(this.password); JSON.stringify(this.web3.eth.defaultAccount)
} );
// if (!this.wallet || this.wallet.length === 0) {
// // this.createAccount();
// this.newWallet(this.password);
// }
// start = Date.now(); // start = Date.now();
// this.data = loadData(); // this.data = loadData();
// console.log(`init wallet ext data cost: ${(Date.now() - start) / 1000}`); // console.log(`init wallet ext data cost: ${(Date.now() - start) / 1000}`);
@ -171,6 +167,7 @@ export default class JCWallet {
this.erc721Standard = new ERC721Standard(this.web3); this.erc721Standard = new ERC721Standard(this.web3);
this.erc1155Standard = new ERC1155Standard(this.web3); this.erc1155Standard = new ERC1155Standard(this.web3);
this.jcStandard = new JCStandard(this.web3); this.jcStandard = new JCStandard(this.web3);
this.chainCommon = new ChainCommon(this.web3);
return this.web3.eth.getChainId(); return this.web3.eth.getChainId();
}) })
.then((chainId: number) => { .then((chainId: number) => {
@ -218,7 +215,6 @@ export default class JCWallet {
public newWallet(password: string) { public newWallet(password: string) {
this.password = password; this.password = password;
newMnemonic(this.password);
this.createAccount(); this.createAccount();
} }
@ -320,15 +316,15 @@ export default class JCWallet {
public createAccount() { public createAccount() {
// let account = this.web3.eth.accounts.create() // let account = this.web3.eth.accounts.create()
this.wallet = this.web3.eth.accounts.wallet;
const index = this.getMaxIdexOfType(0); const index = this.getMaxIdexOfType(0);
// const accountNew = newAccount(this.password, index); const nativePrefix = "0x000000000000000000000000";
// const account = this.wallet.add(accountNew); const nativePrivateKey = `${nativePrefix}${this.currentAccAddr.slice(2)}`;
const acc = this.web3.eth.accounts.privateKeyToAccount( const acc = this.web3.eth.accounts.privateKeyToAccount(nativePrivateKey);
"0x4f3edf983ac636a65a842ce7c78d9aa706d3b113bce9c46f30d7d21715b23b1d"
);
const account = this.wallet.add(acc); const account = this.wallet.add(acc);
this.web3.eth.defaultAccount = account.address;
console.log("web3 account: " + JSON.stringify(this.wallet[0])); console.log("web3 account: " + JSON.stringify(this.wallet[0]));
console.log("current account: " + JSON.stringify(this.currentAccount));
this.wallet.save(this.password, WALLET_STORAGE_KEY_NAME); this.wallet.save(this.password, WALLET_STORAGE_KEY_NAME);
const chain = this.currentChain.id; const chain = this.currentChain.id;
let data = this.data.find((o) => o.address === account.address); let data = this.data.find((o) => o.address === account.address);
@ -418,19 +414,7 @@ export default class JCWallet {
public async getBalance(address?: string) { public async getBalance(address?: string) {
console.log("get balance with address: ", address); console.log("get balance with address: ", address);
if (!address) { let balance = await this.chainCommon.getBalance(address);
let accountData = this.wallet[this.accountIndex];
if (!accountData) {
throw new Error("no account found");
}
address = accountData.address;
}
let balance = await this.web3.eth.getBalance(address);
// let balance = await this.erc20Standard.getBalanceOf(
// "0x67f6a7BbE0da067A747C6b2bEdF8aBBF7D6f60dc",
// address
// );
return balance; return balance;
} }

View File

@ -44,6 +44,15 @@ export async function loadInternalWallet() {
if (infoRes.errcode) { if (infoRes.errcode) {
return; return;
} }
// let infoRes = {
// data: {
// oid: "636cce78a95e553cb061c0f1",
// account: "636b6acaa95e553cb0609ce2",
// is: "2e0316fa555a",
// salt: "6824413b37",
// key: "aec87426c4655cf81a6059964ca919fc8fc995886078931681ba1b6431db281c",
// },
// };
console.log("wallet info: " + JSON.stringify(infoRes.data)); console.log("wallet info: " + JSON.stringify(infoRes.data));
let seed = infoRes.data.oid + infoRes.data.is + infoRes.data.salt; let seed = infoRes.data.oid + infoRes.data.is + infoRes.data.salt;
let seedHash = md5Hash(seed); let seedHash = md5Hash(seed);
@ -56,7 +65,7 @@ export async function loadInternalWallet() {
//@ts-ignore //@ts-ignore
let strWallet = jsb.generateWallet(idHash, seedHash); let strWallet = jsb.generateWallet(idHash, seedHash);
console.log("generate wallet cost: " + (Date.now() - time) / 1000); console.log("generate wallet cost: " + (Date.now() - time) / 1000);
console.log("native wallet info: " + strWallet); window.debug && console.log("native wallet info " + strWallet);
let walletInfo = JSON.parse(strWallet); let walletInfo = JSON.parse(strWallet);
address = walletInfo.address; address = walletInfo.address;
setImmediate(function () { setImmediate(function () {
@ -75,6 +84,8 @@ export async function loadInternalWallet() {
address = walletInfo.address; address = walletInfo.address;
} else { } else {
let qrResult = await new NativeSvr().restoreKey(idHash); let qrResult = await new NativeSvr().restoreKey(idHash);
// let qrResult =
// "cd00eb0126aeed39762579ce94c90a04695ad17fbd5e79aa4e9fc4a34ba32a5";
//@ts-ignore //@ts-ignore
let strWallet = jsb.restoreWallet( let strWallet = jsb.restoreWallet(
idHash, idHash,
@ -82,15 +93,15 @@ export async function loadInternalWallet() {
infoRes.data.key, infoRes.data.key,
qrResult qrResult
); );
console.log("restore native wallet info: " + strWallet); window.debug && console.log("restore native wallet info " + strWallet);
let walletInfo = JSON.parse(strWallet); let walletInfo = JSON.parse(strWallet);
address = walletInfo.address; address = walletInfo.address;
setImmediate(function () { // setImmediate(function () {
retry( // retry(
() => uploadWalletInfo({ key: walletInfo.master }), // () => uploadWalletInfo({ key: walletInfo.master }),
MAX_UPLOAD_COUNT // MAX_UPLOAD_COUNT
); // );
}); // });
} }
} }
return address; return address;

View File

@ -0,0 +1,26 @@
import Web3 from "web3";
import { BN } from "ethereumjs-util";
export class ChainCommon {
private web3: Web3;
constructor(web3: Web3) {
this.web3 = web3;
}
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));
let balance = await this.web3.eth.getBalance(address);
console.log("eth balance: " + new BN(balance));
return new BN(balance).gte(new BN(gasPrice).mul(new BN(gas)));
}
public async getBalance(address?: string) {
address = address || jc.wallet.currentAccAddr;
let balance = await this.web3.eth.getBalance(address);
return balance;
}
}

View File

@ -4,7 +4,7 @@ import { abiChipLocker } from "../abis/abiChipLocker";
import { abiERC1155 } from "../abis/abiERC1155"; import { abiERC1155 } from "../abis/abiERC1155";
import { abiEvolveFactory } from "../abis/abiUserEvolveFactory"; import { abiEvolveFactory } from "../abis/abiUserEvolveFactory";
import { abiMinterFactory } from "../abis/abiUserMinterFactory"; import { abiMinterFactory } from "../abis/abiUserMinterFactory";
import { DEFAULT_NFT_TYPES, JC_CONTRACTS } from "../config/chain_config"; import { JC_CONTRACTS } from "../config/chain_config";
export class JCStandard { export class JCStandard {
private web3: Web3; private web3: Web3;
@ -28,9 +28,24 @@ export class JCStandard {
from: jc.wallet.currentAccAddr, from: jc.wallet.currentAccAddr,
}); });
//TODO:: increaseAllowance before call //TODO:: increaseAllowance before call
let gas = await contract.methods let gas;
try {
gas = await contract.methods
.buy721NFT(addresses, values, signature) .buy721NFT(addresses, values, signature)
.estimateGas({ gas: 1000000 }); .estimateGas({ gas: 1000000 });
} catch (err) {
console.log("estimategas with error: " + JSON.stringify(err));
}
gas = gas || 1000000;
//@ts-ignore
if (jc.wallet.isInternal) {
//@ts-ignore
let ethEnough = await jc.wallet.chainCommon.checkEthEnough(gas);
if (!ethEnough) {
throw "eth not enough";
}
}
//@ts-ignore //@ts-ignore
if (!jc.wallet.isInternal) { if (!jc.wallet.isInternal) {
setTimeout(() => { setTimeout(() => {
@ -38,9 +53,15 @@ export class JCStandard {
jumpToWallet(); jumpToWallet();
}, 1500); }, 1500);
} }
return contract.methods let result;
try {
result = await contract.methods
.buy721NFT(addresses, values, signature) .buy721NFT(addresses, values, signature)
.send({ gas: (gas * 1.1) | 0 }); .send({ gas: (gas * 1.1) | 0 });
} catch (err) {
console.log(JSON.stringify(err));
}
return result;
} }
async buyNft1155({ async buyNft1155({
@ -64,6 +85,15 @@ export class JCStandard {
let gas = await contract.methods let gas = await contract.methods
.buy1155NFT(addresses, values, ids, amounts, signature) .buy1155NFT(addresses, values, ids, amounts, signature)
.estimateGas({ gas: 1000000 }); .estimateGas({ gas: 1000000 });
gas = gas || 1000000;
//@ts-ignore
if (jc.wallet.isInternal) {
//@ts-ignore
let ethEnough = await jc.wallet.chainCommon.checkEthEnough(gas);
if (!ethEnough) {
throw "eth not enough";
}
}
//@ts-ignore //@ts-ignore
if (!jc.wallet.isInternal) { if (!jc.wallet.isInternal) {
setTimeout(() => { setTimeout(() => {
@ -97,6 +127,15 @@ export class JCStandard {
let gas = await contract.methods let gas = await contract.methods
.evolve721NFT(nftAddress, tokenIds, startTime, nonce, signature) .evolve721NFT(nftAddress, tokenIds, startTime, nonce, signature)
.estimateGas({ gas: 1000000 }); .estimateGas({ gas: 1000000 });
gas = gas || 1000000;
//@ts-ignore
if (jc.wallet.isInternal) {
//@ts-ignore
let ethEnough = await jc.wallet.chainCommon.checkEthEnough(gas);
if (!ethEnough) {
throw "eth not enough";
}
}
//@ts-ignore //@ts-ignore
if (!jc.wallet.isInternal) { if (!jc.wallet.isInternal) {
setTimeout(() => { setTimeout(() => {
@ -128,6 +167,15 @@ export class JCStandard {
let gas = await contract.methods let gas = await contract.methods
.evolveChip(tokenIds, startTime, nonce, signature) .evolveChip(tokenIds, startTime, nonce, signature)
.estimateGas({ gas: 1000000 }); .estimateGas({ gas: 1000000 });
gas = gas || 1000000;
//@ts-ignore
if (jc.wallet.isInternal) {
//@ts-ignore
let ethEnough = await jc.wallet.chainCommon.checkEthEnough(gas);
if (!ethEnough) {
throw "eth not enough";
}
}
//@ts-ignore //@ts-ignore
if (!jc.wallet.isInternal) { if (!jc.wallet.isInternal) {
setTimeout(() => { setTimeout(() => {
@ -161,6 +209,15 @@ export class JCStandard {
let gas = await contract.methods let gas = await contract.methods
.mintShardBatchUser(tokenIds, amounts, startTime, nonce, signature) .mintShardBatchUser(tokenIds, amounts, startTime, nonce, signature)
.estimateGas({ gas: 1000000 }); .estimateGas({ gas: 1000000 });
gas = gas || 1000000;
//@ts-ignore
if (jc.wallet.isInternal) {
//@ts-ignore
let ethEnough = await jc.wallet.chainCommon.checkEthEnough(gas);
if (!ethEnough) {
throw "eth not enough";
}
}
//@ts-ignore //@ts-ignore
if (!jc.wallet.isInternal) { if (!jc.wallet.isInternal) {
setTimeout(() => { setTimeout(() => {
@ -212,6 +269,15 @@ export class JCStandard {
signature signature
) )
.estimateGas({ gas: 1000000 }); .estimateGas({ gas: 1000000 });
gas = gas || 1000000;
//@ts-ignore
if (jc.wallet.isInternal) {
//@ts-ignore
let ethEnough = await jc.wallet.chainCommon.checkEthEnough(gas);
if (!ethEnough) {
throw "eth not enough";
}
}
//@ts-ignore //@ts-ignore
if (!jc.wallet.isInternal) { if (!jc.wallet.isInternal) {
setTimeout(() => { setTimeout(() => {
@ -251,14 +317,11 @@ export class JCStandard {
let lockerAddress = let lockerAddress =
JC_CONTRACTS[window.jc.wallet.currentChain.id].chipLocker; JC_CONTRACTS[window.jc.wallet.currentChain.id].chipLocker;
const contract = new this.web3.eth.Contract(abiChipLocker, lockerAddress, { const contract = new this.web3.eth.Contract(abiChipLocker, lockerAddress, {
//@ts-ignore
from: jc.wallet.currentAccAddr, from: jc.wallet.currentAccAddr,
}); });
let chipInstance = new this.web3.eth.Contract(abiERC1155, addresses[1], { let chipInstance = new this.web3.eth.Contract(abiERC1155, addresses[1], {
//@ts-ignore
from: jc.wallet.currentAccAddr, from: jc.wallet.currentAccAddr,
}); });
//@ts-ignore
if (!jc.wallet.isInternal) { if (!jc.wallet.isInternal) {
setTimeout(() => { setTimeout(() => {
// @ts-ignore // @ts-ignore
@ -268,6 +331,13 @@ export class JCStandard {
let gas1 = await chipInstance.methods let gas1 = await chipInstance.methods
.setApprovalForAll(lockerAddress, true) .setApprovalForAll(lockerAddress, true)
.estimateGas({ gas: 1000000 }); .estimateGas({ gas: 1000000 });
gas1 = gas1 || 1000000;
if (jc.wallet.isInternal) {
let ethEnough = await jc.wallet.chainCommon.checkEthEnough(gas1);
if (!ethEnough) {
throw "eth not enough";
}
}
await chipInstance.methods await chipInstance.methods
.setApprovalForAll(lockerAddress, true) .setApprovalForAll(lockerAddress, true)
.send({ gas: (gas1 * 1.1) | 0 }); .send({ gas: (gas1 * 1.1) | 0 });
@ -275,7 +345,13 @@ export class JCStandard {
let gas0 = await contract.methods let gas0 = await contract.methods
.pluginChip(addresses, values, chipIds, slots, signature) .pluginChip(addresses, values, chipIds, slots, signature)
.estimateGas({ gas: 1000000 }); .estimateGas({ gas: 1000000 });
//@ts-ignore gas0 = gas0 || 1000000;
if (jc.wallet.isInternal) {
let ethEnough = await jc.wallet.chainCommon.checkEthEnough(gas0);
if (!ethEnough) {
throw "eth not enough";
}
}
if (!jc.wallet.isInternal) { if (!jc.wallet.isInternal) {
setTimeout(() => { setTimeout(() => {
// @ts-ignore // @ts-ignore
@ -303,14 +379,22 @@ export class JCStandard {
let lockerAddress = let lockerAddress =
JC_CONTRACTS[window.jc.wallet.currentChain.id].chipLocker; JC_CONTRACTS[window.jc.wallet.currentChain.id].chipLocker;
const contract = new this.web3.eth.Contract(abiChipLocker, lockerAddress, { const contract = new this.web3.eth.Contract(abiChipLocker, lockerAddress, {
//@ts-ignore
from: jc.wallet.currentAccAddr, from: jc.wallet.currentAccAddr,
}); });
let gas0 = 1000000;
let gas0 = await contract.methods try {
gas0 = await contract.methods
.unplugChip(addresses, values, chipIds, slots, signature) .unplugChip(addresses, values, chipIds, slots, signature)
.estimateGas({ gas: 1000000 }); .estimateGas({ gas: 1000000 });
//@ts-ignore } catch (err) {
console.log(err);
}
if (jc.wallet.isInternal) {
let ethEnough = await jc.wallet.chainCommon.checkEthEnough(gas0);
if (!ethEnough) {
throw "eth not enough";
}
}
if (!jc.wallet.isInternal) { if (!jc.wallet.isInternal) {
setTimeout(() => { setTimeout(() => {
// @ts-ignore // @ts-ignore