2022-06-22 15:29:26 +08:00

102 lines
2.9 KiB
TypeScript

import { WALLET_ACCOUNT_CHANGE, WALLET_CHAIN_CHANGE, WALLET_SHOW_QR } from "../common/WalletEvent";
import { IChainData } from "../JCWallet";
import { renderFromTokenMinimalUnit } from "../util/number.util";
import WalletBase from "./WallerBase";
const {ccclass, property} = cc._decorator;
@ccclass
export default class WalletInfo extends WalletBase {
@property(cc.Label)
addressLabel: cc.Label = null;
@property(cc.Label)
balanceLabel: cc.Label = null;
@property(cc.Label)
nameLabel: cc.Label = null;
@property(cc.Node)
avatar: cc.Node = null;
accountId: string = '';
balance: string = ''
// LIFE-CYCLE CALLBACKS:
// onLoad () {}
start () {
super.start()
this.accountId = this.wallet.currentAccount().address
this.updateUI()
this.updateBalance()
this.wallet.mainHandlers.on(WALLET_CHAIN_CHANGE, this.chainChange.bind(this))
this.wallet.mainHandlers.on(WALLET_ACCOUNT_CHANGE, this.chainChange.bind(this))
}
// update (dt) {}
updateUI(): void {
super.updateUI()
this.nameLabel.string = this.wallet.currentAccountData.nickname || 'Account'
this.addressLabel.string = this.formatAddress()
this.balanceLabel.string = this.formatMoney()
if (this.wallet.iconType === 'jazz') {
this.avatar.getComponent('JazzIcon').init(this.accountId)
} else {
this.avatar.getComponent('HashIcon').init(this.accountId)
}
}
formatAddress() {
if (this.accountId.length >= 10) {
return this.accountId.substring(0, 6) + '...' + this.accountId.substring(this.accountId.length - 4)
} else if (this.accountId.length > 0 && this.accountId.length < 10) {
return this.accountId
} else {
return ''
}
}
formatMoney() {
console.log('update balance: ', this.balance)
const chainData = this.wallet.currentChain
let symbol = chainData.symbol
if (this.balance === '-') {
return `- ${symbol}`;
}
let money = renderFromTokenMinimalUnit(this.balance, 18, 4)
return `${money} ${symbol}`;
}
updateBalance() {
this.balance = '-'
this.updateUI()
this.wallet.getBalance()
.then(v => {
console.log('update balance: ', v);
this.balance = v + ''
this.updateUI()
})
}
chainChange(data: IChainData) {
this.updateBalance()
}
onAccountChange() {
this.accountId = this.wallet.currentAccount().address
this.updateBalance()
}
showReceiveNode() {
const address = this.wallet.currentAccount().address
const chainId = this.wallet.currentChain.id
let qrUrl = `ethereum:${address}@${chainId}`
// this.showQr(qrUrl)
this.wallet.mainHandlers.emit(WALLET_SHOW_QR, {val: qrUrl})
}
}