This commit is contained in:
aozhiwei 2022-05-03 23:37:11 +08:00
parent 3974451176
commit 3eb1df1195
20 changed files with 7900 additions and 171 deletions

View File

@ -2,8 +2,9 @@ const app = require('j7/app');
const event = require('j7/event'); const event = require('j7/event');
const config = require('j7/config'); const config = require('j7/config');
event.addListener(event.APP_INITIALIZED_EVENT, () => { event.addListener(event.APP_INITIALIZED_EVENT, async () => {
require('./metamgr').init(); require('./metadata/factory').init();
await require('./blockchain').init();
require('./middlewares/factory').init(); require('./middlewares/factory').init();
require('./controllers/factory').init(); require('./controllers/factory').init();
require('./models/factory').init(); require('./models/factory').init();

View File

@ -1,17 +1,11 @@
const controllers = {}; const controllers = {};
function add(name) { function add(name) {
controllers[name] = require('./' + name); controllers[name] = require(`./${name}`);
controllers[name].init(); controllers[name].init();
} }
function init() { function init() {
add('proxy');
}
function create(name) {
} }
exports.init = init; exports.init = init;
exports.create = create;

View File

@ -1,41 +0,0 @@
const https = require('https');
const app = require('j7/app');
const utils = require('j7/utils');
const http = require('j7/http');
const serviceFactory = require('../services/factory');
async function get(session) {
const seqId = session.request('seq_id');
const targetUrl = session.request('target_url');
const cbUrl = session.request('cb_url');
const reqJson = session.requestToJson();
new Promise(async (resolve) => {
const params = utils.jsonDecode(session.request('params'));
const {err, data} = await http.get(targetUrl, params);
const rspJson = {
'errcode': 0,
'errmsg': '',
'seq_id': seqId,
'req_json': reqJson,
'data': data
};
if (err) {
rspJson['errcode'] = 1;
rspJson['errmsg'] = '' + err;
}
console.log('data', data);
console.log('rspJson:' + utils.jsonEncode(rspJson));
await http.get(cbUrl, rspJson);
});
session.rspOk();
};
async function post(session) {
}
function init() {
app.registerHandler('Proxy', 'get', get);
app.registerHandler('Proxy', 'post', post);
}
exports.init = init;

View File

@ -0,0 +1,8 @@
const utils = require('j7/utils');
const basewrap = require('./basewrap');
class Config extends basewrap.BaseWrap {
}
module.exports = Config;

View File

@ -0,0 +1,8 @@
const utils = require('j7/utils');
const basewrap = require('./basewrap');
class Contract extends basewrap.BaseWrap {
}
module.exports = Contract;

View File

@ -0,0 +1,59 @@
const assert = require('assert');
const utils = require('j7/utils');
const bcutils = require('j7/bcutils');
const basewrap = require('./basewrap');
const factory = require('./factory');
const HERO_TYPE = 3;
const GUN_TYPE = 7;
const MATERIAL_TYPE = 10;
const BLIND_BOX_TYPE = 12;
const MATERIAL_CHIP_SUBTYPE = 3;
class Item extends basewrap.BaseWrap {
getNftType() {
switch (this['type']) {
case HERO_TYPE:
{
return bcutils.HERO_TYPE;
}
break;
case GUN_TYPE:
{
return bcutils.EQUIP_TYPE;
}
break;
case MATERIAL_TYPE:
{
if (this['sub_type'] == MATERIAL_CHIP_SUBTYPE) {
return bcutils.CHIP_TYPE;
} else {
return bcutils.NONE_TYPE;
}
}
break;
case BLIND_BOX_TYPE:
{
return bcutils.BLIND_BOX_TYPE;
}
break;
default:
{
return bcutils.NONE_TYPE;
}
break;
}
return bcutils.NONE_TYPE;
}
randLuckBox(tokenType) {
const itemId = factory.callMetaStatic('LuckyBox', 'randLuckBox', this['id'], tokenType);
assert(itemId > 0);
return itemId;
}
}
module.exports = Item;

View File

@ -0,0 +1,52 @@
const assert = require('assert');
const utils = require('j7/utils');
const bcutils = require('j7/bcutils');
const basewrap = require('./basewrap');
class LuckyBox extends basewrap.BaseWrap {
static idTypeHash = {
}
_init0(factory) {
const key = this['box_id'] + '_' + this['type'];
if (!utils.hasKey(LuckyBox.idTypeHash, key)) {
LuckyBox.idTypeHash[key] = {
'total_space': 0,
'items': []
};
}
assert(this['weight'] > 0);
LuckyBox.idTypeHash[key]['total_space'] += this['weight'];
LuckyBox.idTypeHash[key]['items'].push({
'space': LuckyBox.idTypeHash[key]['total_space'],
'meta': this
});
const itemMeta = factory.getMetaByKey('Item', this['item_id']);
assert(itemMeta);
assert(itemMeta.getNftType() != bcutils.NONE_TYPE);
assert(itemMeta.getNftType() == this['type']);
}
static randLuckBox(boxId, tokenType) {
const key = boxId + '_' + tokenType;
if (!utils.hasKey(LuckyBox.idTypeHash, key)) {
console.log(1111, key);
return 0;
}
const data = LuckyBox.idTypeHash[key];
assert(data['total_space'] > 0);
const rand = utils.randRange(0, data['total_space'] - 1);
for (let i in data['items']) {
const item = data['items'][i];
if (rand < item['space']) {
return item['meta']['item_id'];
}
}
return 0;
}
}
module.exports = LuckyBox;

View File

@ -0,0 +1,8 @@
const utils = require('j7/utils');
const basewrap = require('./basewrap');
class MarketDb extends basewrap.BaseWrap {
}
module.exports = MarketDb;

View File

@ -0,0 +1,57 @@
const utils = require('j7/utils');
const bcutils = require('j7/bcutils');
const basewrap = require('./basewrap');
const metaFactory = require('./factory');
class Present extends basewrap.BaseWrap {
_init0 () {
const items = this['items'].split('|');
let totalSpace = 0;
this._items = [];
items.forEach((tmpStr) => {
const item = tmpStr.split(':');
item[1] = parseInt(item[1]);
totalSpace += item[1];
const itemMeta = metaFactory.getMetaByKey('Item', item[0]);
if (!itemMeta) {
throw 'itemMeta is null' + this;
}
const nftType = itemMeta.getNftType();
if (nftType == bcutils.NONE_TYPE) {
throw 'itemMeta nft type is null' + this;
}
this._items.push({
'space': totalSpace,
'itemId': item[0],
'tokenType': nftType
});
});
if (!(totalSpace > 0)) {
throw 'total not > 0' + this
}
this._totalSpace = totalSpace;
}
randItem() {
const rand = utils.randRange(0, this._totalSpace);
for (let i in this._items) {
const item = this._items[i];
if (rand < item['space']) {
return item;
}
}
return null;
}
getCount() {
return this['quantity'];
}
getTags() {
return this['tags'];
}
}
module.exports = Present;

View File

@ -0,0 +1,8 @@
const utils = require('j7/utils');
const basewrap = require('./basewrap');
class PresentList extends basewrap.BaseWrap {
}
module.exports = PresentList;

View File

@ -0,0 +1,8 @@
const utils = require('j7/utils');
const basewrap = require('./basewrap');
class Web3 extends basewrap.BaseWrap {
}
module.exports = Web3;

View File

@ -2,8 +2,16 @@ const utils = require('j7/utils');
class BaseWrap { class BaseWrap {
constructor(json) { #writeLock = false;
constructor(json, metaClass) {
this._json = json; this._json = json;
//this._metaClass = metaClass;
this._metaName = metaClass['wrapClassName'];
}
lock() {
//this.#writeLock = true;
} }
_getHandler() { _getHandler() {
@ -29,16 +37,21 @@ class BaseWrap {
} }
return prop in obj ? obj[prop] : null; return prop in obj ? obj[prop] : null;
}, },
set: () => { set: (obj, prop, val) => {
console.log(111111); if (this.#writeLock) {
console.log(111111);
} else {
Reflect.set(obj, prop, val);
}
return true;
} }
}; };
} }
} getMetaName() {
return this._metaName;
class Config extends BaseWrap { }
} }
exports.Config = Config; exports.BaseWrap = BaseWrap;

