diff --git a/src/ain.ts b/src/ain.ts index aadf681..8b6c3fc 100644 --- a/src/ain.ts +++ b/src/ain.ts @@ -50,12 +50,22 @@ export default class AinModule { return this.ain!.signer } - getAddress() { + async getAddress() { this.checkAinInitiated(); try { return this.getSigner().getAddress(); } catch (e) { - return null; + throw new Error("Need to set up an account or signer first."); + } + } + + isAccountSetUp() { + try { + this.checkAinInitiated(); + this.getSigner().getAddress(); + return true; + } catch (e) { + return false; } } @@ -73,8 +83,9 @@ export default class AinModule { } async getBalance() { - const address = this.getAddress(); - return address ? await this.ain!.wallet.getBalance(address) : null; + const address = await this.getAddress(); + const balancePath = `/accounts/${address}/balance`; + return await this.ain!.db.ref(balancePath).getValue(); } async getValue(path: string) { @@ -110,6 +121,13 @@ export default class AinModule { private handleTxResultWrapper(operation: Function) { return async (args: any) => { const res = await operation(args); + // ainWalletSigner return txHash or undefined. + if (typeof res === 'string') { + return res; + } else if (res === undefined) { + throw new Error(`Failed to build transaction.`); + } + // defaultSigner return a result object of transactions. const { tx_hash, result } = res; if (this.hasFailedOpResultList(result)) { throw new Error( diff --git a/src/ainize.ts b/src/ainize.ts index 4d113d7..3d9f9f8 100644 --- a/src/ainize.ts +++ b/src/ainize.ts @@ -40,7 +40,7 @@ export default class Ainize { async login(privateKey: string) { this.ain.setDefaultAccount(privateKey); await this.handler.connect(); - console.log('login success! address:', this.ain.getAddress()); + console.log('login success! address:', await this.ain.getAddress()); } /** @@ -49,7 +49,7 @@ export default class Ainize { async loginWithSigner() { const signer = new AinWalletSigner; this.ain.setSigner(signer); - console.log('login success! address: ', this.ain.getAddress()); + console.log('login success! address: ', await this.ain.getAddress()); } /** @@ -61,24 +61,11 @@ export default class Ainize { console.log('logout success!'); } - /** - * Throw error if user doesn't log in. - * @returns {} - */ - async checkLoggedIn() { - const address = await this.ain.getAddress(); - if (!address) { - throw new Error('You should login first.'); - } - } - async getAddress(): Promise { - await this.checkLoggedIn(); - return await this.ain.getAddress()!; + return await this.ain.getAddress(); } async getAinBalance(): Promise { - await this.checkLoggedIn(); return await this.ain.getBalance() || 0; } @@ -90,10 +77,9 @@ export default class Ainize { */ // TODO(yoojin, woojae): Deploy container, advanced. async deploy({serviceName, billingConfig, serviceUrl}: deployConfig): Promise { - await this.checkLoggedIn(); // TODO(yoojin, woojae): Add container deploy logic. const result = await new Promise(async (resolve, reject) => { - const deployer = this.ain.getAddress()!; + const deployer = await this.ain.getAddress(); if (!billingConfig) { billingConfig = { ...DEFAULT_BILLING_CONFIG, diff --git a/src/controllers/appController.ts b/src/controllers/appController.ts index 21899f6..09b1114 100644 --- a/src/controllers/appController.ts +++ b/src/controllers/appController.ts @@ -124,7 +124,7 @@ export default class AppController { } async checkCostAndBalance(appName: string, value: string) { - const requesterAddress = this.ain.getAddress(); + const requesterAddress = await this.ain.getAddress(); const billingConfig = (await this.getBillingConfig(appName)); const token = value.split(' ').length; let cost = token * billingConfig.costPerToken; diff --git a/src/controllers/serviceController.ts b/src/controllers/serviceController.ts index 7f65b6d..cd7ff83 100644 --- a/src/controllers/serviceController.ts +++ b/src/controllers/serviceController.ts @@ -50,7 +50,7 @@ export default class ServiceController { async chargeCredit(serviceName: string, amount: number): Promise { this.checkRunning(serviceName); const transferKey = Date.now(); - const userAddress = this.ain.getAddress(); + const userAddress = await this.ain.getAddress(); const depositAddress = await this.getDepositAddress(serviceName); const op_list: SetOperation[] = [ getTransferOp(userAddress, depositAddress, transferKey.toString(), amount), @@ -66,13 +66,14 @@ export default class ServiceController { } async getCreditBalance(serviceName: string): Promise { - const userAddress = this.ain.getAddress(); + const userAddress = await this.ain.getAddress(); + console.log("userAddress in getCreditBalance", userAddress) const balancePath = Path.app(serviceName).balanceOfUser(userAddress); return await this.ain.getValue(balancePath) as number | 0; } async getCreditHistory(serviceName: string): Promise { - const userAddress = this.ain.getAddress(); + const userAddress = await this.ain.getAddress(); const creditHistoryPath = Path.app(serviceName).historyOfUser(userAddress); return await this.ain.getValue(creditHistoryPath) as creditHistories; } @@ -82,7 +83,7 @@ export default class ServiceController { const result = await new Promise(async (resolve, reject) => { requestKey = requestKey || Date.now().toString(); try { - const requesterAddress = this.ain.getAddress(); + const requesterAddress = await this.ain.getAddress(); const responsePath = Path.app(serviceName).response(requesterAddress, requestKey.toString()); await this.handler.subscribe(responsePath, resolve); const requestPath = Path.app(serviceName).request(requesterAddress, requestKey); @@ -121,9 +122,7 @@ export default class ServiceController { } checkLoggedIn(): void { - try { - !this.ain.getAddress(); - } catch(error) { + if (!this.ain.isAccountSetUp()) { throw new Error('You should login first.'); } } @@ -132,8 +131,8 @@ export default class ServiceController { this.checkLoggedIn(); const adminPath = `/manage_app/${serviceName}/config/admin`; const adminList = await this.ain.getValue(adminPath); - if(!adminList[this.ain.getAddress()]) { - throw new Error('You are not admin'); + if(!adminList[(await this.ain.getAddress())]) { + throw new Error('You are not a service admin.'); } } } \ No newline at end of file diff --git a/src/handlers/handler.ts b/src/handlers/handler.ts index d82c7c5..230bdf5 100644 --- a/src/handlers/handler.ts +++ b/src/handlers/handler.ts @@ -32,7 +32,7 @@ export default class Handler { } private async disconnectedCb() { - if(AinModule.getInstance().isDefaultAccountExist()) { + if(await AinModule.getInstance().getAddress()) { console.log('disconnected. reconnecting...'); await this.connect(); } @@ -49,7 +49,7 @@ export default class Handler { }, (valueChangedEvent: any) => { this.unsubscribe(subscribeId); - resolve(valueChangedEvent.values.after.data); + resolve(valueChangedEvent.values.after); }, (err) => { throw new Error(err.message);