TestChain/assets/scripts/wallet/WalletController.ts
2022-06-16 16:01:37 +08:00

129 lines
4.0 KiB
TypeScript

import { WALLET_CHAIN_CHANGE } from "../../comp/wallet/scripts/common/WalletEvent";
import JCWallet, { IChainData } from "../../comp/wallet/scripts/JCWallet";
import sth = require("../../comp/wallet/scripts/lib/ethSigUtil");
import { GET } from "../../comp/wallet/scripts/lib/Http";
const {ccclass, property} = cc._decorator;
const EIP721_DOMAIN_DATA = [
{ name: 'name', type: 'string' },
{ name: 'version', type: 'string' }
]
@ccclass
export default class WalletController extends cc.Component {
private wallet: JCWallet
@property(cc.Node)
private walletNode: cc.Node = null
// private apiBase = 'https://market.cebg.games'
private apiBase = 'https://game2006api-test.kingsome.cn'
// LIFE-CYCLE CALLBACKS:
// onLoad () {}
start () {
this.walletNode.active = false;
this.wallet = new JCWallet();
let chains = CC_DEBUG ? [322, 97] : [321, 56]
this.wallet.init({
chains
})
this.wallet.mainHandlers.on(WALLET_CHAIN_CHANGE, this.chainChange.bind(this))
console.log(this.wallet.currentAccount());
}
chainChange(data: IChainData) {
}
// update (dt) {}
testShowWallet() {
this.walletNode.active = !this.walletNode.active
}
async testSign() {
// const nonce = Math.random() * 100000 | 0
let account = this.wallet.currentAccount()
let nonceUrlBase = this.apiBase + '/webapp/index.php?c=Market&a=getNonce'
let nonceUrl = `${nonceUrlBase}&account=${account.address}&net_id=322`
let res = await GET(nonceUrl);
let obj: any = {}
obj = JSON.parse(res as string);
const nonce = obj.nonce;
console.log(res);
const tips:string = 'signrequest'
const signMsg = {
tips,
nonce
}
const signObj = {
types: {
EIP712Domain: EIP721_DOMAIN_DATA,
set: [
{ name: 'tips', type: 'string' },
{ name: 'nonce', type: 'string' }
]
},
primaryType: 'set',
domain: {
name: 'Auth',
version: '1'
},
message: signMsg
}
let result = this.wallet.signTypedData(signObj)
console.log(`sign result: ${result}`)
let v = {
"types": {
"EIP712Domain": [
{
"name": "name",
"type": "string"
},
{
"name": "version",
"type": "string"
}
],
"set": [
{
"name": "tips",
"type": "string"
},
{
"name": "nonce",
"type": "string"
}
]
},
"primaryType": "set",
"domain": {
"name": "Auth",
"version": "1"
},
"message": {
"tips": "signrequest",
"nonce": "62aac5d66d627_1655358934"
}
}
const sig = '0x62326600dd17bc202a623f361ab6a06b3eea6dd0a6fb1c868fbcadfddf84ffbe082c681274457b6afb06ea5a2dc5f895c7683f9d5a978c58c570a6530d7cfb441b';
let resultAddress = this.wallet.recoverTypedSignature(v, sig)
console.log(`source address: ${account.address}`)
console.log(`target address: ${resultAddress}`)
console.log(`is same: ${account.address.toLowerCase() == resultAddress}`)
let loginUrlBase = this.apiBase + '/webapp/index.php?c=Market&a=auth'
let loginUrl = `${loginUrlBase}&account=${account.address}&nonce=${nonce}&signature=${result}&tips=${tips.replace(/\ /g, '+')}&net_id=322`
let resLogin = await GET(loginUrl);
console.log(resLogin);
}
}