This commit is contained in:
aozhiwei 2023-06-12 15:08:40 +08:00
parent 6a78f31a13
commit 4531802f13
22 changed files with 0 additions and 2624 deletions

View File

@ -1,155 +0,0 @@
const log = require('j7/log');
const app = require('j7/app');
const bcutils = require('j7/bcutils');
const utils = require('j7/utils');
const j7event = require('j7/event');
const metaFactory = require('../../metadata/factory');
const C = require('../../C');
const gameapi = require('../gameapi');
/*
// 操作成功的事件
event BuyTransactionBatch(
address indexed buyer,
address[3] addresses,
uint256 price,
uint256[] ids,
uint256[] amounts
);
*/
class Activate1155Nft {
async start(instance, conn, event) {
this.instance = instance;
this.conn = conn;
this.event = event;
console.log('Activate1155Nft', event);
const blockNumber = event['blockNumber'];
const returnValues = event['returnValues'];
const transId = returnValues['nonce'];
const buyer = returnValues['buyer'];
if (returnValues['ids'].length != 1) {
this.throwError('error returnValues:' + utils.jsonEncode(returnValues));
return;
}
const tokenId = returnValues['ids'][0];
const params = bcutils.extractParamsFromTransId(transId);
if (!params || params.length != 3) {
this.throwError('error transId:' + transId);
return;
}
const itemUniId = params[0];
const subParams1 = bcutils.extractSubParams(params[1]);
var level = subParams1[0];
let itemId = Math.max(1, subParams1[1]);
if (itemId == 0 ||
itemId == 1) {
itemId = 130011;
}
await this.mintNft(
transId,
bcutils.toNormalAddress(buyer),
blockNumber,
tokenId,
itemUniId,
itemId,
level);
j7event.emitEvent(C.CREATE_EXEC_CONFIRM_BALANCE_EVENT,
'chipInstance', //this.instance['name'],
bcutils.toNormalAddress(buyer),
[tokenId],
0);
await gameapi.confirmTransactionDb(this.instance, transId);
}
async mintNft(transId, owner, blockNumber, tokenId, itemUniId, itemId, level) {
const itemMeta = metaFactory.getMetaByKey('Item', itemId);
if (!itemMeta) {
this.throwError('activate1155nft error transId:1');
return;
}
const tokenType = itemMeta.getNftType();
if (tokenType != bcutils.CHIP_TYPE) {
this.throwError('activate1155nft error transId:2');
return;
}
await this.updateGameDbInfo(transId, itemUniId, itemId, tokenId, tokenType, level);
const {err, row} = await this.conn.ormSelectOne(
't_nft1155',
[
['owner_address', bcutils.toNormalAddress(owner)],
['token_id', tokenId],
]
);
if (err) {
log.error('processEvent:' + err);
throw 'processEvent:' + err;
}
if (!row) {
const nowTime = utils.getUtcTime();
const fieldList = [
['token_id', tokenId],
['item_id', itemId],
['owner_address', bcutils.toNormalAddress(owner)],
['createtime', nowTime],
['modifytime', nowTime],
];
const {err} = await this.conn.insert(
't_nft1155',
fieldList
);
if (err) {
log.error('processEvent:' + err);
throw 'processEvent:' + err;
}
}
}
async updateGameDbInfo(transId, itemUniId, itemId, tokenId, tokenType, level) {
const {err, conn} = await app.getDbConn('GameDb0');
if (err) {
this.throwError('gamedb connection err:' + err);
return;
}
const nowTime = utils.getUtcTime();
try {
try {
await conn.upsert(
't_chip',
[
['token_id', tokenId],
],
[
],
[
['token_id', tokenId],
['item_id', itemId],
['item_num', 1],
['chip_grade', level],
['createtime', nowTime],
['modifytime', nowTime],
]
);
} finally{
conn.release();
}
} catch (e) {
this.throwError('updateGameDbInfo err:' + e);
return;
}
}
throwError(err) {
const errMsg = 'processActivate1155NftEvent:' +
utils.jsonEncode(this.instance) +
' err:' + err;
throw errMsg;
}
}
module.exports = Activate1155Nft;

View File

@ -1,169 +0,0 @@
const log = require('j7/log');
const app = require('j7/app');
const bcutils = require('j7/bcutils');
const utils = require('j7/utils');
const j7event = require('j7/event');
const metaFactory = require('../../metadata/factory');
const C = require('../../C');
const gameapi = require('../gameapi');
/*
操作成功的事件
event TokenMinted(
address indexed to,
uint256 indexed nonce,
uint256 startTime,
uint256[] ids
)
*/
class Activate721Nft {
async start(instance, conn, event) {
console.log('Activate721Nft', event);
const blockNumber = event['blockNumber'];
const returnValues = event['returnValues'];
const transId = returnValues['nonce'];
const to = returnValues['to'];
if (returnValues['ids'].length != 1) {
this.throwError('error returnValues:' + utils.jsonEncode(returnValues));
return;
}
const tokenId = returnValues['ids'][0];
const params = bcutils.extractParamsFromTransId(transId);
if (!params || params.length != 3) {
this.throwError(instance, 'activate721nft error transId:' + transId);
return;
}
const itemUniId = params[0];
const itemId = params[1];
console.log(params);
await this.mintNft(
instance,
conn,
transId,
bcutils.toNormalAddress(to),
blockNumber,
tokenId,
itemUniId,
itemId);
await gameapi.confirmTransactionDb(this.instance, transId);
}
async mintNft(instance, conn, transId, owner, blockNumber, tokenId, itemUniId, itemId) {
const itemMeta = metaFactory.getMetaByKey('Item', itemId);
if (!itemMeta) {
this.throwError(instance, 'activate721nft error transId:1');
return;
}
const tokenType = itemMeta.getNftType();
if (tokenType == bcutils.NONE_TYPE) {
this.throwError(instance, 'activate721nft error transId:2');
return;
}
await this.updateGameDbInfo(instance, conn, transId, itemUniId, itemId, tokenId, tokenType);
const {err, row} = await conn.ormSelectOne(
't_nft',
[
['token_id', tokenId],
]
);
if (err) {
log.error('processEvent:' + err);
throw 'processEvent:' + err;
}
if (!row) {
const nowTime = utils.getUtcTime();
const fieldList = [
['token_id', tokenId],
['token_type', tokenType],
['item_id', itemId],
['game_id', 2006],
['owner_address', bcutils.toNormalAddress(owner)],
['creator_address', bcutils.toNormalAddress(owner)],
['confirm_block_number', blockNumber],
['createtime', nowTime],
['modifytime', nowTime],
];
const {err} = await conn.insert(
't_nft',
fieldList
);
if (err) {
log.error('processEvent:' + err);
throw 'processEvent:' + err;
}
try {
j7event.emitEvent(C.CREATE_EXEC_CONFIRM_OWNER_EVENT, tokenId);
} catch (err) {
log.warning('processEvent:' + err);
}
}
}
async updateGameDbInfo(instance, marketDbConn, transId, itemUniId, itemId, tokenId, tokenType) {
const {err, conn} = await app.getDbConn('GameDb0');
if (err) {
this.throwError(instance, 'gamedb connection err:' + err);
return;
}
try {
try {
let tblName = '';
switch (tokenType) {
case bcutils.HERO_TYPE:
{
tblName = 't_hero';
}
break;
case bcutils.EQUIP_TYPE:
{
tblName = 't_gun';
}
break;
case bcutils.CHIP_TYPE:
{
tblName = 't_chip';
}
break;
default:
{
}
break;
}
if (!tblName) {
this.throwError(instance, 'error token_type:' + tokenType);
return;
}
await conn.update(
tblName,
[
['idx', itemUniId],
],
[
['token_id', tokenId],
['!account_id', () => {
return 'null';
}],
]
);
} finally{
conn.release();
}
} catch (e) {
this.throwError(instance, 'updateGameDbInfo err:' + e);
return;
}
}
throwError(instance, err) {
const errMsg = 'processActivate721NftEvent:' + utils.jsonEncode(instance) + ' err:' + err;
throw errMsg;
}
}
module.exports = Activate721Nft;

View File

