Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/yoojin/signer login #95

Merged
merged 3 commits into from
Jan 29, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 22 additions & 4 deletions src/ain.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
}

Expand All @@ -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) {
Expand Down Expand Up @@ -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(
Expand Down
22 changes: 4 additions & 18 deletions src/ainize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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());
}

/**
Expand All @@ -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());
}

/**
Expand All @@ -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<string> {
await this.checkLoggedIn();
return await this.ain.getAddress()!;
return await this.ain.getAddress();
}

async getAinBalance(): Promise<number> {
await this.checkLoggedIn();
return await this.ain.getBalance() || 0;
}

Expand All @@ -90,10 +77,9 @@ export default class Ainize {
*/
// TODO(yoojin, woojae): Deploy container, advanced.
async deploy({serviceName, billingConfig, serviceUrl}: deployConfig): Promise<Service> {
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,
Expand Down
2 changes: 1 addition & 1 deletion src/controllers/appController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
17 changes: 8 additions & 9 deletions src/controllers/serviceController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ export default class ServiceController {
async chargeCredit(serviceName: string, amount: number): Promise<string> {
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),
Expand All @@ -66,13 +66,14 @@ export default class ServiceController {
}

async getCreditBalance(serviceName: string): Promise<number> {
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<creditHistories> {
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;
}
Expand All @@ -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);
Expand Down Expand Up @@ -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.');
}
}
Expand All @@ -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.');
}
}
}
2 changes: 1 addition & 1 deletion src/handlers/handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}
Expand Down
Loading