Exemplo n.º 1
0
    def _handle_swap(self, swap_data: str, src_token: str, dst_token: str, retry=False):
        swap_json = swap_query_res(swap_data)
        # this is an id, and not the TX hash since we don't actually know where the TX happened, only the id of the
        # swap reported by the contract
        swap_id = get_swap_id(swap_json)
        dest_address = swap_json['destination']
        self.logger.debug(f'{swap_json}')
        amount = int(swap_json['amount'])

        swap_failed = False
        fee = 0
        data = b''
        nonce = int(swap_json['nonce'])
        swap = None

        try:
            if dst_token == 'native':
                data, tx_dest, tx_amount, tx_token, fee = self._tx_native_params(amount, dest_address, retry)
            else:
                self.erc20.address = dst_token
                data, tx_dest, tx_amount, tx_token, fee = self._tx_erc20_params(amount, dest_address, dst_token, retry)

            if retry:

                original_nonce = nonce
                nonce = int(self.multisig_wallet.get_token_nonce(swap_retry_address) + 1)  # + 1 to advance the counter

                swap = Swap.objects.get(src_tx_hash=swap_id)
                swap.status = Status.SWAP_FAILED

                self.update_retry_db(f"{original_nonce}|{tx_token}", f"{nonce}|{swap_retry_address.lower()}")

                tx_token = w3.toChecksumAddress(swap_retry_address)

            msg = message.Submit(w3.toChecksumAddress(tx_dest),
                                 tx_amount,  # if we are swapping token, no ether should be rewarded
                                 nonce,
                                 tx_token,
                                 fee,
                                 data)

        except ValueError as e:
            self.logger.error(f"Error: {e}")
            swap_failed = True

        # this could have already been set by retry
        if not swap:
            swap = Swap(src_network="Secret", src_tx_hash=swap_id, unsigned_tx=data, src_coin=src_token,
                        dst_coin=dst_token, dst_address=dest_address, amount=str(amount), dst_network="Ethereum",
                        status=Status.SWAP_FAILED)

        if swap_failed or not self._validate_fee(amount, fee):
            self._save_failed_swap(swap, swap_id)
        else:
            self._broadcast_and_save(msg, swap, swap_id)
Exemplo n.º 2
0
    def _handle(self, event: AttributeDict):
        """Extracts tx data from @event and add unsigned_tx to db"""
        if not self.contract.verify_destination(event):
            return

        amount = str(self.contract.extract_amount(event))

        try:
            block_number, tx_hash, recipient, token = self.contract.parse_swap_event(
                event)
            if token is None:
                token = 'native'
        except ValueError:
            return

        try:
            s20 = self._get_s20(token)
            mint = mint_json(amount, tx_hash, recipient, s20.address)
            unsigned_tx = create_unsigned_tx(self.config.scrt_swap_address,
                                             mint, self.config.chain_id,
                                             self.config.enclave_key,
                                             self.config.swap_code_hash,
                                             self.multisig.address)

            tx = Swap(src_tx_hash=tx_hash,
                      status=Status.SWAP_UNSIGNED,
                      unsigned_tx=unsigned_tx,
                      src_coin=token,
                      dst_coin=s20.name,
                      dst_address=s20.address,
                      src_network="Ethereum",
                      sequence=self.sequence,
                      amount=amount)
            tx.save(force_insert=True)
            self.sequence = self.sequence + 1
            self.logger.info(
                f"saved new Ethereum -> Secret transaction {tx_hash}, for {amount} {s20.name}"
            )
            # SwapTrackerObject.update_last_processed(src=Source.ETH.value, update_val=block_number)
        except (IndexError, AttributeError, KeyError) as e:
            self.logger.error(f"Failed on tx {tx_hash}, block {block_number}, "
                              f"due to error: {e}")
        except RuntimeError as e:
            self.logger.error(
                f"Failed to create swap tx for eth hash {tx_hash}, block {block_number}. Error: {e}"
            )
        except NotUniqueError as e:
            self.logger.error(
                f"Tried to save duplicate TX, might be a catch up issue - {e}")
        # return block_number, tx_hash, recipient, s20
        SwapTrackerObject.update_last_processed('Ethereum', block_number)
Exemplo n.º 3
0
    def _handle_swap(self, swap_data: str, src_token: str, dst_token: str):
        swap_json = swap_query_res(swap_data)
        # this is an id, and not the TX hash since we don't actually know where the TX happened, only the id of the
        # swap reported by the contract
        swap_id = get_swap_id(swap_json)
        dest_address = swap_json['destination']
        self.logger.info(f'{swap_json}')
        amount = int(swap_json['amount'])

        if dst_token == 'native':
            data, tx_dest, tx_amount, tx_token, fee = self._tx_native_params(
                amount, dest_address)
        else:
            self.erc20.address = dst_token
            data, tx_dest, tx_amount, tx_token, fee = self._tx_erc20_params(
                amount, dest_address, dst_token)

        if not self._validate_fee(amount, fee):
            self.logger.error("Tried to swap an amount too low to cover fee")
            swap = Swap(src_network="Secret",
                        src_tx_hash=swap_id,
                        unsigned_tx=data,
                        src_coin=src_token,
                        dst_coin=dst_token,
                        dst_address=dest_address,
                        amount=str(amount),
                        dst_network="Ethereum",
                        status=Status.SWAP_FAILED)
            try:
                swap.save()
            except (DuplicateKeyError, NotUniqueError):
                pass
            return

        msg = message.Submit(
            tx_dest,
            tx_amount,  # if we are swapping token, no ether should be rewarded
            int(swap_json['nonce']),
            tx_token,
            fee,
            data)
        # todo: check we have enough ETH
        swap = Swap(src_network="Secret",
                    src_tx_hash=swap_id,
                    unsigned_tx=data,
                    src_coin=src_token,
                    dst_coin=dst_token,
                    dst_address=dest_address,
                    amount=str(amount),
                    dst_network="Ethereum",
                    status=Status.SWAP_FAILED)
        try:
            tx_hash = self._broadcast_transaction(msg)
            swap.dst_tx_hash = tx_hash
            swap.status = Status.SWAP_SUBMITTED
        except (ValueError, TransactionNotFound) as e:
            self.logger.critical(
                f"Failed to broadcast transaction for msg {repr(msg)}: {e}")
        finally:
            try:
                swap.save()
            except (DuplicateKeyError, NotUniqueError):
                pass