Search code examples
djangoethereumweb3pycoinpayments-api

Sending tokens out on coinpayments success payment using Web3py


I'm writing Django app and want to send out tokens using Web3 once Coinpayments sends me callback about successfull payment. The problem is that Coinpayments sends multiple callbacks at once and just in one case tokens are sending, other callbacks get replacement transaction underpriced error. I've already tried to use solutions like add +1 to nonce or remove this parameter, but that doesn't help me because transactions are still building with the same nonce. How can that be fixed or what am I doing wrong?

class CoinpaymentsIPNPaymentView(BaseCoinpaymentsIPNView):
    def post(self, request, order_id, *args, **kwargs):
        status = int(request.POST.get('status'))
        order = Order.objects.get(id=order_id)
        order.status = request.POST.get("status_text")
        if not status >= 100:
            order.save()
            return JsonResponse({"status": status})
        amount = Decimal(request.POST.get('amount1'))
        record = Record.objects.create(
            user=order.user,
            type='i',
            amount=amount,
        )
        order.record = record
        order.save()

        gold_record = GoldRecord.objects.get(from_record=record)

        contract = w3.eth.contract(address=CONTRACT_ADDRESS, abi=ABI_JSON)
        transaction = contract.functions.transfer(order.user.wallet.address, int(gold_record.amount * 10 ** 18)).buildTransaction({
            'chainId': 1,
            'gas': 70000,
            'nonce': w3.eth.getTransactionCount(WALLET_ADDRESS)                      # address where all tokens are stored
        })
        signed_tx = w3.eth.account.signTransaction(transaction, WALLET_PRIVATE_KEY)  # signing with wallet's above private key
        tx_hash = w3.eth.sendRawTransaction(signed_tx.rawTransaction)
        print(tx_hash.hex())
        tx_receipt = w3.eth.waitForTransactionReceipt(tx_hash)

        return JsonResponse({"status": status})

P.S. I've already asked it on Ethereum StackExchange, but nobody answered or commented it: https://ethereum.stackexchange.com/questions/80961/sending-tokens-out-on-coinpayments-success-payment-using-web3py


Solution

  • Ok, let the web know answer and solution that I found out by myself

    Each transaction should have unique nonce, so I noticed that if I do a loop for sending transactions and set nonce as w3.eth.getTransactionCount(WALLET_ADDRESS) + index then it sends all transactions without any errors. So I removed instant coins sending (even removed waitForTransactionReceipt to speed up it), and made management command where I process all payouts and if it was sent successfully I assign its tx_hash and run it every 10 minutes with Heroku Scheduler