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

Add Signer login #94

Merged
merged 6 commits into from
Jan 23, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@
"typescript": "^4.6.3"
},
"dependencies": {
"@ainblockchain/ain-js": "^1.3.5",
"@ainblockchain/ain-js": "^1.6.3",
"axios": "^0.26.1",
"express": "^4.18.2",
"fast-json-stable-stringify": "^2.1.0",
Expand Down
46 changes: 32 additions & 14 deletions src/ain.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import Ain from "@ainblockchain/ain-js";
import { getBlockChainEndpoint } from "./constants";
import { TransactionBody } from "@ainblockchain/ain-util";
import { txResult } from "./types/type";
import { Signer } from "@ainblockchain/ain-js/lib/signer/signer";
import { DefaultSigner } from "@ainblockchain/ain-js/lib/signer/default-signer"

// NOTE(yoojin): Plz suggest a good name.
export default class AinModule {
Expand All @@ -20,12 +22,6 @@ export default class AinModule {
this.ain = new Ain(blockchainEndpoint, chainId);
}

isDefaultAccountExist(): boolean {
if (this.getDefaultAccount())
return true;
return false;
}

createAccount() {
this.checkAinInitiated();
const newAccount = this.ain!.wallet.create(1)[0];
Expand All @@ -39,39 +35,61 @@ export default class AinModule {
this.ain!.wallet.addAndSetDefaultAccount(privateKey);
}

setSigner(signer: Signer) {
this.checkAinInitiated();
this.ain!.setSigner(signer);
}

getDefaultAccount() {
this.checkAinInitiated();
return this.ain!.wallet.defaultAccount;
}

getSigner() {
this.checkAinInitiated();
return this.ain!.signer
}

getAddress() {
this.checkAinInitiated();
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ain 초기화가 되면 signer가 무조건 있나요?
signer가 있다면 무조건 defaultAddress가 있는게 맞나요?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ain 초기화시 defaultSigner가 반드시 생성됩니다. 이 때 defaultSigner에서 getAddress() 는 defaultWalletAddress 를 반환합니다.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

default account가 세팅되지 않은 경우 해당 부분에서 에러를 던지네요. 기존 getAddress에서는 해당 경우에 null을 반환했기 때문에 try-catch 문으로 null 반환하도록 변경하겠습니다.
추가적으로 defaultAccount 존재 유무를 확인하는 코드들의 수정이 덜 이루어진것을 발견하여 같이 수정하도록 하겠습니다.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

넵 그부분만 수정하고 merge해주세요!

try {
return this.getSigner().getAddress();
} catch (e) {
return null;
}
}

removeDefaultAccount() {
this.checkAinInitiated();
this.ain!.wallet.removeDefaultAccount();
}

getAddress() {
this.isDefaultAccountExist();
return this.ain!.wallet.defaultAccount!.address;
removeSigner() {
this.checkAinInitiated();
const wallet = this.ain!.wallet;
const provider = this.ain!.provider;
wallet.removeDefaultAccount();
this.ain!.setSigner(new DefaultSigner(wallet, provider))
}

async getBalance() {
this.isDefaultAccountExist();
return await this.ain!.wallet.getBalance();
const address = this.getAddress();
return address ? await this.ain!.wallet.getBalance(address) : null;
}

async getValue(path: string) {
this.checkAinInitiated();
return await this.ain!.db.ref(path).getValue();
}

private async _sendTransaction(data: TransactionBody) {
private async _sendTransaction(txBody: TransactionBody) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

사용하는 코드들도 바꾸어주어야 하지 않나요?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

파라메터 변수 명만 변경되어 호출부에선 변경 필요 없을 것 같습니다

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

아 맞네요 확인했습니다~

this.checkAinInitiated();
return await this.ain!.sendTransaction(data);
return await this.ain!.signer.sendTransaction(txBody);
}

private checkAinInitiated(): boolean {
if (!this.ain)
throw new Error('Set initAin(chainId) First.');
throw new Error('Set initAin(chainId) first.');
return true;
}

Expand Down
35 changes: 28 additions & 7 deletions src/ainize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { deployConfig } from "./types/type";
import AinModule from "./ain";
import Internal from "./internal";
import { Account } from "@ainblockchain/ain-util";
import { AinWalletSigner } from "@ainblockchain/ain-js/lib/signer/ain-wallet-signer";

export default class Ainize {
private cache: NodeCache;
Expand Down Expand Up @@ -42,21 +43,43 @@ export default class Ainize {
console.log('login success! address:', this.ain.getAddress());
}

/**
* Login to ainize using AIN Wallet Signer.
*/
async loginWithSigner() {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

login with wallet이 더 좋을 것 같습니다.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

wallet 이란 명명이 web3에서 관념적으로 사용되는 의미나 ain-js에서 사용되는 등 혼동될 가능성이 있을 것 같습니다.
그러나 signer도 가독성 좋은 명명인지는 확신이 없어서, 우선 회의때 논의되었던 명명인 loginWithSigner로 merge하고 추후 관련하여 다시 논의하면 좋을 것 같습니다.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

const signer = new AinWalletSigner;
this.ain.setSigner(signer);
console.log('login success! address: ', this.ain.getAddress());
}

/**
* Logout from ainize.
*/
async logout() {
this.ain.removeDefaultAccount();
this.ain.removeSigner();
await this.handler.disconnect();
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> {
return await this.ain.getAddress();
await this.checkLoggedIn();
return await this.ain.getAddress()!;
}

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

// FIXME(yoojin): add config type and change param type.
Expand All @@ -67,12 +90,10 @@ export default class Ainize {
*/
// TODO(yoojin, woojae): Deploy container, advanced.
async deploy({serviceName, billingConfig, serviceUrl}: deployConfig): Promise<Service> {
if(!this.ain.isDefaultAccountExist()) {
throw new Error('you should login first');
}
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 = this.ain.getAddress()!;
if (!billingConfig) {
billingConfig = {
...DEFAULT_BILLING_CONFIG,
Expand Down
11 changes: 7 additions & 4 deletions src/controllers/serviceController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,13 +120,16 @@ export default class ServiceController {
return (await this.ain.getValue(Path.app(serviceName).billingConfig())).depositAddress;
}

isLoggedIn(): void {
if(!this.ain.getDefaultAccount())
throw new Error('You should login First.');
checkLoggedIn(): void {
try {
!this.ain.getAddress();
} catch(error) {
throw new Error('You should login first.');
}
}

async isAdmin(serviceName: string): Promise<void> {
this.isLoggedIn();
this.checkLoggedIn();
const adminPath = `/manage_app/${serviceName}/config/admin`;
const adminList = await this.ain.getValue(adminPath);
if(!adminList[this.ain.getAddress()]) {
Expand Down
14 changes: 7 additions & 7 deletions src/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ export default class Service {
* @returns {string} Transaction hash.
*/
async chargeCredit(amount: number) {
this.isLoggedIn();
this.checkLoggedIn();
return await this.serviceController.chargeCredit(this.serviceName, amount);
}

Expand All @@ -52,7 +52,7 @@ export default class Service {
* @returns {string} Transaction hash.
*/
async withdrawCredit(amount: number) {
this.isLoggedIn();
this.checkLoggedIn();
return await this.serviceController.withdrawCredit(this.serviceName, amount);
}

Expand All @@ -61,7 +61,7 @@ export default class Service {
* @returns {number} Amount of credit balance.
*/
async getCreditBalance() {
this.isLoggedIn();
this.checkLoggedIn();
return await this.serviceController.getCreditBalance(this.serviceName);
}

Expand All @@ -70,7 +70,7 @@ export default class Service {
* @returns {creditHistories} Histories of credit deposit and usage.
*/
async getCreditHistory() {
this.isLoggedIn();
this.checkLoggedIn();
return await this.serviceController.getCreditHistory(this.serviceName);
}

Expand All @@ -80,7 +80,7 @@ export default class Service {
* @returns {string} Response data from service.
*/
async request(requestData: any, requestKey?: string) {
this.isLoggedIn();
this.checkLoggedIn();
return await this.serviceController.request(this.serviceName, requestData, requestKey);
}

Expand Down Expand Up @@ -113,7 +113,7 @@ export default class Service {
return this.serviceController.isAdmin(this.serviceName);
}

private isLoggedIn() {
return this.serviceController.isLoggedIn();
private checkLoggedIn() {
return this.serviceController.checkLoggedIn();
}
}
8 changes: 4 additions & 4 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@
# yarn lockfile v1


"@ainblockchain/ain-js@^1.3.5":
version "1.6.0"
resolved "https://registry.npmjs.org/@ainblockchain/ain-js/-/ain-js-1.6.0.tgz"
integrity sha512-REzTJAf8w2TIsJLH7DhKWJF+kxfgMnCCwzWaeD4rYAv4TeD70PhFmYDrDMuy/qZd5KKMXqMigiU9PLWbiu8a7A==
"@ainblockchain/ain-js@^1.6.3":
version "1.6.3"
resolved "https://registry.yarnpkg.com/@ainblockchain/ain-js/-/ain-js-1.6.3.tgz#56ca744a6bf5e558f2acba75f106e8f88f5426ba"
integrity sha512-rdQfT6jcqcF4VP1twwMQkCijZ6SN1RewTjU1D35rJ7ZnRQjoIxekkodkdcIDVvyUEpR6A6iuT9SSSTz9KUMNbA==
dependencies:
"@ainblockchain/ain-util" "^1.1.9"
"@types/node" "^12.7.3"
Expand Down