View File

@ -0,0 +1,219 @@
const app = require('j7/app');
const utils = require('j7/utils');
const log = require('j7/log');
const metaClassList = [];
const metaClasses = {};
function registerMetaClass(fileName, primKey, wrapClass, aliseName = '') {
const metaClass = {
'fileName' : fileName,
'primKey' : primKey,
'wrapClassName': wrapClass,
'wrapClass': require('./' + wrapClass),
'rawList' : [],
'rawHash' : {},
'wrapList' : [],
'wrapHash' : {},
'aliseName': aliseName
};
metaClassList.push(metaClass);
if (aliseName) {
metaClasses[aliseName] = metaClass;
} else {
metaClasses[wrapClass] = metaClass;
}
}
function onAllLoadPost(classList) {
for (let i = 0; i < 3; ++i) {
classList.forEach((metaClass) => {
metaClass['wrapList'].forEach((item) => {
if (item['_init' + i]) {
item['_init' + i](exports);
}
});
});
}
classList.forEach((metaClass) => {
metaClass['wrapList'].forEach((item) => {
item.lock();
});
});
}
function loadMeta(metaClass) {
const json = utils.readJsonFromFile(metaClass['fileName']);
if (!json) {
throw new Error('读取配置' + metaClass['fileName'] + '失败');
}
if (Array.isArray(json)) {
metaClass['rawList'] = json;
} else {
metaClass['rawList'].push(json);
}
let idx = 0;
metaClass['rawList'].forEach(function (item) {
const wrapOjb = new metaClass['wrapClass'](item, metaClass);
const wrapProxy = new Proxy(wrapOjb, wrapOjb._getHandler());
metaClass['wrapList'].push(wrapProxy);
if (metaClass['primKey'] == '') {
metaClass['rawHash'][idx] = item;
metaClass['wrapHash'][idx] = wrapProxy;
} else {
metaClass['rawHash'][item[metaClass['primKey']]] = item;
metaClass['wrapHash'][item[metaClass['primKey']]] = wrapProxy;
}
++idx;
});
}
function load() {
metaClassList.forEach((metaClass) => {
loadMeta(metaClass);
//log.debug(utils.jsonEncode(metaClass));
});
onAllLoadPost(metaClassList);
}
function init() {
let configDir = './config/';
if (utils.isOnlineEnv()) {
configDir = '../config/';
} else if (utils.getArgv('env') == 'dev'){
configDir = './config_dev/';
}
console.log(configDir, utils.getArgv('env'));
let resDir = './res/';
if (utils.isOnlineEnv()) {
resDir = '../res/';
} else if (utils.getArgv('env') == 'dev'){
resDir = './res_dev/';
}
registerMetaClass(configDir + 'config.json',
'',
'Config'
);
registerMetaClass(configDir + 'web3.json',
'',
'Web3'
);
registerMetaClass(configDir + 'contract.json',
'',
'Contract'
);
registerMetaClass(configDir + 'marketdb_mysql.json',
'',
'MarketDb'
);
registerMetaClass(configDir + 'present_list.json',
'',
'PresentList'
);
registerMetaClass(resDir + 'item@item.json',
'id',
'Item'
);
registerMetaClass(resDir + 'luckyBox@luckyBox.json',
'id',
'LuckyBox'
);
load();
{
const classList = [];
getMetaByKey('PresentList', '0')['list'].forEach((item) => {
registerMetaClass(resDir + item + '@present.json',
'id',
'Present',
'Present' + item
);
const metaClass = getMetaClass('Present' + item);
loadMeta(metaClass);
classList.push(metaClass);
});
onAllLoadPost(classList);
}
{
traverseMetaList('MarketDb', (dbConf, idx) => {
app.registerDb('MarketDb' + idx, dbConf);
});
}
}
function getMetaClass(name) {
return utils.hasKey(metaClasses, name) ? metaClasses[name] : null;
}
function getMetaByKey(name, key) {
const metaClass = getMetaClass(name);
return metaClass && key in metaClass['wrapHash'] ? metaClass['wrapHash'][key] : null;
}
function getMetaList(name) {
const metaClass = getMetaClass(name);
return metaClass ? metaClass['wrapList'] : null;
}
function callMetaStatic(name, method, ...args) {
const metaClass = getMetaClass(name);
return metaClass['wrapClass'][method](...args);
}
function traverseMetaList(name, cb) {
const metaList = getMetaList(name);
if (metaList) {
for (let i = 0; i < metaList.length; ++i) {
if (!cb(metaList[i], i, metaList.length)) {
break;
}
}
}
}
function getWeb3Conf() {
return getMetaByKey('Web3', '0');
}
function getContracts() {
return getMetaList('Contract');
}
function getContractByName(name) {
return getMetaByKey('Contract', name);
}
function getContractByAddress(address) {
let contract = null;
getContracts().forEach((item) => {
if (item['address'] == address) {
contract = item;
}
});
return contract;
}
function getUserAddress() {
return getWeb3Conf()['user_address'];
}
function getPrivateKey() {
return getWeb3Conf()['private_key'];
}
exports.init = init;
exports.getMetaByKey = getMetaByKey;
exports.traverseMetaList = traverseMetaList;
exports.callMetaStatic = callMetaStatic;
exports.getWeb3Conf = getWeb3Conf;
exports.getContracts = getContracts;
exports.getContractByName = getContractByName;
exports.getContractByAddress = getContractByAddress;
exports.getUserAddress = getUserAddress;
exports.getPrivateKey = getPrivateKey;

