aozhiwei 8ae8866c71 1
2022-01-21 12:31:55 +08:00

86 lines
2.1 KiB
JavaScript

var utils = require('./utils');
var bc = require('./blockchain');
var metamgr = require('./metamgr');
async function buyBox(req, rsp)
{
try {
let privateKey = metamgr.getServerConf()['private_key'];
let paymentTokenAddress = metamgr.getContractByName('coin')['address'];
let tokenId = 1001;
let boxId = 1001;
let type = 1001;
let price = 100;
let buyerAddress = metamgr.getServerConf()['user_address'];
let nonce = Math.random()*1000|0;
let signStr = bc.web3.utils.soliditySha3(type, paymentTokenAddress, price, nonce);
const { signature } = await bc.web3.eth.accounts.sign(signStr, privateKey);
await bc.coinInstance.methods.increaseAllowance(
metamgr.getContractByName('mall')['address'],
price).send({ gas: 1000000 });
let result = await bc.mallInstance.methods.buyBoxWithSignature(
boxId,
type,
buyerAddress,
price,
paymentTokenAddress,
nonce,
signature).send({gas: 1000000});
utils.rspData(rsp, {
'signature' : signature,
'result': result
});
} catch (err) {
utils.rspErr(rsp, 1, '' + err);
}
}
async function privateKeyToAccount(req, rsp)
{
let privateKey = metamgr.getServerConf()['private_key'];
let account = await bc.web3.eth.accounts.privateKeyToAccount(privateKey);
utils.rspData(rsp, {
'account' : account
});
}
async function getAccounts(req, rsp)
{
let accounts = await bc.web3.eth.getAccounts();
utils.rspData(rsp, accounts);
}
async function getBalance(req, rsp)
{
let balance = await bc.getBalance(metamgr.getServerConf()['user_address']);
utils.rspData(rsp, {
'user_address': metamgr.getServerConf()['user_address'],
'balance': balance
});
}
async function execCmd(req, rsp)
{
let cmd = req.query.cmd;
let handlers = {
'buyBox': buyBox,
'getAccounts': getAccounts,
'getBalance': getBalance,
'privateKeyToAccount': privateKeyToAccount,
};
let handle = handlers[cmd];
if (handle) {
handle(req, rsp);
} else {
utils.rspErr(rsp, 100, 'not found');
}
}
exports.execCmd = execCmd;