2022-06-21 15:54:48 +08:00

85 lines
2.4 KiB
TypeScript

import { IToken } from "../data/DataModel";
import { renderFromTokenMinimalUnit } from "../util/number.util";
import HashIcon from "./comp/HashIcon";
import WalletBase from "./WallerBase";
const {ccclass, property} = cc._decorator;
const ETH_TYPE = 'eth'
@ccclass
export default class OneToken extends WalletBase {
@property(cc.Label)
symbolLabel: cc.Label = null;
@property(cc.Label)
countLabel: cc.Label = null;
@property(HashIcon)
icon: HashIcon = null;
data: IToken = null
// LIFE-CYCLE CALLBACKS:
// onLoad () {}
start () {
super.start()
this.updateInfo()
}
// update (dt) {}
init(_data: IToken) {
this.data = _data
}
private async updateInfo() {
if (this.data.symbol) {
this.symbolLabel.string = this.data.symbol
} else {
// TODO: get from remote
let symbol = await this.wallet.erc20Standard.getTokenSymbol(this.data.address)
this.data.symbol = symbol
}
this.icon.init(this.data.address)
if (this.data.decimal === undefined && this.data.type !== ETH_TYPE) {
// get from chain
let decimal = await this.wallet.erc20Standard.getTokenDecimals(this.data.address)
this.data.decimal = parseInt(decimal)
}
if (this.data.balance !== undefined) {
this.showBalance()
} else {
this.countLabel.string = '-'
}
if (this.data.type === ETH_TYPE) {
let balance = await this.wallet.getBalance()
this.data.balance = balance
} else {
const account = this.wallet.currentAccount().address
let balance = await this.wallet.erc20Standard.getBalanceOf(this.data.address, account)
this.data.balance = balance
}
this.showBalance()
}
private showBalance() {
if (this.data.decimal !== undefined && this.data.balance !== undefined) {
this.countLabel.string = this.formatMoney()
}
}
formatMoney() {
console.log('update balance: ', this.data.balance)
const chainData = this.wallet.currentChain
let symbol = chainData.symbol
if (this.data.balance === '-') {
return `-`;
}
let money = renderFromTokenMinimalUnit(this.data.balance, this.data.decimal, 4)
return `${money}`;
}
}