@ -1,117 +0,0 @@
const log = require('j7/log');
const bcutils = require('j7/bcutils');
const utils = require('j7/utils');
const j7event = require('j7/event');
const metaFactory = require('../../metadata/factory');
const C = require('../../C');
class ActivateProcess {
async start(instance, conn, event) {
const {err, row} = await conn.ormSelectOne(
't_activate_event',
[
['txhash', event['transactionHash']],
['log_index', event['logIndex']],
]
);
if (err) {
this.throwError(instance, err);
}
if (!row) {
const blockNumber = event['blockNumber'];
const returnValues = event['returnValues'];
const oldTokenId = returnValues['nftOld'];
const newTokenId = returnValues['nftNew'];
const fieldList = [
['old_token_id', oldTokenId],
['old_token_type', returnValues['nftType']],
['new_token_id', newTokenId],
['txhash', event['transactionHash']],
['block_number', blockNumber],
['log_index', event['logIndex']],
['_to', bcutils.toNormalAddress(returnValues['to'])],
['raw_data', utils.jsonEncode(event)],
['createtime', utils.getUtcTime()],
['modifytime', utils.getUtcTime()],
];
{
const {err, row} = await conn.ormSelectOne(
't_nft',
[
['token_id', oldTokenId],
]
);
if (err) {
log.error('processEvent:' + err);
throw 'processEvent:' + err;
} else {
await this.mintNft(
conn,
bcutils.toNormalAddress(returnValues['to']),
blockNumber,
newTokenId,
row['token_type'],
row['item_id'],
row['tags']);
}
}
const {err} = await conn.insert(
't_activate_event',
fieldList
);
if (err) {
this.throwError(instance, err);
}
}
}
async mintNft(conn, owner, blockNumber, tokenId, tokenType, itemId, tags) {
const {err, row} = await conn.ormSelectOne(
't_nft',
[
['token_id', tokenId],
]
);
if (err) {
log.error('processEvent:' + err);
throw 'processEvent:' + err;
}
if (!row) {
const nowTime = utils.getUtcTime();
const fieldList = [
['token_id', tokenId],
['token_type', tokenType],
['item_id', itemId],
['tags', tags],
['game_id', 2006],
['owner_address', bcutils.toNormalAddress(owner)],
['creator_address', bcutils.toNormalAddress(owner)],
['confirm_block_number', blockNumber],
['createtime', nowTime],
['modifytime', nowTime],
];
const {err} = await conn.insert(
't_nft',
fieldList
);
if (err) {
log.error('processEvent:' + err);
throw 'processEvent:' + err;
}
try {
j7event.emitEvent(C.CREATE_EXEC_CONFIRM_OWNER_EVENT, tokenId);
} catch (err) {
log.warning('processEvent:' + err);
}
}
}
throwError(instance, err) {
const errMsg = 'processActivateEvent:' + utils.jsonEncode(instance) + ' err:' + err;
throw errMsg;
}
}
module.exports = ActivateProcess;

View File

@ -1,115 +0,0 @@
const log = require('j7/log');
const bcutils = require('j7/bcutils');
const utils = require('j7/utils');
const j7event = require('j7/event');
const metaFactory = require('../../metadata/factory');
const C = require('../../C');
class BoxOpenedProcess {
async start(instance, conn, event) {
const {err, row} = await conn.ormSelectOne(
't_boxopened_event',
[
['txhash', event['transactionHash']],
['log_index', event['logIndex']],
]
);
if (err) {
this.throwError(instance, err);
}
if (!row) {
const blockNumber = event['blockNumber'];
const returnValues = event['returnValues'];
const fieldList = [
['box_token_id', returnValues['boxId']],
['txhash', event['transactionHash']],
['block_number', blockNumber],
['log_index', event['logIndex']],
['_to', bcutils.toNormalAddress(returnValues['to'])],
['raw_data', utils.jsonEncode(event)],
['createtime', utils.getUtcTime()],
['modifytime', utils.getUtcTime()],
];
for (let i = 0; i < 3; ++i) {
const id = returnValues['ids'][i];
const type = returnValues['types'][i];
if (id != '0') {
fieldList.push(
['token_id' + (i + 1), id],
);
fieldList.push(['token_type' + (i + 1), type]),
await this.mintNft(
conn,
bcutils.toNormalAddress(returnValues['to']),
blockNumber,
id,
type);
}
}
const {err} = await conn.insert(
't_boxopened_event',
fieldList
);
if (err) {
this.throwError(instance, err);
}
}
}
async mintNft(conn, owner, blockNumber, tokenId, tokenType) {
const {err, row} = await conn.ormSelectOne(
't_nft',
[
['token_id', tokenId],
]
);
if (err) {
log.error('processEvent:' + err);
throw 'processEvent:' + err;
}
if (!row) {
const itemMeta = metaFactory.getMetaByKey('Item', 110001);
if (!itemMeta) {
return;
}
const nftItemId = itemMeta.randLuckBox(tokenType);
if (nftItemId > 0) {
const nowTime = utils.getUtcTime();
const fieldList = [
['token_id', tokenId],
['token_type', tokenType],
['item_id', nftItemId],
['tags', tokenType == bcutils.HERO_TYPE ? '1' : 0],
['game_id', 2006],
['owner_address', bcutils.toNormalAddress(owner)],
['creator_address', bcutils.toNormalAddress(owner)],
['confirm_block_number', blockNumber],
['createtime', nowTime],
['modifytime', nowTime],
];
const {err} = await conn.insert(
't_nft',
fieldList
);
if (err) {
log.error('processEvent:' + err);
throw 'processEvent:' + err;
}
try {
j7event.emitEvent(C.CREATE_EXEC_CONFIRM_OWNER_EVENT, tokenId);
} catch (err) {
log.warning('processEvent:' + err);
}
}
}
}
throwError(instance, err) {
const errMsg = 'processBoxOpenedEvent:' + utils.jsonEncode(instance) + ' err:' + err;
throw errMsg;
}
}
module.exports = BoxOpenedProcess;

View File

@ -1,52 +0,0 @@
const log = require('j7/log');
const app = require('j7/app');
const bcutils = require('j7/bcutils');
const utils = require('j7/utils');
const event = require('j7/event');
const metaFactory = require('../../metadata/factory');
const C = require('../../C');
const factory = require('../factory');
const gameapi = require('../gameapi');
/*
event ChipPlugin(
address nft,
uint256 nftId,
address chip,
uint256[] ids
);
*/
class ChipPlugin {
async start(instance, conn, event) {
console.log('chipSucc', event);
this.instance = instance;
this.conn = conn;
this.event = event;
const blockNumber = event['blockNumber'];
const returnValues = event['returnValues'];
const transId = returnValues['nonce'];
const nftAddress = returnValues['nft'];
const chipAddress = returnValues['chip'];
const tokenId = returnValues['nftId'];
try {
const newRequest = new factory.create('ExecConfirmPlugin', null);
await newRequest.init('nftChipLockerInstance', nftAddress, chipAddress, tokenId);
} catch (e) {
this.throwError(e);
}
await gameapi.confirmTransactionDb(this.instance, transId);
}
throwError(err) {
const errMsg = 'chipPluginEvent:' + utils.jsonEncode(this.instance) + ' err:' + err;
throw errMsg;
}
}
module.exports = ChipPlugin;

View File

@ -1,52 +0,0 @@
const log = require('j7/log');
const app = require('j7/app');
const bcutils = require('j7/bcutils');
const utils = require('j7/utils');
const event = require('j7/event');
const metaFactory = require('../../metadata/factory');
const C = require('../../C');
const factory = require('../factory');
const gameapi = require('../gameapi');
/*
event ChipUnplug(
address nft,
uint256 nftId,
address chip,
uint256[] ids
);
*/
class ChipUnplug {
async start(instance, conn, event) {
console.log('evolveSucc', event);
this.instance = instance;
this.conn = conn;
this.event = event;
const blockNumber = event['blockNumber'];
const returnValues = event['returnValues'];
const transId = returnValues['nonce'];
const nftAddress = returnValues['nft'];
const chipAddress = returnValues['chip'];
const tokenId = returnValues['nftId'];
try {
const newRequest = new factory.create('ExecConfirmPlugin', null);
await newRequest.init('nftChipLockerInstance', nftAddress, chipAddress, tokenId);
} catch (e) {
this.throwError(e);
}
await gameapi.confirmTransactionDb(this.instance, transId);
}
throwError(err) {
const errMsg = 'chipUnplugEvent:' + utils.jsonEncode(this.instance) + ' err:' + err;
throw errMsg;
}
}
module.exports = ChipUnplug;

View File

