eth錢包開發(fā)(nodejs)(二)

使用web3.js進(jìn)行充值監(jiān)聽的兩種方式

  • 通過token event進(jìn)行監(jiān)聽(只適合代幣轉(zhuǎn)賬)
contract.events.Transfer({}, {
    fromBlock: 0,
    toBlock: 'latest',
}, async (error, event) => {
    if (error) {
        logger.error(error);
    } else {
        //獲取event中轉(zhuǎn)賬信息
        const to = event.returnValues.to.toLowerCase();
        const bigValue = Big(event.returnValues.value);
        const value = bigValue.div(1000000).toFixed(6);
        const hash = event.transactionHash;

        const user = await userService.findUidByEthAddress(to);
        logger.debug(user);

        if(user === null || user.uid === 0) {
            return;
        }

        let encryptData = crypto.encrypt(JSON.stringify({
            hash: event.transactionHash,
            uid: user.uid,
            value: value.toString(),
            fromAddress: event.returnValues.from,
        }), rechargeKey, rechargeIv);

        const tx = await txService.findByHash(hash);

        if(tx !== null) {
            logger.info("交易重復(fù)提交");
            return;
        }

        await txService.createTransaction(user.uid, hash, value.toString(), event.returnValues.from);

        try {
            const response = await fetchRequest(rechargeEthUsdtApi, encryptData);
            if(response.code === 1) {
                await txService.commitTransaction(hash);
                logger.debug({msg: "狀態(tài)提交成功", resCode: response.code});
            }
        } catch (e) {
            logger.error(e);
            await txService.invalidTransaction(hash);
            logger.debug({msg: "狀態(tài)提交成功", resCode: 0});
        }

        const mainAddress = await userService.mainAccount();

        try {
            logger.info("retrieve all ETH-USDT from child address");
            await retrieveAllEthUsdt(user.uid, mainAddress);
            logger.info("retrieve all ETH-USDT from child address successful");
        } catch (e) {
            logger.error(e);
            logger.info("fail to retrieve all ETH-USDT from child address")
        }

    }
});
  • 掃塊監(jiān)聽(適合eth和所有代幣)
