pay-svr/src/queue/transfer.queue.ts
2023-07-14 13:53:06 +08:00

105 lines
2.7 KiB
TypeScript

import { singleton } from 'decorators/singleton'
import { AsyncQueue, createAsyncQueue } from 'common/AsyncQueue'
import { DocumentType } from '@typegoose/typegoose'
import { PayRecordClass } from 'modules/PayRecord'
import logger from 'logger/logger'
import { pushTaskToChain } from 'service/chain.svr'
import { TransferRecord } from 'modules/TransferRecord'
import config from 'config/config'
import assert from 'assert'
/**
* let data = {
taskId: '1',
source: 'pay',
cb: 'status update callback url',
data: [
{
address: '0xb592244aa6477eBDDc14475aaeF921cdDcC0170f',
from: '',
to: '0x90F8bf6A479f320ead074411a4B0e7944Ea8c9C1',
amount: 1000,
type: 3
},
],
}
*/
@singleton
export class TransferQueue {
private queue: AsyncQueue
constructor() {
this.queue = createAsyncQueue()
}
public addTask(task: DocumentType<PayRecordClass>) {
this.queue.push(async () => {
try {
let chainCfg = config.chainCfgs[task.network.toLowerCase()]
assert(chainCfg, `chain config not found: ${task.network}`)
let chainId = chainCfg.chainId
let wallet = chainCfg.wallet
let token = task.crypto.toLowerCase()
let address
if (token === 'agor') {
address = 'eth'
} else {
let env = task.env ? task.env.toLowerCase() : 'dev'
address = chainCfg.tokens[`${token}_${env}`]
}
assert(address, `token address not found: ${task.crypto}`)
let record = await TransferRecord.insertOrUpdate(
{ recordId: task.id },
{
account: task.account,
chain: chainId,
contract: address,
to: task.address,
from: wallet,
amount: task.cryptoAmount,
$inc: { version: 1 },
},
)
let datas: any = [
{
chain: record.chain,
address: record.contract,
from: record.from,
to: record.to,
amount: record.amount,
type: 3,
},
]
if (token === 'agor') {
datas = [
{
from: record.from,
to: record.to,
amount: record.amount,
type: 6,
},
]
}
let reqData = {
taskId: record.id,
source: 'pay',
data: datas,
max: 1,
cb: process.env.PAY_TRANSFER_CB_URL,
}
await pushTaskToChain(reqData)
task.tranStatus = 1
await task.save()
} catch (err) {
task.tranStatus = 99
await task.save()
logger.error('error add chain task: ')
logger.error(err)
}
})
}
}