@ -1,35 +0,0 @@
const log = require('j7/log');
const app = require('j7/app');
const bcutils = require('j7/bcutils');
const utils = require('j7/utils');
const event = require('j7/event');
const metaFactory = require('../../metadata/factory');
const C = require('../../C');
/*
// 失败的event
event TokenEvolveFail(
address indexed to,
bytes signature,
string reason,
bytes byteReason
);
*/
class EvolveFail {
async start(instance, conn, event) {
console.log('EvolveFail', event);
this.instance = instance;
this.conn = conn;
this.event = event;
}
throwError(err) {
const errMsg = 'evolveFailEvent:' + utils.jsonEncode(this.instance) + ' err:' + err;
throw errMsg;
}
}
module.exports = EvolveFail;

View File

@ -1,110 +0,0 @@
const log = require('j7/log');
const app = require('j7/app');
const bcutils = require('j7/bcutils');
const utils = require('j7/utils');
const event = require('j7/event');
const metaFactory = require('../../metadata/factory');
const C = require('../../C');
const gameapi = require('../gameapi');
/*
// 成功的event
// logic/EvolveFactory
event TokenEvolved(address indexed owner, uint256[] tokenIds);
*/
class EvolveSucc {
async start(instance, conn, event) {
console.log('evolveSucc', event);
this.instance = instance;
this.conn = conn;
this.event = event;
const blockNumber = event['blockNumber'];
const returnValues = event['returnValues'];
const transId = returnValues['nonce'];
const owner = returnValues['owner'];
if (returnValues['tokenIds'].length < 2) {
this.throwError('tokenIds length error:' + utils.jsonEncode(returnValues));
return;
}
const tokenId = returnValues['tokenIds'][0];
const tokenId1 = returnValues['tokenIds'][0];
const tokenId2 = returnValues['tokenIds'][1];
const params = bcutils.extractParamsFromTransId(transId);
if (!params || params.length != 3) {
this.throwError('error transId:' + transId);
return;
}
const tokenType = params[0];
await this.notifyGameApi(transId, tokenId, tokenType, tokenId1, tokenId2);
await gameapi.confirmTransactionDb(this.instance, transId);
}
async notifyGameApi(transId, tokenId, tokenType, tokenId1, tokenId2) {
console.log(transId, tokenId, tokenType);
let a = '';
switch (Number(tokenType)) {
case bcutils.HERO_TYPE:
{
a = 'heroUpgradeQuality';
}
break;
case bcutils.EQUIP_TYPE:
{
a = 'gunUpgradeQuality';
}
break;
case bcutils.CHIP_TYPE:
{
a = 'chipUpgradeGrade';
}
break;
default:
{
throw 'error token type';
}
break;
}
while (true) {
try {
const {err, data} = await gameapi.callApi
(
'Callback',
a,
{
'trans_id': transId,
'token_id': tokenId,
'token_id1': tokenId1,
'token_id2': tokenId2,
}
);
if (err) {
throw err;
}
console.log(data);
if (!data) {
throw 'data is empty';
}
if (data['errcode'] == 0) {
return;
}
} catch (e) {
log.error(e);
}
await utils.sleep(3000 + utils.randRange(500, 1500));
}
}
throwError(err) {
const errMsg = 'evolveSuccEvent:' + utils.jsonEncode(this.instance) + ' err:' + err;
throw errMsg;
}
}
module.exports = EvolveSucc;

View File

@ -1,57 +0,0 @@
const log = require('j7/log');
const bcutils = require('j7/bcutils');
const utils = require('j7/utils');
class Nft1155TransferProcess {
async start(instance, conn, event) {
if ([
'TransferSingle',
'TransferBatch'
].indexOf(instance['eventName']) < 0) {
this.throwError(instance, 'error eventName');
return;
}
const {err, row} = await conn.ormSelectOne(
't_nft1155_transfer',
[
['txhash', event['transactionHash']],
['log_index', event['logIndex']],
]
);
if (err) {
this.throwError(instance, err);
return;
}
if (!row) {
const returnValues = event['returnValues'];
const {err} = await conn.insert(
't_nft1155_transfer',
[
['event_name', instance['eventName']],
['instance_name', instance['name']],
['txhash', event['transactionHash']],
['block_number', event['blockNumber']],
['log_index', event['logIndex']],
['_from', bcutils.toNormalAddress(returnValues['from'])],
['_to', bcutils.toNormalAddress(returnValues['to'])],
['return_values', utils.jsonEncode(returnValues)],
['raw_data', utils.jsonEncode(event)],
['createtime', utils.getUtcTime()],
['modifytime', utils.getUtcTime()],
]
);
if (err) {
this.throwError(instance, err);
}
}
};
throwError(instance, err) {
const errMsg = 'processNft1155TransferEvent:' + utils.jsonEncode(instance) + ' err:' + err;
throw errMsg;
}
}
module.exports = Nft1155TransferProcess;

View File

@ -1,47 +0,0 @@
const log = require('j7/log');
const bcutils = require('j7/bcutils');
const utils = require('j7/utils');
class NftTransferProcess {
async start(instance, conn, event) {
const {err, row} = await conn.ormSelectOne(
't_nft_transfer',
[
['txhash', event['transactionHash']],
['log_index', event['logIndex']],
]
);
if (err) {
this.throwError(instance, err);
}
if (!row) {
const returnValues = event['returnValues'];
const {err} = await conn.insert(
't_nft_transfer',
[
['token_id', returnValues['tokenId']],
['txhash', event['transactionHash']],
['block_number', event['blockNumber']],
['log_index', event['logIndex']],
['_from', bcutils.toNormalAddress(returnValues['from'])],
['_to', bcutils.toNormalAddress(returnValues['to'])],
['raw_data', utils.jsonEncode(event)],
['createtime', utils.getUtcTime()],
['modifytime', utils.getUtcTime()],
]
);
if (err) {
this.throwError(instance, err);
}
}
};
throwError(instance, err) {
const errMsg = 'processNftTransferEvent:' + utils.jsonEncode(instance) + ' err:' + err;
throw errMsg;
}
}
module.exports = NftTransferProcess;

View File

@ -1,32 +0,0 @@
const log = require('j7/log');
const app = require('j7/app');
const bcutils = require('j7/bcutils');
const utils = require('j7/utils');
const event = require('j7/event');
const metaFactory = require('../../metadata/factory');
const C = require('../../C');
/*
// 失败事件
event TokenMintFail(
address indexed to,
bytes signature,
string reason,
bytes byteReason
);
*/
class ShardMintFail {
async start(instance, conn, event) {
console.log('ShardMintFail', event);
}
throwError(err) {
const errMsg = 'shardMintFailEvent:' + utils.jsonEncode(this.instance) + ' err:' + err;
throw errMsg;
}
}
module.exports = ShardMintFail;

View File

@ -1,50 +0,0 @@
const log = require('j7/log');
const app = require('j7/app');
const bcutils = require('j7/bcutils');
const utils = require('j7/utils');
const event = require('j7/event');
const metaFactory = require('../../metadata/factory');
const C = require('../../C');
const gameapi = require('../gameapi');
/*
// 成功事件
// logic/MinterFactory.sol
event TokenMintedBatch(
address contractAddress,
address indexed to,
uint256[] ids,
uint256[] amounts
);
*/
class ShardMintSucc {
async start(instance, conn, event) {
console.log('ShardMintSucc', event);
this.instance = instance;
this.conn = conn;
this.event = event;
const blockNumber = event['blockNumber'];
const returnValues = event['returnValues'];
const transId = returnValues['nonce'];
const params = bcutils.extractParamsFromTransId(transId);
if (!params || params.length != 3) {
this.throwError('error transId:' + transId);
return;
}
await gameapi.confirmTransactionDb(this.instance, transId);
}
throwError(err) {
const errMsg = 'shardMintEvent:' + utils.jsonEncode(this.instance) + ' err:' + err;
throw errMsg;
}
}
module.exports = ShardMintSucc;

View File

@ -1,32 +0,0 @@
const log = require('j7/log');
const app = require('j7/app');
const bcutils = require('j7/bcutils');
const utils = require('j7/utils');
const event = require('j7/event');
const metaFactory = require('../../metadata/factory');
const C = require('../../C');
/*
// 失败事件
event TokenMintFail(
address indexed to,
bytes signature,
string reason,
bytes byteReason
);
*/
class ShardMixFail {
async start(instance, conn, event) {
console.log('ShardMixFail', event);
}
throwError(err) {
const errMsg = 'shardMixFailEvent:' + utils.jsonEncode(this.instance) + ' err:' + err;
throw errMsg;
}
}
module.exports = ShardMixFail;

