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

Feat/woojae/model controller #42

Merged
merged 7 commits into from
Sep 19, 2023
Merged
Show file tree
Hide file tree
Changes from 4 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
15 changes: 1 addition & 14 deletions src/ainize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,35 +3,22 @@ import * as NodeCache from "node-cache";
import Middleware from "./middlewares/middleware";
import { getBlockChainEndpoint } from "./constants";
import Handler from "./handlers/handler";
import Wallet from "./modules/wallet";
import App from "./modules/app";
import DepositService from "./modules/service/depositService";
import UseService from "./modules/service/useService";
import Service from "./modules/service";
import Admin from "./modules/admin";
import Model from "./model";
export default class Ainize {
private cache: NodeCache;
ain: Ain;
middleware: Middleware;
handler: Handler;
wallet: Wallet;
app:App;
service: Service;
admin: Admin;

constructor(chainId: 1|0, privateKey?: string ) {
constructor(chainId: 1|0) {
const blockChainEndpoint = getBlockChainEndpoint(chainId);
this.ain = new Ain(blockChainEndpoint, chainId);
this.app = new App(this);
this.cache = new NodeCache();
this.middleware = new Middleware(this.cache);
this.handler = new Handler(this);
this.wallet = new Wallet(this, privateKey);
const depositService = new DepositService(this);
const useService = new UseService(this);
this.service = new Service(this, depositService, useService);
this.admin = new Admin(this, depositService, useService);
}

model(modelName: string) {
Expand Down
67 changes: 56 additions & 11 deletions src/controllers/modelController.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,16 @@
import { SetOperation } from "@ainblockchain/ain-js/lib/types";
import AinModule from "../ain";
import { Path } from "../constants";
import { getRequestDepositOp, getTransferOp } from "../utils/util";
import { buildSetOperation, buildTxBody } from "../utils/builder";

export default class ModelController {
private static instance: ModelController | undefined;
private ain = AinModule.getInstance();
static getInstance() {
if(!ModelController.instance){
ModelController.instance = new ModelController();

}
return ModelController.instance;
}
Expand All @@ -14,37 +22,64 @@ export default class ModelController {

//TODO(woojae): implement this
async getInformation(modelName: string) {
return await true;
return await 'information of model';
}

//TODO(woojae): implement this
async calculateCost(modelName: string, requestData: string) {
return await 0.3;
const billingConfig = await this.ain.getValue(Path.app(modelName).billingConfig());
const token = requestData.split(' ').length;
let cost = token * billingConfig.costPerToken;
if (billingConfig.minCost && cost < billingConfig.minCost) {
cost = billingConfig.minCost;
} else if (billingConfig.maxCost && cost > billingConfig.maxCost) {
cost = billingConfig.maxCost;
}
return cost;
}

//TODO(woojae): implement this
async chargeCredit(modelName: string, amount: number) {
return await true;
this.isLoggedIn();
const transferKey = Date.now();
const userAddress = this.ain.getDefaultAccount()!.address;
Copy link
Collaborator

Choose a reason for hiding this comment

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

여러 함수에 쓰여서 ainize 에 getAddress 나 getUserAddress 추가해도 좋을 것 같습니다.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

ainize보단 ain에 추가하겠습니다

const depositAddress = await this.getDepositAddress(modelName);
const op_list: SetOperation[] = [
getTransferOp(userAddress, depositAddress, transferKey.toString(), amount),
getRequestDepositOp(modelName, userAddress, transferKey.toString(), amount)
]
const txBody = buildTxBody(op_list, transferKey);
return this.ain.sendTransaction(txBody);
}


//TODO(woojae): implement this
async withdrawCredit(modelName: string, amount: number) {
return await true;
}

//TODO(woojae): implement this
async getCreditBalance(modelName: string) {
return await 0.3;
this.isLoggedIn();
const userAddress = this.ain.getDefaultAccount()!.address;
const balancePath = Path.app(modelName).balanceOfUser(userAddress);
return await this.ain.getValue(balancePath);
}

//TODO(woojae): implement this
async getCreditHistory(modelName: string) {
return await true;
this.isLoggedIn();
const userAddress = this.ain.getDefaultAccount()!.address;
const creditHistoryPath = Path.app(modelName).historyOfUser(userAddress);
return await this.ain.getValue(creditHistoryPath);
}

//TODO(woojae): implement this
//TODO(woojae): connect with handler
async use(modelName: string, requestData: string) {
return await true;
this.isLoggedIn();
const requestKey = Date.now();
const requesterAddress = this.ain.getDefaultAccount()!.address;
const requestPath = Path.app(modelName).request(requesterAddress, requestKey);
const requestOp = buildSetOperation("SET_VALUE", requestPath, {prompt: requestData});
const txBody = buildTxBody(requestOp);
await this.ain.sendTransaction(txBody);
return requestKey;
}

//TODO(woojae): implement this
Expand All @@ -64,4 +99,14 @@ export default class ModelController {
async changeModelInfo(modelName: string, config: any) {
return await true;
}

private async getDepositAddress(appName: string) {
return await this.ain.getValue(Path.app(appName).billingConfig().defaultAddress);
Copy link
Collaborator

Choose a reason for hiding this comment

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

(await this.ain.getValue(Path.app(appName).billingConfig()).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.

앗 수정했습니다.

}

private isLoggedIn() {
if(!this.ain.getDefaultAccount())
throw new Error('Set defaultAccount First.');
Copy link
Collaborator

Choose a reason for hiding this comment

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

Login First?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

수정했습니다.

return true;
}
}
55 changes: 55 additions & 0 deletions src/internal.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { SetOperation } from "@ainblockchain/ain-js/lib/types";
import { Request } from "express";
import { getChangeBalanceOp, getResponseOp, getWriteHistoryOp } from "./utils/util";
import { HISTORY_TYPE, RESPONSE_STATUS, request, response } from "./types/type";
import { buildTxBody } from "./utils/builder";
import AinModule from "./ain";
import { Path } from "./constants";

export default class internal {
private ain: AinModule;
constructor() {
Copy link
Collaborator

Choose a reason for hiding this comment

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

minor) constructor 없이 변수 선언부에 바로 할당해도 좋을 것 같습니다.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

수정했습니다.

this.ain = AinModule.getInstance();
}
async handleDeposit(req: Request) {
const transferKey = req.body.valuePath[4];
Copy link
Collaborator

Choose a reason for hiding this comment

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

request data 처럼 deposit data도 type 및 parsing func 있으면 더 좋을 것 같습니다.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

반영했습니다.
원래 deposit은 유저가 request에 있는 데이터들에 접근할 필요가 없어서 안만들었었는데, 개발할 때 편의와 통일성을 위해 작성했습니다.

const transferValue = req.body.value;
const appName = req.body.valuePath[1];
const requesterAddress = req.body.auth.addr;
const ops: SetOperation[] = [];
const changeBalanceOp = await getChangeBalanceOp(appName, requesterAddress, "INC_VALUE", transferValue);
const writeHistoryOp = await getWriteHistoryOp(appName, requesterAddress, HISTORY_TYPE.DEPOSIT, transferValue, transferKey);
ops.push(changeBalanceOp);
ops.push(writeHistoryOp);
const txBody = buildTxBody(ops);
return await this.ain.sendTransaction(txBody);
}

async handleRequest(req: Request, cost: number, status: RESPONSE_STATUS, responseData: string) {
const { requesterAddress, requestKey, appName } = this.getDataFromServiceRequest(req);
const ops:SetOperation[] = [];
const responseOp = getResponseOp(appName, requesterAddress, requestKey, status, responseData, cost);
ops.push(responseOp);
if(cost > 0) {
const changeBalanceOp = getChangeBalanceOp(appName, requesterAddress, 'DEC_VALUE', cost);
const writeHistoryOp = getWriteHistoryOp(appName, requesterAddress, HISTORY_TYPE.USAGE, cost, requestKey);
ops.push(changeBalanceOp);
ops.push(writeHistoryOp);
}
const txBody = buildTxBody(ops);
return await this.ain.sendTransaction(txBody);
}

getDataFromServiceRequest(req: Request) {
if(!req.body.valuePath[1] || !req.body.valuePath[3] || !req.body.valuePath[4] || !req.body.value.prompt) {
throw new Error("Not from service request");
}
const requestData: request = {
appName: req.body.valuePath[1],
requesterAddress: req.body.auth.addr,
requestKey: req.body.valuePath[4],
requestData: req.body.value.prompt,
}
return requestData;
}
};
66 changes: 0 additions & 66 deletions src/modules/admin.ts

This file was deleted.

6 changes: 3 additions & 3 deletions src/modules/app.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { SetOperation } from "@ainblockchain/ain-js/lib/types";
import { Path } from "../constants";
import { appBillingConfig, setRuleParam, setTriggerFunctionParm, triggerFunctionConfig } from "../types/type";
import { buildSetOperation } from "../utils/builder";
import { buildSetOperation, buildTxBody } from "../utils/builder";
import ModuleBase from "./moduleBase";

export default class App extends ModuleBase {
Expand Down Expand Up @@ -39,7 +39,7 @@ export default class App extends ModuleBase {
const configOp = this.buildSetAppBillingConfigOp(appName, defaultConfig);
setBillingConfigOps.push(configOp);

const txBody = this.buildTxBody([
const txBody = buildTxBody([
createAppOp,
...setRuleOps,
...setFunctionOps,
Expand All @@ -56,7 +56,7 @@ export default class App extends ModuleBase {
*/
async setAppBillingConfig(appName: string, config: appBillingConfig) {
const setConfigOp = this.buildSetAppBillingConfigOp(appName, config);
const txBody = this.buildTxBody(setConfigOp);
const txBody = buildTxBody(setConfigOp);
return await this.sendTransaction(txBody);
}

Expand Down
12 changes: 0 additions & 12 deletions src/modules/moduleBase.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,18 +8,6 @@ export default class ModuleBase {
constructor(ainize: Ainize) {
this.ain = ainize.ain;
}

protected buildTxBody(operation: SetOperation | SetOperation[], timestamp? : number): TransactionBody {
return {
operation: Array.isArray(operation) ? {
type: "SET",
op_list: operation
} : operation,
gas_price: 500,
timestamp: timestamp? timestamp : Date.now(),
nonce: -1,
}
}

protected getDefaultAccount() {
const defaultAccount = this.ain.wallet.defaultAccount;
Expand Down
41 changes: 0 additions & 41 deletions src/modules/service.ts

This file was deleted.

38 changes: 0 additions & 38 deletions src/modules/service/depositService.ts

This file was deleted.

Loading