const watchTransaction = async () => {

    //初始化lastblock
    lastBlock = await getAsync(redisBlockCountKey);
    logger.debug(lastBlock);
    if (lastBlock === null) {
        lastBlock = await web3.eth.getBlockNumber();
        await setAsync(redisBlockCountKey, lastBlock);
        return;
    }

    const currentBlock = await web3.eth.getBlockNumber();
    logger.debug(currentBlock);

    //初始化
    if (currentBlock - lastBlock > 50) {
        await setAsync(redisBlockCountKey, currentBlock);
        return;
    }

    await setAsync(redisBlockCountKey, currentBlock + 1);

    const mainAddress = await userService.mainAccount();

    //掃塊
    for (let i = lastBlock; i < currentBlock + 1; i++) {

        const block = await web3.eth.getBlock(i, true);
        const txs = block.transactions;

        logger.info("txCount: " + txs.length);
        for (let j = 0; j < txs.length; j++) {
            const tx = txs[j];
            const toAddress = tx.to.toLowerCase();

            let user;
            try {
                user = await userService.findUidByEthAddress(toAddress);
            } catch (e) {
                continue;
            }

            //eth交易處理
            if (user !== null && user.uid !== 0 && tx.from !== mainAddress) {
                logger.debug(user);
                const hash = tx.hash;
                const findTx = await rechargeInfoService.checkHash(hash);
                if (findTx !== null) {
                    logger.debug("交易重復(fù)提交");
                    continue;
                }

                const bigValue = Big(tx.value).div('1e+18');

                //提交服務(wù)器
                let encryptData = crypto.encrypt(JSON.stringify({
                    hash: hash,
                    uid: user.uid,
                    value: bigValue,
                    fromAddress: tx.from,
                    cid: 1
                }), rechargeKey, rechargeIv);

                await rechargeInfoService.createRechargeInfo(user.uid, hash, bigValue.toString(), tx.from, 1);

                let response;

                try {
                    response = await fetchRequest(rechargeApi, encryptData);
                } catch (e) {
                    await rechargeInfoService.invalidTransaction(hash);
                    logger.debug({msg: "狀態(tài)提交成功", resCode: 0});
                }

                if (response.code === 1) {
                    await rechargeInfoService.commitTransaction(hash);
                    logger.debug({msg: "狀態(tài)提交成功", resCode: response.code});
                } else {
                    await rechargeInfoService.invalidTransaction(hash);
                    logger.debug({msg: "狀態(tài)提交成功", resCode: response.code});
                }

                const ethBalance = await web3.eth.getBalance(toAddress);
                //提取子賬戶中的eth
                if(ethBalance > web3.utils.toWei("0.005", "ether")) {
                    try {
                        logger.info("retrieve ETH from child address");
                        await retrieveAllEth(user.uid, mainAddress);
                        logger.info("retrieve ETH from child address successful")
                    } catch (e) {
                        logger.error(e);
                        logger.info("fail to retrieve ETH from child address");
                    }
                }

                continue;
            }

            const input = tx.input;

            //token交易處理
            if (input.length === 138 && input.substr(0, 10) === "0xa9059cbb") {
                const addr = input.substring(34, 74);

                const user = await userService.findUidByEthAddress("0x" + addr);

                if (user !== null && user.uid !== 0 && tx.from !== mainAddress) {

                    logger.debug(user);

                    const hash = tx.hash;

                    //檢查token是否在數(shù)據(jù)庫內(nèi)
                    const token = await coinService.findByCoinAddress(toAddress);

                    if (token === null) {
                        continue;
                    }

                    //檢查token轉(zhuǎn)賬是否有效
                    const transactionReceipt = await web3.eth.getTransactionReceipt(hash);

                    if (transactionReceipt.logs.length === 0) {
                        continue;
                    }

                    //創(chuàng)建合約對象
                    const contract = await new web3.eth.Contract(abi, toAddress);
                    const tokenValue = web3.utils.hexToNumberString(input.substring(74, input.length));

                    const bigValue = Big(tokenValue).div('1e+' + token.decimal);

                    // 保存數(shù)據(jù)庫
                    await rechargeInfoService.createRechargeInfo(user.uid, hash, bigValue.toString(), tx.from, token.cid);

                    // 提取子賬戶中的token
                    try {
                        logger.info("retrieve coin from child address");
                        await retrieveAllCoin(user.uid, mainAddress, contract);
                        logger.info("retrieve coin from child address successful");
                    } catch (e) {
                        logger.error(e);
                        logger.info("fail to retrieve coin from child address");
                    }

                    // 提交服務(wù)器
                    let encryptData = crypto.encrypt(JSON.stringify({
                        hash: hash,
                        uid: user.uid,
                        value: bigValue.toString(),
                        fromAddress: tx.from,
                        cid: token.cid
                    }), rechargeKey, rechargeIv);

                    let response;
                    try {
                        response = await fetchRequest(rechargeApi, encryptData);
                    } catch (e) {
                        await rechargeInfoService.invalidTransaction(hash);
                        logger.debug({msg: "狀態(tài)提交成功", resCode: 0});
                    }

                    if (response.code === 1) {
                        await rechargeInfoService.commitTransaction(hash);
                        logger.debug({msg: "狀態(tài)提交成功", resCode: response.code});
                    } else {
                        await rechargeInfoService.invalidTransaction(hash);
                        logger.debug({msg: "狀態(tài)提交成功", resCode: response.code});
                    }

                }
            }
        }
    }

};
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末栓始,一起剝皮案震驚了整個(gè)濱河市卤橄,隨后出現(xiàn)的幾起案子娃惯,更是在濱河造成了極大的恐慌滴须,老刑警劉巖窟绷,帶你破解...
    沈念sama閱讀 219,490評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異奕筐,居然都是意外死亡泪酱,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,581評論 3 395
  • 文/潘曉璐 我一進(jìn)店門娃殖,熙熙樓的掌柜王于貴愁眉苦臉地迎上來值戳,“玉大人,你說我怎么就攤上這事炉爆。” “怎么了?”我有些...
    開封第一講書人閱讀 165,830評論 0 356
  • 文/不壞的土叔 我叫張陵芬首,是天一觀的道長赴捞。 經(jīng)常有香客問我,道長郁稍,這世上最難降的妖魔是什么赦政? 我笑而不...
    開封第一講書人閱讀 58,957評論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮耀怜,結(jié)果婚禮上恢着,老公的妹妹穿的比我還像新娘。我一直安慰自己财破,他們只是感情好掰派,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,974評論 6 393
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著左痢,像睡著了一般靡羡。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上俊性,一...
    開封第一講書人閱讀 51,754評論 1 307
  • 那天略步,我揣著相機(jī)與錄音,去河邊找鬼定页。 笑死趟薄,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的典徊。 我是一名探鬼主播竟趾,決...
    沈念sama閱讀 40,464評論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼宫峦!你這毒婦竟也來了岔帽?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,357評論 0 276
  • 序言:老撾萬榮一對情侶失蹤导绷,失蹤者是張志新(化名)和其女友劉穎犀勒,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體妥曲,經(jīng)...
    沈念sama閱讀 45,847評論 1 317
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡贾费,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,995評論 3 338
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了檐盟。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片褂萧。...
    茶點(diǎn)故事閱讀 40,137評論 1 351
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖葵萎,靈堂內(nèi)的尸體忽然破棺而出导犹,到底是詐尸還是另有隱情唱凯,我是刑警寧澤,帶...
    沈念sama閱讀 35,819評論 5 346
  • 正文 年R本政府宣布谎痢,位于F島的核電站磕昼,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏节猿。R本人自食惡果不足惜票从,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,482評論 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望滨嘱。 院中可真熱鬧峰鄙,春花似錦、人聲如沸太雨。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,023評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽躺彬。三九已至煤墙,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間宪拥,已是汗流浹背仿野。 一陣腳步聲響...
    開封第一講書人閱讀 33,149評論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留她君,地道東北人脚作。 一個(gè)月前我還...
    沈念sama閱讀 48,409評論 3 373
  • 正文 我出身青樓,卻偏偏與公主長得像缔刹,于是被迫代替她去往敵國和親球涛。 傳聞我的和親對象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,086評論 2 355

推薦閱讀更多精彩內(nèi)容