View File

@ -1,180 +0,0 @@
const log = require('j7/log');
const app = require('j7/app');
const bcutils = require('j7/bcutils');
const utils = require('j7/utils');
const j7event = require('j7/event');
const metaFactory = require('../../metadata/factory');
const C = require('../../C');
const gameapi = require('../gameapi');
/*
//成功事件
// logic/MinterFactory.sol
event TokenMinted(
address contractAddress,
address to,
uint256 indexed tokenId
);
*/
class ShardMixSucc {
async start(instance, conn, event) {
console.log('ShardMixSucc', event);
this.instance = instance;
this.conn = conn;
this.event = event;
const blockNumber = event['blockNumber'];
const returnValues = event['returnValues'];
const transId = returnValues['nonce'];
const owner = returnValues['to'];
const tokenId = returnValues['tokenId'];
const params = bcutils.extractParamsFromTransId(transId);
if (!params || params.length != 3) {
this.throwError('error transId:' + transId);
return;
}
const subParams1 = bcutils.extractSubParams(params[0]);
let itemId = subParams1[0];
const tokenType = Number(subParams1[1]);
if (!(tokenType == bcutils.HERO_TYPE ||
tokenType == bcutils.EQUIP_TYPE
)) {
this.throwError('error tokenType:' + tokenType);
return;
}
if (itemId == 0) {
const heroId = metaFactory.callMetaStatic('Item', 'randHero', transId);
const gunId = metaFactory.callMetaStatic('Item', 'randGun', transId);
const heroMeta = metaFactory.getMetaByKey('Item', heroId);
const gunMeta = metaFactory.getMetaByKey('Item', gunId);
console.log(heroId, gunId);
switch (tokenType) {
case bcutils.HERO_TYPE:
{
if (!heroMeta) {
this.throwError('error randHero');
}
itemId = heroMeta['id'];
}
break;
case bcutils.EQUIP_TYPE:
{
if (!gunMeta) {
this.throwError('error randEquip');
}
itemId = gunMeta['id'];
}
break;
default:
{
this.throwError('error tokenType:' + tokenType);
return;
}
break;
}
} else {
const itemMeta = metaFactory.getMetaByKey('Item', itemId);
if (itemMeta.getNftType() != tokenType) {
this.throwError('error tokenType:' + tokenType);
return;
}
}
await this.mintNft(transId, owner, blockNumber, tokenId, tokenType, itemId);
j7event.emitEvent(C.CREATE_EXEC_CONFIRM_OWNER_EVENT, tokenId);
await gameapi.confirmTransactionDb(this.instance, transId);
}
async mintNft(transId, owner, blockNumber, tokenId, tokenType, itemId) {
try {
const nowTime = utils.getUtcTime();
{
const {err} = await this.conn.upsert(
't_nft',
[
['token_id', tokenId],
],
[
],
[
['token_id', tokenId],
['token_type', tokenType],
['item_id', itemId],
['game_id', 2006],
['owner_address', bcutils.toNormalAddress(owner)],
['creator_address', bcutils.toNormalAddress(owner)],
['confirm_block_number', blockNumber],
['createtime', nowTime],
['modifytime', nowTime],
]
);
if (err) {
this.throwError('error upsert t_nft:' + err);
return;
}
}
const {err, conn} = await app.getDbConn('GameDb0');
if (err) {
this.throwError('gamedb connection err:' + err);
return;
}
let tblName = '';
let fields = [];
switch (tokenType) {
case bcutils.HERO_TYPE:
{
tblName = 't_hero';
fields = [
['token_id', tokenId],
['hero_id', itemId],
['createtime', nowTime],
['modifytime', nowTime],
];
}
break;
case bcutils.EQUIP_TYPE:
{
tblName = 't_gun';
fields = [
['token_id', tokenId],
['gun_id', itemId],
['createtime', nowTime],
['modifytime', nowTime],
];
}
break;
default:
{
}
break;
}
if (!tblName) {
this.throwError('error token_type2:' + tokenType);
return;
}
await conn.upsert(
tblName,
[
['token_id', tokenId],
],
[
],
fields
);
} catch (err) {
this.throwError('mintNft:' + err);
}
}
throwError(err) {
const errMsg = 'shardMixEvent:' + utils.jsonEncode(this.instance) + ' err:' + err;
throw errMsg;
}
}
module.exports = ShardMixSucc;

View File