View File

@ -1,80 +0,0 @@
const app = require('j7/app');
const utils = require('j7/utils');
const log = require('j7/log');
const metawrap = require('./metawrap');
const metaClasses = [];
const MT_CONFIG = 0;
function registerMetaClass(fileName, idx, primKey, wrapClass) {
metaClasses.push({
'fileName' : fileName,
'idx' : idx,
'primKey' : primKey,
'wrapClass': wrapClass,
'rawList' : [],
'rawHash' : {},
'wrapList' : [],
'wrapHash' : {},
});
}
function load() {
metaClasses.forEach(function (metaClass) {
const json = utils.readJsonFromFile(metaClass['fileName']);
if (!json) {
throw new Error('读取配置' + metaClass['fileName'] + '失败');
}
if (Array.isArray(json)) {
metaClass['rawList'] = json;
} else {
metaClass['rawList'].push(json);
}
let idx = 0;
metaClass['rawList'].forEach(function (item) {
const wrapOjb = new metawrap[metaClass['wrapClass']](item);
const wrapProxy = new Proxy(wrapOjb, wrapOjb._getHandler());
metaClass['wrapList'] = wrapProxy;
if (metaClass['primKey'] == '') {
metaClass['rawHash'][idx] = item;
metaClass['wrapHash'][idx] = wrapProxy;
} else {
metaClass['rawHash'][item[metaClass['primKey']]] = item;
metaClass['wrapHash'][item[metaClass['primKey']]] = wrapProxy;
}
++idx;
});
//log.debug(utils.jsonEncode(metaClass));
});
}
function init() {
let configDir = './config/';
if (utils.isOnlineEnv()) {
configDir = '../config/';
}
registerMetaClass(configDir + 'config.json',
MT_CONFIG,
'',
'Config'
);
load();
}
function getMetaClass(metaIdx) {
return metaIdx >= 0 && metaIdx < metaClasses.length ? metaClasses[metaIdx] : null;
}
function getMetaByKey(metaIdx, key) {
const metaClass = getMetaClass(metaIdx);
return metaClass && key in metaClass['wrapHash'] ? metaClass['wrapHash'][key] : null;
}
function getMetaList(metaIdx) {
const metaClass = getMetaClass(metaIdx);
return metaClass ? metaClass['rawList'] : null;
}
exports.init = init;

