Skip to content

Commit

Permalink
Merge pull request #42 from ainize-team/feat/woojae/modelController
Browse files Browse the repository at this point in the history
Feat/woojae/model controller
  • Loading branch information
akastercomcom authored Sep 19, 2023
2 parents 3388997 + bfe339f commit 69d9f88
Show file tree
Hide file tree
Showing 16 changed files with 226 additions and 353 deletions.
9 changes: 7 additions & 2 deletions src/ain.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,8 @@ export default class AinModule {

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

setDefaultAccount(privateKey: string) {
Expand Down Expand Up @@ -50,4 +50,9 @@ export default class AinModule {
throw new Error('Set initAin(chainId) First.');
return true;
}

getAddress() {
this.isDefaultAccountExist();
return this.ain!.wallet.defaultAccount!.address;
}
}
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/operator";
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.getAddress();
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.getAddress();
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.getAddress();
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.getAddress();
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;
}

private isLoggedIn() {
if(!this.ain.getDefaultAccount())
throw new Error('You should login First.');
return true;
}
}
61 changes: 61 additions & 0 deletions src/internal.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import { SetOperation } from "@ainblockchain/ain-js/lib/types";
import { Request } from "express";
import { getChangeBalanceOp, getResponseOp, getWriteHistoryOp } from "./utils/operator";
import { HISTORY_TYPE, RESPONSE_STATUS, deposit, request, response } from "./types/type";
import { buildTxBody } from "./utils/builder";
import AinModule from "./ain";

export default class internal {
private ain = AinModule.getInstance();
async handleDeposit(req: Request) {
const { requesterAddress, appName, transferKey, transferValue } = this.getDataFromDepositRequest(req);
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;
}

private getDataFromDepositRequest(req: Request) {
if(!req.body.valuePath[1] || !req.body.valuePath[4] || !req.body.value) {
throw new Error("Not from deposit request");
}
const depositData: deposit = {
transferKey: req.body.valuePath[4],
transferValue: req.body.value,
appName: req.body.valuePath[1],
requesterAddress: req.body.auth.addr,
}
return depositData;
}
}
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.

Loading

0 comments on commit 69d9f88

Please sign in to comment.