@ -1,485 +0,0 @@
const app = require('j7/app');
const utils = require('j7/utils');
const bcutils = require('j7/bcutils');
const log = require('j7/log');
const event = require('j7/event');
const BaseService = require('./baseservice');
const bc = require('../blockchain');
const C = require('../C');
const factory = require('./factory');
const BoxOpenedProcess = require('./_internal/boxopened_process');
const ActivateProcess = require('./_internal/activate_process');
const NftTransferProcess = require('./_internal/nft_transfer_process');
const Nft1155TransferProcess = require('./_internal/nft1155_transfer_process');
const Activate721NftProcess = require('./_internal/activate721nft_process');
const Activate1155NftProcess = require('./_internal/activate1155nft_process');
const ShardMixSuccProcess = require('./_internal/shard_mix_succ_process');
const ShardMixFailProcess = require('./_internal/shard_mix_fail_process');
const ShardMintSuccProcess = require('./_internal/shard_mint_succ_process');
const ShardMintFailProcess = require('./_internal/shard_mint_fail_process');
const EvolveSuccProcess = require('./_internal/evolve_succ_process');
const EvolveFailProcess = require('./_internal/evolve_fail_process');
const ChipPluginProcess = require('./_internal/chip_plugin_process');
const ChipUnplugProcess = require('./_internal/chip_unplug_process');
const LIMIT_COUNT = 100;
class EventCenter extends BaseService {
instances = [
{
'name': 'HEROInstance',
'eventName': 'Transfer',
},
{
'name': 'WEAPONInstance',
'eventName': 'Transfer',
},
// {
// 'name': 'chipInstance',
// 'eventName': 'Transfer',
// },
// {
// 'name': 'luckboxInstance',
// 'eventName': 'Transfer',
// }
];
instances1155 = [
{
'name': 'chipInstance',
'eventName': 'TransferSingle',
},
{
'name': 'chipInstance',
'eventName': 'TransferBatch',
},
{
'name': 'shardInstance',
'eventName': 'TransferSingle',
},
{
'name': 'shardInstance',
'eventName': 'TransferBatch',
},
];
// boxInstance = {
// 'name': 'boxproxyInstance',
// 'eventName': 'BoxOpened',
// };
// activateInstance = {
// 'name': 'activateproxyInstance',
// 'eventName': 'LogNFTActivate',
// };
activate721NftInstance = {
'name': 'UserMinterFactoryInstance',
'eventName': 'TokenMinted',
};
activate1155NftInstance = {
'name': 'nftMallInstance',
'eventName': 'BuyTransactionBatch',
};
shardMixByUserFailInstance = {
'name': 'userFactoryInstance',
'eventName': 'TokenMintFail',
};
shardMixByUserSuccInstance = {
'name': 'factoryInstance',
'eventName': 'TokenMinted',
};
// shardMintByUserFailInstance = {
// 'name': 'userFactoryInstance',
// 'eventName': 'TokenMintFail',
// };
shardMintByUserSuccInstance = {
'name': 'factoryInstance',
'eventName': 'TokenMintedBatch',
};
evolveFailInstance = {
'name': 'userProxyInstance',
'eventName': 'TokenEvolveFail',
};
evolveSuccInstance = {
'name': 'proxyInstance',
'eventName': 'TokenEvolved',
};
chipPluginInstance = {
'name': 'nftChipLockerInstance',
'eventName': 'ChipPlugin',
};
chipUnplugInstance = {
'name': 'nftChipLockerInstance',
'eventName': 'ChipUnplug',
};
async init() {
this.lastIdx = 0;
this.pendingConfirmOwnerHash = {};
this.pendingConfirmBalanceHash = {};
const {err, conn} = await app.getDbConn('MarketDb0');
if (err) {
throw 'db error:' + err;
}
this.conn = conn;
{
event.addListener(C.DESTORY_EXEC_CONFIRM_OWNER_EVENT, (tokenId) => {
log.info('destory confirm owner:' + tokenId);
try {
if (utils.getVal(this.pendingConfirmOwnerHash, tokenId)) {
delete this.pendingConfirmOwnerHash[tokenId];
}
} catch(err) {
log.error('destory confirm owner:' + err);
}
});
event.addListener(C.CREATE_EXEC_CONFIRM_OWNER_EVENT, (tokenId) => {
log.info('create confirm owner:' + tokenId);
try {
this.addConfirmOwnerRequest(tokenId);
} catch(err) {
log.error('create confirm owner:' + err);
}
});
}
{
event.addListener
(C.DESTORY_EXEC_CONFIRM_BALANCE_EVENT,
(instanceName, address, tokenId) => {
log.info('destory confirm balance:' + instanceName + ' ' + address + tokenId);
try {
const key = this.genBalanceKey(instanceName, address, tokenId);
if (utils.getVal(this.pendingConfirmBalanceHash, key)) {
delete this.pendingConfirmBalanceHash[key];
}
} catch(err) {
log.error('destory confirm balance:' + err);
}
});
event.addListener
(C.CREATE_EXEC_CONFIRM_BALANCE_EVENT,
(instanceName, address, tokenIds, idx) => {
log.info('create confirm balance:' + instanceName + ' ' + address + utils.jsonEncode(tokenIds));
try {
this.addConfirmBalanceRequest(instanceName, address, tokenIds, idx);
} catch(err) {
log.error('create confirm balance:' + err);
}
});
}
this.confirmOwner();
this.confirmBalance();
//this.addConfirmBalanceRequest('shardInstance', '0xffcf8fdee72ac11b5c542428b35eef5769c409f0', [1], 0);
await this.initEventProcess();
}
async initEventProcess() {
const initInstance = (instance) => {
instance['pullCount'] = 0;
instance['eventCount'] = 0;
instance['fromBlock'] = 0;
instance['toBlock'] = 0;
instance['currBlock'] = 0;
};
const allInstances = [];
{
this.instances.forEach((item) => {
allInstances.push(item);
});
// this.instances1155.forEach((item) => {
// allInstances.push(item);
// });
//allInstances.push(this.boxInstance);
//allInstances.push(this.activateInstance);
allInstances.push(this.activate721NftInstance);
//allInstances.push(this.activate1155NftInstance);
//allInstances.push(this.shardMixByUserFailInstance);
//allInstances.push(this.shardMixByUserSuccInstance);
//allInstances.push(this.shardMintByUserFailInstance);
//allInstances.push(this.shardMintByUserSuccInstance);
//allInstances.push(this.evolveFailInstance);
//allInstances.push(this.evolveSuccInstance);
//allInstances.push(this.chipPluginInstance);
//allInstances.push(this.chipUnplugInstance);
console.log(allInstances);
{
const instanceHash = {};
allInstances.forEach((item) => {
const key = item['name'] + '.' + item['eventName'];
if (utils.hasKey(instanceHash, key)) {
console.log(key);
throw '!!!!duplicate instance';
}
instanceHash[key] = item;
});
}
allInstances.forEach((item) => {
initInstance(item);
});
let count = 0;
const outputLog = async () => {
while (true) {
log.info(++count + '-------------------------------------------------------------');
log.info('pendingConfirmOwnerHash.size:' +
Object.keys(this.pendingConfirmOwnerHash).length +
'pendingConfirmBalanceHash.size:' +
Object.keys(this.pendingConfirmBalanceHash).length);
allInstances.forEach((item) => {
log.info(utils.jsonEncode(item));
});
await utils.sleep(1000 * 10);
}
};
setTimeout(outputLog, 1000 * 3);
}
{
this.instances.forEach(async (item) => {
factory.create('EventProcess', null)
.init(this.conn, item, async (event) => {
await (new NftTransferProcess()).start(item, this.conn, event);
});
});
}
// {
// this.instances1155.forEach(async (item) => {
// factory.create('EventProcess', null)
// .init(this.conn, item, async (event) => {
// await (new Nft1155TransferProcess()).start(item, this.conn, event);
// });
// });
// }
/*
{
factory.create('EventProcess', null)
.init(this.conn, this.boxInstance, async (event) => {
await (new BoxOpenedProcess()).start(this.boxInstance, this.conn, event);
});
}
{
factory.create('EventProcess', null)
.init(this.conn, this.activateInstance, async (event) => {
await (new ActivateProcess()).start(this.activateInstance, this.conn, event);
});
}*/
{
factory.create('EventProcess', null)
.init(this.conn, this.activate721NftInstance, async (event) => {
await (new Activate721NftProcess()).start(this.activate721NftInstance, this.conn, event);
});
}
// {
// factory.create('EventProcess', null)
// .init(this.conn, this.activate1155NftInstance, async (event) => {
// await (new Activate1155NftProcess()).start(this.activate1155NftInstance, this.conn, event);
// });
// }
// {
// factory.create('EventProcess', null)
// .init(this.conn, this.shardMixByUserFailInstance, async (event) => {
// await (new ShardMixFailProcess()).start(this.shardMixByUserFailInstance, this.conn, event);
// });
// }
// {
// factory.create('EventProcess', null)
// .init(this.conn, this.shardMixByUserSuccInstance, async (event) => {
// await (new ShardMixSuccProcess()).start(this.shardMixByUserSuccInstance, this.conn, event);
// });
// }
{
/*factory.create('EventProcess', null)
.init(this.conn, this.shardMintByUserFailInstance, async (event) => {
await (new ShardMintFailProcess()).start(this.shardMintByUserFailInstance, this.conn, event);
});
*/
}
// {
// factory.create('EventProcess', null)
// .init(this.conn, this.shardMintByUserSuccInstance, async (event) => {
// await (new ShardMintSuccProcess()).start(this.shardMintByUserSuccInstance, this.conn, event);
// });
// }
// {
// factory.create('EventProcess', null)
// .init(this.conn, this.evolveFailInstance, async (event) => {
// await (new EvolveFailProcess()).start(this.evolveFailInstance, this.conn, event);
// });
// }
// {
// factory.create('EventProcess', null)
// .init(this.conn, this.evolveSuccInstance, async (event) => {
// await (new EvolveSuccProcess()).start(this.evolveSuccInstance, this.conn, event);
// });
// }
// {
// factory.create('EventProcess', null)
// .init(this.conn, this.chipPluginInstance, async (event) => {
// await (new ChipPluginProcess()).start(this.chipPluginInstance, this.conn, event);
// });
// }
// {
// factory.create('EventProcess', null)
// .init(this.conn, this.chipUnplugInstance, async (event) => {
// await (new ChipUnplugProcess()).start(this.chipUnplugInstance, this.conn, event);
// });
// }
}
async addConfirmOwnerRequest(tokenId) {
const pendingRequest = utils.getVal(this.pendingConfirmOwnerHash, tokenId);
if (!pendingRequest) {
const newRequest = new factory.create('ExecConfirmOwner', null);
this.pendingConfirmOwnerHash[tokenId] = newRequest;
newRequest.init(tokenId);
return;
} else {
pendingRequest.addTryCount();
}
}
async addConfirmBalanceRequest(instanceName, address, tokenIds, idx) {
const syncTokenIds = [];
tokenIds.forEach(
(element) => {
const tokenId = element;
const key = this.genBalanceKey(instanceName, address, tokenId);
const pendingRequest = utils.getVal(this.pendingConfirmBalanceHash, key);
if (pendingRequest) {
pendingRequest.addTryCount(tokenId);
} else {
syncTokenIds.push(tokenId);
}
}
);
if (syncTokenIds.length > 0) {
const newRequest = new factory.create('ExecConfirmBalance', null);
syncTokenIds.forEach(
(element) => {
const tokenId = element;
const key = this.genBalanceKey(instanceName, address, tokenId);
this.pendingConfirmBalanceHash[key] = newRequest;
}
);
newRequest.init(instanceName, address, syncTokenIds, idx);
}
}
async confirmOwner() {
let maxIdx = 0;
while (true) {
{
const {err, rows} = await this.conn.execQuery(
'SELECT * FROM t_nft_transfer WHERE `idx` > ? AND ' +
'`owner_confirmed` = 0 LIMIT ' + LIMIT_COUNT,
[this.lastIdx]);
if (!err) {
for (let i in rows) {
const row = rows[i];
this.addConfirmOwnerRequest(row['token_id']);
if (row['idx'] > this.lastIdx) {
this.lastIdx = row['idx'];
}
}
if (rows.length < 1 && this.lastIdx + LIMIT_COUNT < maxIdx) {
this.lastIdx += LIMIT_COUNT;
continue;
}
}
}
{
const {err, row} = await this.conn.execQueryOne(
'SELECT max(idx) max_idx FROM t_nft_transfer', []);
if (!err && row['max_idx'] != null) {
maxIdx = row['max_idx'];
}
}
while (Object.keys(this.pendingConfirmOwnerHash).length > 50) {
await utils.sleep(1000 + utils.randRange(500, 1500));
}
await utils.sleep(2000 + utils.randRange(500, 1500));
}
}
async confirmBalance() {
let maxIdx = 0;
let lastIdx = 0;
while (true) {
{
const {err, rows} = await this.conn.execQuery(
'SELECT * FROM t_nft1155_transfer WHERE `idx` > ? AND ' +
'`owner_confirmed` = 0 LIMIT ' + LIMIT_COUNT,
[lastIdx]);
if (!err) {
for (let i in rows) {
const row = rows[i];
const instanceName = row['instance_name'];
const tokenIds = this.extractTokenIds(row);
console.log('confirmBalance', instanceName, tokenIds, row);
if (bcutils.isValidAddress(row['_from'])) {
this.addConfirmBalanceRequest(instanceName, row['_from'], tokenIds, row['idx']);
}
if (bcutils.isValidAddress(row['_to'])) {
this.addConfirmBalanceRequest(instanceName, row['_to'], tokenIds, row['idx']);
}
if (row['idx'] > lastIdx) {
lastIdx = row['idx'];
}
}
if (rows.length < 1 && lastIdx + LIMIT_COUNT < maxIdx) {
lastIdx += LIMIT_COUNT;
continue;
}
}
}
{
const {err, row} = await this.conn.execQueryOne(
'SELECT max(idx) max_idx FROM t_nft1155_transfer', []);
if (!err && row['max_idx'] != null) {
maxIdx = row['max_idx'];
}
}
while (Object.keys(this.pendingConfirmBalanceHash).length > 50) {
await utils.sleep(1000 + utils.randRange(500, 1500));
}
await utils.sleep(2000 + utils.randRange(500, 1500));
}
}
extractTokenIds(row) {
let tokenIds = [];
try {
const returnValues = utils.jsonDecode(row['return_values']);
const eventName = row['event_name'];
console.log(returnValues, eventName);
if (eventName == 'TransferSingle') {
tokenIds.push(returnValues['id']);
} else if (eventName == 'TransferBatch') {
tokenIds = returnValues['ids'];
}
} catch (e) {
}
return tokenIds;
}
genBalanceKey(instanceName, address, tokenId) {
return instanceName + '!' + address.toString() + '!' + tokenId;
}
}
module.exports = EventCenter;