View File

@ -1,10 +0,0 @@
const app = require('j7/app');
async function authenticate(session) {
}
function init() {
app.addMiddleware('authenticate', authenticate);
}
exports.init = init;

View File

@ -1,12 +1,5 @@
const middlewares = {};
function add(name) {
middlewares[name] = require('./' + name);
middlewares[name].init();
}
function init() { function init() {
add('authenticate');
} }
exports.init = init; exports.init = init;

File diff suppressed because it is too large Load Diff

View File

@ -1,11 +1,15 @@
{ {
"name": "httpgate_svr", "name": "web3helper",
"version": "1.0.0", "version": "1.0.0",
"description": "", "description": "",
"private": true, "private": true,
"scripts": {}, "scripts": {},
"dependencies": { "dependencies": {
"j7": "file:../../third_party/j7", "j7": "file:../../third_party/j7",
"nodejs-websocket": "^1.7.2" "@metamask/eth-sig-util": "^4.0.0",
"express": "^4.17.2",
"log4js": "~6.3.0",
"mysql": "~2.18.1",
"web3": "^1.6.1"
} }
} }

View File

@ -1,4 +1,3 @@
const channelDef = require('j7/channel')
const services = {}; const services = {};
function add(clsNames, modName) { function add(clsNames, modName) {
@ -8,12 +7,17 @@ function add(clsNames, modName) {
'clsName': clsName, 'clsName': clsName,
'modName': modName, 'modName': modName,
'class': modClass 'class': modClass
}; }
}); });
} }
function init() { function init() {
create('WsServer', null).init(); add(['Present'], 'present');
add(['EventCenter'], 'event_center');
add(['ExecConfirmOwner'], 'exec_confirm_owner');
add(['EventProcess'], 'event_process');
create('Present', null).init();
create('EventCenter', null).init();
} }
function create(name, session) { function create(name, session) {

View File

@ -1,5 +1,9 @@
const utils = require('j7/utils'); const utils = require('j7/utils');
const app = require('j7/app'); const app = require('j7/app');
const error = require('j7/error');
const modelsFactory = require('./models/factory');
const serviceFactory = require('./services/factory');
const metaFactory = require('./metadata/factory');
class Session { class Session {
@ -7,6 +11,18 @@ class Session {
this.req = req; this.req = req;
this.rsp = rsp; this.rsp = rsp;
this.nowTime = utils.getUtcTime(); this.nowTime = utils.getUtcTime();
this.useConns = {};
}
async destory() {
if (this.user) {
await this.user.destory();
}
for (let key in this.useConns) {
this.useConns[key].release();
}
//console.log(new Error().stack);
this.useConns = null;
} }
getNowTime() { getNowTime() {
@ -37,6 +53,10 @@ class Session {
this.rspErr(errCode, errMsg); this.rspErr(errCode, errMsg);
} }
throwError(errCode, errMsg) {
throw new error.InternalError(errCode, errMsg);
}
request(name, defVal = null) { request(name, defVal = null) {
return name in this.req.query ? this.req.query[name] : defVal; return name in this.req.query ? this.req.query[name] : defVal;
} }
@ -45,6 +65,64 @@ class Session {
return utils.jsonEncode(this.req.query); return utils.jsonEncode(this.req.query);
} }
async getMarketDb() {
const idx = 0;
const dbKey = 'MarketDb' + idx;
if (this.useConns[dbKey]) {
return this.useConns[dbKey];
}
const {err, conn} = await app.getDbConn(dbKey);
if (err) {
console.log(err);
}
//console.log(new Error().stack);
if (!err && conn) {
this.useConns[dbKey] = conn;
}
return conn;
}
createModel(name) {
return modelsFactory.create(name, this);
}
createService(name) {
return serviceFactory.create(name, this);
}
getMeta(name, key) {
return metaFactory.getMetaByKey(name, key);
}
callMetaStatic(name, method, ...args) {
return metaFactory.callMetaStatic(name, method, this, ...args);
}
traverseMetaList(name, cb) {
return metaFactory.traverseMetaList(name, cb);
}
callMetaFactory(name, ...args) {
return metaFactory[name](this, ...args);
}
async marketConn(method, ...args) {
const conn = await this.getMarketDb();
const ret = await conn[method](...args);
if (ret.err){
this.throwError(500, 'internal error');
log.error(ret.err);
return;
}
if (utils.hasKey(ret, 'row')) {
return ret['row'];
} else if (utils.hasKey(ret, 'rows')) {
return ret['rows'];
} else {
return null;
}
}
} }
module.exports = Session; module.exports = Session;