View File

@ -1,220 +0,0 @@
const app = require('j7/app');
const utils = require('j7/utils');
const bcutils = require('j7/bcutils');
const log = require('j7/log');
const bc = require('../blockchain');
const BaseService = require('./baseservice');
class EventProcess extends BaseService {
async init(conn, instance, cb) {
this.conn = conn;
this.instance = instance;
this.cb = cb;
this.lastBlockNumber = 0;
await this.start();
}
async start() {
while (true) {
await this.pullEvent();
await utils.sleep(8000 + utils.randRange(500, 1500));
}
}
async pullEvent() {
const logClass = this.getInstanceName() + ' pullEvent:';
while (true) {
await bc.lockQuery();
try {
const fromBlock = await this.getFromBlock();
const toBlock = await this.calcToBlock(fromBlock);
if (toBlock > fromBlock) {
const events = await bc[this.getInstanceName()].getPastEvents(
this.instance['eventName'],
{
fromBlock: fromBlock,
toBlock: toBlock,
},
);
this.instance['fromBlock'] = fromBlock;
this.instance['toBlock'] = toBlock;
this.instance['currBlock'] = bc.getCurrBlockNumber();
this.instance['eventCount'] += events.length;
if (events.length > 0) {
console.log(events);
await this.updateFirstBlockNumber(fromBlock);
}
await this.processEvents(events, toBlock);
await this.saveLastBlockNumber(toBlock);
}
++this.instance['pullCount'];
return;
} catch (err) {
log.error(logClass + err);
await utils.sleep(1000 + utils.randRange(10, 2000));
} finally {
await bc.unlockQuery();
}
}
}
getInstanceName() {
return this.instance['name'];
}
async processEvents(events, toBlock) {
for (let i in events) {
while (true) {
try {
await this.cb(events[i]);
await this.saveToDb(events[i]);
break;
} catch (err) {
log.error(err);
}
await utils.sleep(8000 + utils.randRange(500, 1500));
}
}
}
async getFromBlock() {
const logClass = this.getInstanceName() + ' getFromBlock:';
const firstBlockNumber = await bc.getFirstBlockNumber();
while (this.lastBlockNumber < 1) {
try {
const {err, row} = await this.conn.ormSelectOne(
't_parameter',
[
['name', this.getBlockNumberDbName()]
]
);
if (!err) {
if (row) {
this.lastBlockNumber = Number(row['value']);
} else {
this.lastBlockNumber = firstBlockNumber;
}
}
console.log(logClass, this.lastBlockNumber, bc.getCurrBlockNumber());
while (this.lastBlockNumber + 8 > bc.getCurrBlockNumber()) {
await utils.sleep(1000 + utils.randRange(500, 1500));
}
continue;
} catch (err) {
log.log(err);
}
await utils.sleep(5000 + utils.randRange(500, 1500));
}
return this.lastBlockNumber + 1;
}
async calcToBlock(fromBlock) {
const currBlockNumber = bc.getCurrBlockNumber();
const distanceBlock = currBlockNumber - fromBlock - 8;
const batchBlockNum = 888;
if (distanceBlock > 0) {
if (distanceBlock > batchBlockNum) {
return fromBlock + batchBlockNum;
} else {
return fromBlock + distanceBlock;
}
}
return fromBlock;
}
async saveLastBlockNumber(blockNumber) {
const logClass = 'event_process.saveLastBlockNumber';
while (true) {
const {err} = await this.conn.upsert(
't_parameter',
[
['name', this.getBlockNumberDbName()]
],
[
['value', blockNumber],
],
[
['name', this.getBlockNumberDbName()],
['value', blockNumber],
]
);
if (!err) {
break;
}
log.error(logClass + err);
await utils.sleep(5000 + utils.randRange(500, 1500));
}
this.lastBlockNumber = blockNumber;
}
async updateFirstBlockNumber(blockNumber) {
const logClass = 'event_process.updateFirstBlockNumber';
while (true) {
const {err} = await this.conn.upsert(
't_parameter',
[
['name', this.getFirstBlockNumberDbName()]
],
[
['!value', () => {
return 'LEAST(CONVERT(value, unsigned), ' + blockNumber + ')';
}],
],
[
['name', this.getFirstBlockNumberDbName()],
['value', blockNumber],
]
);
if (!err) {
break;
}
log.error(logClass + err);
await utils.sleep(5000 + utils.randRange(500, 1500));
}
}
async saveToDb(event) {
const logClass = 'event_process.saveToDb';
while (true) {
const nowTime = utils.getUtcTime();
const returnValues = event['returnValues'];
const {err} = await this.conn.upsert(
't_blockchain_event',
[
['txhash', event['transactionHash']],
['log_index', event['logIndex']],
],
[
],
[
['instance_name', this.instance['name']],
['event_name', this.instance['eventName']],
['txhash', event['transactionHash']],
['log_index', event['logIndex']],
['block_number', event['blockNumber']],
['raw_data', utils.jsonEncode(event)],
['return_values', utils.jsonEncode(returnValues)],
['createtime', utils.getUtcTime()],
['modifytime', utils.getUtcTime()],
]
);
if (!err) {
break;
}
log.error(logClass + err);
await utils.sleep(5000 + utils.randRange(500, 1500));
}
}
getBlockNumberDbName() {
return this.instance['name'] + '.' + this.instance['eventName'] + '.last_block_number';
}
getFirstBlockNumberDbName() {
return this.instance['name'] + '.' + this.instance['eventName'] + '.first_block_number';
}
}
module.exports = EventProcess;

View File

@ -1,163 +0,0 @@
const bcutils = require('j7/bcutils');
const utils = require('j7/utils');
const app = require('j7/app');
const log = require('j7/log');
const event = require('j7/event');
const bc = require('../blockchain');
const C = require('../C');
class ExecConfirmBalance {
async init(instanceName, address, tokenIds, idx) {
try {
this.instanceName = instanceName;
this.address = address;
this.tryCount = 1;
this.tokenIds = tokenIds;
this.idx = idx;
await this.doConfirm();
} catch (err) {
log.error('ExecConfirmBalance:' + this.tokenIds.toString() + ' err:' + err);
} finally {
this.destory();
}
}
destory() {
this.tokenIds.forEach
(
(element) => {
const tokenId = element;
event.emitEvent(C.DESTORY_EXEC_CONFIRM_BALANCE_EVENT, this.instanceName, this.address, tokenId);
}
);
}
addTryCount(tokenId) {
++this.tryCount;
}
async doConfirm() {
while (true) {
await bc.mustBeActive();
const oldTryCount = this.tryCount;
const oldBlockNumber = bc.getCurrBlockNumber();
let oldBalances = await this.getBalances();
while (oldBlockNumber + 8 > bc.getCurrBlockNumber()) {
await utils.sleep(1000 + utils.randRange(0, 500));
}
await bc.mustBeActive();
const newBlockNumber = bc.getCurrBlockNumber();
let newBalances = await this.getBalances();
if (this.isSameBlances(oldBalances, newBalances)) {
const ok = await this.updateConfirmed(newBalances, oldBlockNumber);
if (ok && oldTryCount == this.tryCount) {
break;
}
}
await utils.sleep(1000 + utils.randRange(500, 1500));
}
}
async getBalances() {
while (true) {
await bc.lockQuery();
try {
const address = [];
this.tokenIds.forEach(
(element) => {
address.push(this.address);
}
);
let banlances = await bc[this.instanceName].methods.balanceOfBatch
(
address,
this.tokenIds
).call();
if (banlances.length == banlances.length) {
return banlances;
}
} catch (err) {
log.error(err);
} finally {
await bc.unlockQuery();
}
await utils.sleep(5000 + utils.randRange(1500, 2500));
}
}
isSameBlances(oldBalances, newBalances) {
if (oldBalances.length != newBalances.length) {
return false;
}
for (let i = 0; i < oldBalances.length; ++i) {
if (oldBalances[i] != newBalances[i]) {
return false;
}
}
return true;
}
async updateConfirmed(newBalances, blockNumber) {
const {err, conn} = await app.getDbConn('MarketDb0');
if (err) {
log.error('updateConfirmed:' + this.tokenId + ' err:' + err);
return false;
}
try {
const nowTime = utils.getUtcTime();
for (let i = 0; i < this.tokenIds.length; ++i) {
const tokenId = this.tokenIds[i];
const balance = newBalances[i];
{
const {err} = await conn.upsert(
't_nft1155',
[
['owner_address', this.address],
['token_id', tokenId]
],
[
['balance', balance],
['!confirm_count', () => {
return 'confirm_count + 1';
}],
['confirm_block_number', blockNumber]
],
[
['owner_address', this.address],
['token_id', tokenId],
['balance', balance],
['confirm_count', 1],
['confirm_block_number', blockNumber],
['createtime', nowTime],
['modifytime', nowTime],
]);
if (err) {
log.error('updateConfirmed:' + tokenId + ' err:' + err);
return false;
}
}
}
{
const {err} = await conn.execScript(
'UPDATE t_nft1155_transfer SET `owner_confirmed`=1 ' +
'WHERE idx=?',
[
this.idx
]);
if (err) {
log.error('updateConfirmed balance' + ' err:' + err);
return false;
}
}
} finally {
conn.release();
}
return true;
}
}
module.exports = ExecConfirmBalance;

View File

@ -1,173 +0,0 @@
const bcutils = require('j7/bcutils');
const utils = require('j7/utils');
const app = require('j7/app');
const log = require('j7/log');
const event = require('j7/event');
const bc = require('../blockchain');
const C = require('../C');
class ExecConfirmOwner {
async init(tokenId) {
try {
this.tryCount = 1;
this.tokenId = tokenId;
this.nftDb = await this.getNftDb(tokenId);
if (!this.nftDb) {
return;
}
this.addTryCount();
await this.doConfirm();
} catch (err) {
log.error('ExecConfirmOwner:' + this.tokenId + ' err:' + err);
} finally {
this.destory();
}
}
destory() {
event.emitEvent(C.DESTORY_EXEC_CONFIRM_OWNER_EVENT, this.tokenId);
}
addTryCount() {
++this.tryCount;
}
async doConfirm() {
while (true) {
await bc.mustBeActive();
const oldTryCount = this.tryCount;
const oldBlockNumber = bc.getCurrBlockNumber();
let oldOwner = await this.getOwner();
while (oldBlockNumber + 8 > bc.getCurrBlockNumber()) {
await utils.sleep(1000 + utils.randRange(0, 500));
}
await bc.mustBeActive();
const newBlockNumber = bc.getCurrBlockNumber();
let newOwner = await this.getOwner();
if (oldOwner == newOwner) {
const ok = await this.updateConfirmed(newOwner, oldBlockNumber);
if (ok && oldTryCount == this.tryCount) {
break;
}
}
await utils.sleep(1000 + utils.randRange(500, 1500));
}
}
getInstanceName() {
switch (this.nftDb['token_type']) {
case bcutils.HERO_TYPE:
{
return 'heroInstance';
}
break;
case bcutils.EQUIP_TYPE:
{
return 'equipInstance';
}
break;
case bcutils.CHIP_TYPE:
{
return 'chipInstance';
}
break;
case bcutils.BLIND_BOX_TYPE:
{
return 'luckboxInstance';
}
break;
}
}
async getNftDb(tokenId) {
const {err, conn} = await app.getDbConn('MarketDb0');
if (err) {
return null;
}
try {
const {err, row} = await conn.ormSelectOne(
't_nft',
[
['token_id', tokenId]
]);
return row;
} finally {
conn.release();
}
}
async getOwner() {
const instanceName = this.getInstanceName();
log.info('getOwner:' + instanceName +
' tryCount:' + this.tryCount +
' token_id:' + this.tokenId);
while (true) {
await bc.lockQuery();
try {
let owner = await bc[instanceName].methods.ownerOf(this.tokenId).call();
return owner;
} catch (err) {
const reason = utils.getVal(err, 'reason');
if (reason == 'ERC721: owner query for nonexistent token') {
return '';
}
if (err == 'Error: Returned error: VM Exception while processing transaction: revert ERC721: owner query for nonexistent token' ||
err == 'Error: Returned error: execution reverted: ERC721: owner query for nonexistent token') {
return '';
}
log.error(err);
} finally {
await bc.unlockQuery();
}
await utils.sleep(5000 + utils.randRange(1500, 2500));
}
}
async updateConfirmed(newOwner, blockNumber) {
const {err, conn} = await app.getDbConn('MarketDb0');
if (err) {
log.error('updateConfirmed:' + this.tokenId + ' err:' + err);
return false;
}
try {
{
const {err} = await conn.update(
't_nft',
[
['token_id', this.tokenId]
],
[
['owner_address', bcutils.toNormalAddress(newOwner)],
['confirm_count', this.nftDb['confirm_count'] + 1],
['confirm_block_number', blockNumber]
]);
if (err) {
log.error('updateConfirmed:' + this.tokenId + ' err:' + err);
return false;
}
}
{
const {err} = await conn.execScript(
'UPDATE t_nft_transfer SET `owner_confirmed`=1 ' +
'WHERE token_id=? AND block_number < ?',
[
this.tokenId,
blockNumber
]);
if (err) {
log.error('updateConfirmed:' + this.tokenId + ' err:' + err);
return false;
}
}
} finally {
conn.release();
}
return true;
}
}
module.exports = ExecConfirmOwner;

View File

@ -1,147 +0,0 @@
const bcutils = require('j7/bcutils');
const utils = require('j7/utils');
const app = require('j7/app');
const log = require('j7/log');
const event = require('j7/event');
const bc = require('../blockchain');
const C = require('../C');
/*
function pluginedChips(address nft, address chip, uint256 tokenId)
external
view
returns(uint256[] memory)
{
return chipPlugined[nft][chip][tokenId].values();
}
*/
class ExecConfirmPlugin {
async init(instanceName, nftAddress, chipAddress, tokenId) {
try {
this.instanceName = instanceName;
this.nftAddress = nftAddress;
this.chipAddress = chipAddress;
this.tokenId = tokenId;
await this.doConfirm();
} catch (err) {
log.error('ExecConfirmPlugin:' + this.tokenId() + ' err:' + err);
} finally {
this.destory();
}
}
destory() {
}
async doConfirm() {
while (true) {
await bc.mustBeActive();
const oldBlockNumber = bc.getCurrBlockNumber();
let oldChips = await this.getChips();
while (oldBlockNumber + 8 > bc.getCurrBlockNumber()) {
await utils.sleep(1000 + utils.randRange(0, 500));
}
await bc.mustBeActive();
const newBlockNumber = bc.getCurrBlockNumber();
let newChips = await this.getChips();
if (this.isSameChips(oldChips, newChips)) {
const ok = await this.updateConfirmed(newChips, oldBlockNumber);
if (ok) {
break;
}
}
await utils.sleep(1000 + utils.randRange(500, 1500));
}
}
async getChips() {
while (true) {
await bc.lockQuery();
try {
let chips = await bc[this.instanceName].methods.pluginedChips
(
this.nftAddress,
this.chipAddress,
this.tokenId
).call();
return chips;
} catch (err) {
log.error(err);
} finally {
await bc.unlockQuery();
}
await utils.sleep(5000 + utils.randRange(1500, 2500));
}
}
isSameChips(oldChips, newChips) {
if (oldChips.length != newChips.length) {
return false;
}
for (let i = 0; i < oldChips.length; ++i) {
if (oldChips[i] != newChips[i]) {
return false;
}
}
return true;
}
async updateConfirmed(newChips, blockNumber) {
const {err, conn} = await app.getDbConn('MarketDb0');
if (err) {
log.error('updateConfirmedPlugin:' + this.tokenId + ' err:' + err);
return false;
}
try {
const nowTime = utils.getUtcTime();
{
const chipFields = [
['chip1', ''],
['chip2', ''],
['chip3', ''],
['chip4', ''],
];
for (let i = 0; i < newChips.length; ++i) {
if (newChips[i] != 0) {
chipFields[i][1] = newChips[i];
}
}
const {err} = await conn.upsert(
't_chip_plugin',
[
['token_id', this.tokenId]
],
[
['modifytime', nowTime],
['!confirm_count', () => {
return 'confirm_count + 1';
}],
['confirm_block_number', blockNumber],
...chipFields
],
[
['token_id', this.tokenId],
['confirm_count', 1],
['confirm_block_number', blockNumber],
['createtime', nowTime],
['modifytime', nowTime],
...chipFields
]);
if (err) {
log.error('updateConfirmed:' + this.tokenId + ' err:' + err);
return false;
}
}
} finally {
conn.release();
}
return true;
}
}
module.exports = ExecConfirmPlugin;

View File

@ -12,14 +12,6 @@ function add(clsNames, modName) {
}
function init() {
add(['Present'], 'present');
add(['EventCenter'], 'event_center');
add(['ExecConfirmOwner'], 'exec_confirm_owner');
add(['ExecConfirmBalance'], 'exec_confirm_balance');
add(['ExecConfirmPlugin'], 'exec_confirm_plugin');
add(['EventProcess'], 'event_process');
create('Present', null).init();
create('EventCenter', null).init();
}
function create(name, session) {

View File

@ -1,66 +0,0 @@
const app = require('j7/app');
const utils = require('j7/utils');
const bcutils = require('j7/bcutils');
const log = require('j7/log');
const event = require('j7/event');
const http = require('j7/http');
const BaseService = require('./baseservice');
const bc = require('../blockchain');
const metaFactory = require('../metadata/factory');
const C = require('../C');
const factory = require('./factory');
function throwInstanceError(instance, name, err) {
const errMsg = name +
utils.jsonEncode(instance) +
' err:' + err;
throw errMsg;
}
async function callApi(c, a, params) {
params['c'] = c;
params['a'] = a;
const url = metaFactory.getMetaByKey('Config', 0)['game2006api_url'];
return await http.get(url, params);
}
async function confirmTransactionDb(instance, transId) {
const {err, conn} = await app.getDbConn('GameDb0');
if (err) {
throwInstanceError(instance, 'confirmTransactionDb:', 'gamedb connection err:' + err);
return;
}
const nowTime = utils.getUtcTime();
try {
try {
await conn.update(
't_transaction_prefee',
[
['trans_id', transId],
],
[
['done', 1],
['modifytime', nowTime],
]
);
await conn.update(
't_transaction',
[
['trans_id', transId],
],
[
['status', 3],
['modifytime', nowTime],
]
);
} catch (e) {
throwInstanceError(instance, 'confirmTransactionDb:', e);
return;
}
} finally {
conn.release();
}
}
exports.callApi = callApi;
exports.confirmTransactionDb = confirmTransactionDb;

View File

@ -1,159 +0,0 @@
const assert = require('assert');
const app = require('j7/app');
const utils = require('j7/utils');
const bcutils = require('j7/bcutils');
const log = require('j7/log');
const BaseService = require('./baseservice');
const metaFactory = require('../metadata/factory');
class Present extends BaseService {
async init() {
this.gameId = 2006;
this.nowTime = utils.getUtcTime();
this.tokenTime = this.nowTime;
this.idx = 0;
this.idSection = {};
{
const {err, conn} = await app.getDbConn('MarketDb0');
if (err) {
throw 'db error:' + err;
}
this.conn = conn;
}
{
const {err, row} = await this.conn.execQueryOne(
'SELECT max(idx) max_idx FROM t_mint', []);
if (!err && row['max_idx'] != null) {
this.idx = row['max_idx'];
}
log.info('idx:' + this.idx);
}
const presentList = metaFactory.getMetaByKey('PresentList', '0')['list'];
const idSection = metaFactory.getMetaByKey('PresentList', '0')['id_section'];
Object.keys(idSection).forEach((item) => {
const startId = idSection[item][0];
const endId = idSection[item][1];
assert(startId > 0);
assert(endId > 0);
assert(startId < endId);
this.idSection[item] = {
'startId': startId,
'endId': endId,
'currId': startId
};
});
log.info('load present_list.json list ' + utils.jsonEncode(presentList));
log.info('load present_list.json id_section ' + utils.jsonEncode(this.idSection));
for (let i in presentList) {
const name = presentList[i];
const list = [];
metaFactory.traverseMetaList('Present' + name, (item) => {
list.push(item);
return true;
});
await this.processList(name, list);
}
}
async processList(name, list) {
for (let i in list){
const presentMeta = list[i];
for (let ii = 0; ii < presentMeta.getCount(); ++ii) {
const randItem = presentMeta.randItem();
if (randItem) {
const itemId = randItem['itemId'];
const tokenType = randItem['tokenType'];
await this.processOne(name,
presentMeta,
itemId,
tokenType,
ii + 1,
);
}
}
}
}
async processOne(name, presentMeta, itemId, tokenType, seqId) {
const uniKey = this.genUniKey(name, presentMeta['id'], seqId);
const sented = await this.isSented(uniKey);
if (!sented) {
const tokenId = this.genTokenId(name);
const fieldsList = [
['bc_mint_tokenid', tokenId],
['unikey', uniKey],
['account', bcutils.toNormalAddress(presentMeta['account'])],
['game_id', this.gameId],
['bc_mint_itemid', itemId],
['bc_mint_token_type', tokenType],
['bc_mint_tags', presentMeta.getTags()],
['createtime', this.nowTime],
['modifytime', this.nowTime]
];
log.info('insert t_mint ' + utils.jsonEncode(fieldsList));
const {err} = await this.conn.insert(
't_mint',
fieldsList
);
}
}
async isSented(uniKey) {
const {err, row} = await this.conn.ormSelectOne(
't_mint',
[
['unikey', uniKey],
]
);
if (err) {
throw err;
}
return row ? true : false;
}
genTokenId(batchName) {
let tokenId = 0;
if (utils.getVal(this.idSection, 'id_' + batchName)) {
const section = this.idSection['id_' + batchName];
assert(section['currId'] < section['endId']);
tokenId = section['currId']++;
} else {
tokenId = bcutils.genTokenId(
this.gameId,
bcutils.BC_FUNC_GUILD,
this.nowTime,
1,
this.genIdx()
);
}
return tokenId;
}
genIdx() {
let newIdx = this.idx;
if (this.idx < bcutils.BC_MAX_TOKEN_IDX) {
newIdx = this.idx;
++this.idx;
} else {
this.idx = 0;
newIdx = this.idx;
++this.tokenTime;
}
return newIdx;
}
genUniKey(batchId, rowId, seqId) {
return ''.concat(batchId, '_', rowId, '_', seqId);
}
}
module.exports = Present;