コード例 #1
0
    def establish_trust(self, private_key, token):
        """
        Amount as full
        """
        # Load user secret and get account

        user_key_pair = Keypair.from_secret(private_key)
        root_account = Account(account_id=user_key_pair.public_key, sequence=1)
        public_key = root_account.account_id
        asset_issuer = self.integrated_coins[token.lower()]["assetIssuer"]

        try:
            source_account = self.server.load_account(public_key)
            tx = TransactionBuilder(
                source_account=source_account,
                network_passphrase=self.network_phrase,
                base_fee=self.server.fetch_base_fee()).append_change_trust_op(asset_code=f'{token.upper()}',
                                                                              asset_issuer=asset_issuer).set_timeout(
                30).build()
            tx.sign(private_key)

            self.server.submit_transaction(tx)
            return True
        except exceptions.NotFoundError:
            return False
コード例 #2
0
 def test_tx_fee_less_than_base_fee(self):
     inner_keypair = Keypair.from_secret(
         "SBKTIFHJSS3JJWEZO2W74DZSA45WZU56LOL3AY7GAW63BXPEJQFYV53E")
     inner_source = Account(inner_keypair.public_key, 7)
     destination = "GDQERENWDDSQZS7R7WKHZI3BSOYMV3FSWR7TFUYFTKQ447PIX6NREOJM"
     amount = "2000.0000000"
     inner_tx = (TransactionBuilder(inner_source,
                                    Network.TESTNET_NETWORK_PASSPHRASE,
                                    50,
                                    v1=True).append_payment_op(
                                        destination=destination,
                                        amount=amount,
                                        asset_code="XLM").add_time_bounds(
                                            0, 0).build())
     inner_tx.sign(inner_keypair)
     fee_source = Keypair.from_secret(
         "SB7ZMPZB3YMMK5CUWENXVLZWBK4KYX4YU5JBXQNZSK2DP2Q7V3LVTO5V")
     base_fee = 60
     with pytest.raises(
             ValueError,
             match="Invalid `base_fee`, it should be at least 100 stroops.",
     ):
         TransactionBuilder.build_fee_bump_transaction(
             fee_source.public_key,
             base_fee,
             inner_tx,
             Network.TESTNET_NETWORK_PASSPHRASE,
         )
コード例 #3
0
ファイル: xlm_wallet.py プロジェクト: rahimklaber/anydex-core
    def merge_account(self, address):
        """
        Delete the wallet and send all funds to the specified address
        :param address: address to send funds to
        :return: tx hash
        """
        self.check_and_update_created_on_network()
        if not self.created_on_network:
            return fail(
                RuntimeError(
                    'Cannot do account merge operation: account is not created on network'
                ))
        self._logger.info(
            'Deleting wallet and sending all funds to address %s', address)
        network = Network.PUBLIC_NETWORK_PASSPHRASE if not self.testnet else Network.TESTNET_NETWORK_PASSPHRASE
        tx = TransactionBuilder(
            source_account=self.account,
            base_fee=self.provider.get_base_fee(),
            network_passphrase=network,
        ).append_account_merge_op(address).build()

        tx.sign(self.keypair)
        xdr_tx_envelope = tx.to_xdr()

        tx_hash = self.provider.submit_transaction(xdr_tx_envelope)
        self.created_on_network = False
        return succeed(tx_hash)
コード例 #4
0
    def _manage_sell_order(
        self,
        selling_asset: stellar_sdk.Asset,
        buying_asset: stellar_sdk.Asset,
        amount: Union[str, decimal.Decimal],
        price: Union[str, decimal.Decimal],
        timeout=30,
        offer_id=0,
    ):
        """Places/Deletes a selling order for amount `amount` of `selling_asset` for `buying_asset` with the price of `price`

        Args:
            selling_asset (stellar_sdk.Asset): Selling Asset object - check wallet object.get_asset_by_code function
            buying_asset (stellar_sdk.Asset): Buying Asset object - Asset object - check wallet object.get_asset_by_code function
            amount (Union[str, decimal.Decimal]): Amount to sell.
            price (Union[str, decimal.Decimal]): Price for selling.
            timeout (int, optional): Timeout for submitting the transaction. Defaults to 30.
            offer_id: pass the current offer id and set the amount to 0 to cancel this offer or another amount to update the offer

        Raises:
            ValueError: In case of invalid issuer.
            RuntimeError: Error happened during submission of the transaction.

        Returns:
            (dict): response as the result of sumbit the transaction
        """
        server = self._get_horizon_server()
        tb = TransactionBuilder(self.load_account(), network_passphrase=_NETWORK_PASSPHRASES[self.network.value])
        try:
            tx = (
                tb.append_manage_sell_offer_op(
                    selling_code=selling_asset.code,
                    selling_issuer=selling_asset.issuer,
                    buying_code=buying_asset.code,
                    buying_issuer=buying_asset.issuer,
                    amount=amount,
                    price=price,
                    offer_id=offer_id,
                )
                .set_timeout(timeout)
                .build()
            )
        except stellar_sdk.exceptions.AssetIssuerInvalidError as e:
            raise ValueError("invalid issuer") from e
        except Exception as e:
            raise RuntimeError(
                f"error happened for placing selling order for selling: {selling_asset}, buying: {buying_asset}, amount: {amount} price: {price}"
            ) from e
        else:
            tx.sign(self.secret)
            try:
                resp = server.submit_transaction(tx)
            except Exception as e:
                raise RuntimeError(
                    f"couldn't submit sell offer, probably wallet is unfunded. Please check the error stacktrace for more information."
                ) from e
            return resp
コード例 #5
0
 def create_transaction(self, sourceAccountPublicKey, operationList):
     sourceAccount = self.load_account(sourceAccountPublicKey)
     transactionBuilder = TransactionBuilder(
         source_account=sourceAccount,
         network_passphrase=Network.TESTNET_NETWORK_PASSPHRASE)
     #for operation in operationList:
     #    transactionBuilder.append_operation(operation)
     txnEnv = transactionBuilder.build()
     return txnEnv.to_xdr()
コード例 #6
0
def setup_multisig():
    client_master_account = server.load_account(
        client_master_keypair.public_key)
    te = TransactionBuilder(client_master_account, network_passphrase) \
        .append_ed25519_public_key_signer(client_signer_keypair1.public_key, 40) \
        .append_ed25519_public_key_signer(client_signer_keypair2.public_key, 60) \
        .append_set_options_op(master_weight=0, low_threshold=1, med_threshold=10, high_threshold=100) \
        .build()
    te.sign(client_master_keypair)
    resp = server.submit_transaction(te)
    print(resp)
コード例 #7
0
    def convert_to_USDC(public_key, filename, amount, public=False):
        receipt = ""
        if public:
            server = Server(horizon_url="https://horizon.stellar.org")
            passphrase = Network.PUBLIC_NETWORK_PASSPHRASE
        else:
            server = Server(horizon_url="https://horizon-testnet.stellar.org")
            passphrase = Network.TESTNET_NETWORK_PASSPHRASE

        sender = hidden[0]
        source_keypair = Keypair.from_secret(hidden[1])

        # try:
        destination_p = sender
        source_acc = server.load_account(sender)
        base_fee = server.fetch_base_fee()
        path = [
            Asset('XLM', None),
            Asset("USDC",
                  'GC5W3BH2MQRQK2H4A6LP3SXDSAAY2W2W64OWKKVNQIAOVWSAHFDEUSDC')
        ]
        c_m_value = float(get_XLM_price())
        complete = False
        slip = 0
        while not complete:
            min_received = c_m_value * (1 - slip)
            slip += .25
            transaction = TransactionBuilder(
                source_account=source_acc,
                network_passphrase=passphrase,
                base_fee=base_fee).append_path_payment_strict_send_op(
                    destination_p, "XLM", None, amount, "USDC",
                    'GC5W3BH2MQRQK2H4A6LP3SXDSAAY2W2W64OWKKVNQIAOVWSAHFDEUSDC',
                    str(min_received), path).build()

            transaction.sign(source_keypair)
            try:
                response = server.submit_transaction(transaction)
                if response['successful']:
                    receipt += "Successfully sent " + str(
                        amount) + " XLM to USDC"
                    receipt += "\nslippage: " + str((1 - slip) * 100) + "%"
                    complete = True
            except:
                receipt += "\n Failed at " + str((1 - slip) * 100) + "% rate"
            if slip > 5:
                complete = True
                receipt += "Aborting attempts at transaction"
        return receipt
コード例 #8
0
    def modify_signing_requirements(self,
                                    public_keys_signers,
                                    signature_count,
                                    low_treshold=0,
                                    high_treshold=2,
                                    master_weight=2):
        """modify_signing_requirements sets the signing requirements for a multisig account. It also adds
        the public keys of the signer to this account.
        :param public_keys_signers: list of public keys of signers.
        :type public_keys_signers: list
        :param signature_count: amount of signatures required to transfer funds.
        :type signature_count: int
        :param low_treshold: weight required for low security operations (transaction processing, allow trust, bump sequence)
        :type low_treshold: int
        :param high_treshold: weight required for high security operations (set options, account merge)
        :type high_treshold: int
        :param master_weight: A number from 0-255 (inclusive) representing the weight of the master key. If the weight of the master key is updated to 0, it is effectively disabled.
        :type master_weight: int 
        """
        account = self.load_account()
        source_keypair = Keypair.from_secret(self.secret)

        horizon_server = self._get_horizon_server()
        base_fee = horizon_server.fetch_base_fee()
        transaction_builder = TransactionBuilder(
            account,
            network_passphrase=_NETWORK_PASSPHRASES[str(self.network)],
            base_fee=base_fee)
        # set the signing options
        transaction_builder.append_set_options_op(
            low_threshold=low_treshold,
            med_threshold=signature_count,
            high_threshold=high_treshold,
            master_weight=master_weight)

        # For every public key given, add it as a signer to this account
        for public_key_signer in public_keys_signers:
            transaction_builder.append_ed25519_public_key_signer(
                public_key_signer, 1)

        transaction_builder.set_timeout(30)
        tx = transaction_builder.build()
        tx.sign(source_keypair)

        try:
            response = horizon_server.submit_transaction(tx)
            self._log_info(response)
            self._log_info(
                "Set the signers of {address} to require {signature_count} signers"
                .format(address=self.address, signature_count=signature_count))
        except BadRequestError:
            self._log_info(
                "Transaction need additional signatures in order to send")
            return tx.to_xdr()
コード例 #9
0
def sendXLM(secret, toAddress): 
    server = Server(horizon_url="https://horizon-testnet.stellar.org")
    source_keypair = Keypair.from_secret(secret)

    source_account = server.load_account(account_id=source_keypair.public_key)

    transaction = TransactionBuilder(
        source_account=source_account, network_passphrase=Network.TESTNET_NETWORK_PASSPHRASE, base_fee=100) \
        .append_path_payment_strict_receive_op(destination=toAddress,
                                send_code="XLM", send_issuer=None, send_max="1000", dest_code="XLM",
                                dest_amount="5.50", path=path) \
        .set_timeout(30) \
        .build()
    transaction.sign(source_keypair)
    response = server.submit_transaction(transaction)
コード例 #10
0
    def test_to_xdr_sponsored_reserves(self):
        sequence = 1
        source = Account(
            "GDF5O4OWEMVBY5FLDHWA5RZTYSV2U276XGKZZ6VSHDDR3THSQ6OQS7UM", sequence
        )
        builder = TransactionBuilder(
            source, Network.TESTNET_NETWORK_PASSPHRASE, base_fee=150, v1=False
        )
        builder.add_text_memo("Stellar Python SDK")
        builder.add_time_bounds(1565590000, 1565600000)
        op_source = "GDF5O4OWEMVBY5FLDHWA5RZTYSV2U276XGKZZ6VSHDDR3THSQ6OQS7UM"
        op_account_id = "GCWWANEIF3Z4DMOE4LDRCS22HLLHOEQCOF3QKAC2XWTSYR2AEEQ3P5FW"
        te = (
            builder.append_begin_sponsoring_future_reserves_op(
                sponsored_id="GCEYOF66NL73LL6RIPSIP34WOCESQ3GKJOAYXOEVNKRWRNQRYUILCQWC",
                source=op_source,
            )
            .append_end_sponsoring_future_reserves_op(source=op_source)
            .append_revoke_account_sponsorship_op(
                account_id=op_account_id, source=op_source
            )
            .append_revoke_trustline_sponsorship_op(
                account_id=op_account_id, asset=Asset.native(), source=op_source
            )
            .append_revoke_offer_sponsorship_op(
                seller_id=op_account_id, offer_id=12315, source=op_source
            )
            .append_revoke_data_sponsorship_op(
                account_id=op_account_id, data_name="stellar", source=op_source
            )
            .append_revoke_claimable_balance_sponsorship_op(
                claimable_balance_id="00000000da0d57da7d4850e7fc10d2a9d0ebc731f7afb40574c03395b17d49149b91f5be",
                source=op_source,
            )
            .append_revoke_ed25519_public_key_signer_sponsorship_op(
                account_id=op_account_id,
                signer_key="GBWYVWA2PZBTRRBNZI55OG4EFDJSDNL6ASP2VAQKHORNUSSXP2NCV4N2",
                source=op_source,
            )
            .append_revoke_hashx_signer_sponsorship_op(
                account_id=op_account_id,
                signer_key="da0d57da7d4850e7fc10d2a9d0ebc731f7afb40574c03395b17d49149b91f5be",
                source=op_source,
            )
            .append_revoke_pre_auth_tx_signer_sponsorship_op(
                account_id=op_account_id,
                signer_key="da0d57da7d4850e7fc10d2a9d0ebc731f7afb40574c03395b17d49149b91f5be",
                source=op_source,
            )
            .build()
        )

        xdr = "AAAAAMvXcdYjKhx0qxnsDsczxKuqa/65lZz6sjjHHczyh50JAAAF3AAAAAAAAAACAAAAAQAAAABdUQHwAAAAAF1RKQAAAAABAAAAElN0ZWxsYXIgUHl0aG9uIFNESwAAAAAACgAAAAEAAAAAy9dx1iMqHHSrGewOxzPEq6pr/rmVnPqyOMcdzPKHnQkAAAAQAAAAAImHF95q/7Wv0UPkh++WcIkobMpLgYu4lWqjaLYRxRCxAAAAAQAAAADL13HWIyocdKsZ7A7HM8Srqmv+uZWc+rI4xx3M8oedCQAAABEAAAABAAAAAMvXcdYjKhx0qxnsDsczxKuqa/65lZz6sjjHHczyh50JAAAAEgAAAAAAAAAAAAAAAK1gNIgu88GxxOLHEUtaOtZ3EgJxdwUAWr2nLEdAISG3AAAAAQAAAADL13HWIyocdKsZ7A7HM8Srqmv+uZWc+rI4xx3M8oedCQAAABIAAAAAAAAAAQAAAACtYDSILvPBscTixxFLWjrWdxICcXcFAFq9pyxHQCEhtwAAAAAAAAABAAAAAMvXcdYjKhx0qxnsDsczxKuqa/65lZz6sjjHHczyh50JAAAAEgAAAAAAAAACAAAAAK1gNIgu88GxxOLHEUtaOtZ3EgJxdwUAWr2nLEdAISG3AAAAAAAAMBsAAAABAAAAAMvXcdYjKhx0qxnsDsczxKuqa/65lZz6sjjHHczyh50JAAAAEgAAAAAAAAADAAAAAK1gNIgu88GxxOLHEUtaOtZ3EgJxdwUAWr2nLEdAISG3AAAAB3N0ZWxsYXIAAAAAAQAAAADL13HWIyocdKsZ7A7HM8Srqmv+uZWc+rI4xx3M8oedCQAAABIAAAAAAAAABAAAAADaDVfafUhQ5/wQ0qnQ68cx96+0BXTAM5WxfUkUm5H1vgAAAAEAAAAAy9dx1iMqHHSrGewOxzPEq6pr/rmVnPqyOMcdzPKHnQkAAAASAAAAAQAAAACtYDSILvPBscTixxFLWjrWdxICcXcFAFq9pyxHQCEhtwAAAABtitgafkM4xC3KO9cbhCjTIbV+BJ+qggo7otpKV36aKgAAAAEAAAAAy9dx1iMqHHSrGewOxzPEq6pr/rmVnPqyOMcdzPKHnQkAAAASAAAAAQAAAACtYDSILvPBscTixxFLWjrWdxICcXcFAFq9pyxHQCEhtwAAAALaDVfafUhQ5/wQ0qnQ68cx96+0BXTAM5WxfUkUm5H1vgAAAAEAAAAAy9dx1iMqHHSrGewOxzPEq6pr/rmVnPqyOMcdzPKHnQkAAAASAAAAAQAAAACtYDSILvPBscTixxFLWjrWdxICcXcFAFq9pyxHQCEhtwAAAAHaDVfafUhQ5/wQ0qnQ68cx96+0BXTAM5WxfUkUm5H1vgAAAAAAAAAA"
        assert te.to_xdr() == xdr
        restore_te = TransactionBuilder.from_xdr(
            xdr, Network.TESTNET_NETWORK_PASSPHRASE
        ).build()
        assert restore_te.to_xdr() == xdr
コード例 #11
0
 async def test_check_memo_required_with_memo_muxed_account_async(
         self, httpserver):
     self.__inject_mock_server(httpserver)
     horizon_url = httpserver.url_for("/")
     keypair = Keypair.from_secret(
         "SDQXFKA32UVQHUTLYJ42N56ZUEM5PNVVI4XE7EA5QFMLA2DHDCQX3GPY")
     account = Account(keypair.public_key, 1)
     async with Server(horizon_url, AiohttpClient()) as server:
         transaction = (TransactionBuilder(account).append_payment_op(
             self.DESTINATION_ACCOUNT_MEMO_REQUIRED_A, "10",
             "XLM").append_path_payment_strict_receive_op(
                 self.DESTINATION_ACCOUNT_MEMO_REQUIRED_B,
                 "XLM",
                 None,
                 "10",
                 "BTC",
                 "GA7GYB3QGLTZNHNGXN3BMANS6TC7KJT3TCGTR763J4JOU4QHKL37RVV2",
                 "1",
                 [],
             ).append_path_payment_strict_send_op(
                 self.DESTINATION_ACCOUNT_MEMO_REQUIRED_C,
                 "XLM",
                 None,
                 "10",
                 "BTC",
                 "GA7GYB3QGLTZNHNGXN3BMANS6TC7KJT3TCGTR763J4JOU4QHKL37RVV2",
                 "1",
                 [],
             ).append_account_merge_op(
                 self.DESTINATION_ACCOUNT_MEMO_REQUIRED_D).add_text_memo(
                     "hello, world").build())
         transaction.sign(keypair)
         await server.submit_transaction(transaction)
コード例 #12
0
 def test_check_memo_required_with_account_not_found_sync(self, httpserver):
     self.__inject_mock_server(httpserver)
     horizon_url = httpserver.url_for("/")
     server = Server(horizon_url)
     keypair = Keypair.from_secret(
         "SDQXFKA32UVQHUTLYJ42N56ZUEM5PNVVI4XE7EA5QFMLA2DHDCQX3GPY")
     account = Account(keypair.public_key, 1)
     transaction = (TransactionBuilder(account).append_payment_op(
         self.DESTINATION_ACCOUNT_NO_FOUND, "10",
         "XLM").append_path_payment_strict_receive_op(
             self.DESTINATION_ACCOUNT_NO_FOUND,
             "XLM",
             None,
             "10",
             "BTC",
             "GA7GYB3QGLTZNHNGXN3BMANS6TC7KJT3TCGTR763J4JOU4QHKL37RVV2",
             "1",
             [],
         ).append_path_payment_strict_send_op(
             self.DESTINATION_ACCOUNT_NO_FOUND,
             "XLM",
             None,
             "10",
             "BTC",
             "GA7GYB3QGLTZNHNGXN3BMANS6TC7KJT3TCGTR763J4JOU4QHKL37RVV2",
             "1",
             [],
         ).append_account_merge_op(
             self.DESTINATION_ACCOUNT_NO_FOUND).build())
     transaction.sign(keypair)
     server.submit_transaction(transaction)
コード例 #13
0
    def test_add_memo(self):
        source = Account("GDF5O4OWEMVBY5FLDHWA5RZTYSV2U276XGKZZ6VSHDDR3THSQ6OQS7UM", 1)
        builder = TransactionBuilder(
            source, Network.TESTNET_NETWORK_PASSPHRASE, base_fee=150
        ).add_id_memo(100)
        assert builder.memo == IdMemo(100)

        memo_hash = os.urandom(32)
        builder = TransactionBuilder(
            source, Network.TESTNET_NETWORK_PASSPHRASE, base_fee=150
        ).add_hash_memo(memo_hash)
        assert builder.memo == HashMemo(memo_hash)
        builder = TransactionBuilder(
            source, Network.TESTNET_NETWORK_PASSPHRASE, base_fee=150
        ).add_return_hash_memo(memo_hash)
        assert builder.memo == ReturnHashMemo(memo_hash)
コード例 #14
0
    def activate_account(self, destination_address, starting_balance="12.50"):
        """Activates another account
        :param destination_address: address of the destination.
        :type destination_address: str
        :param starting_balance: the balance that the destination address will start with. Must be a positive integer expressed as a string. If an empty string is provided, 12,5 XLM will be the starting balance
        :type assetcode: str
        """
        server = self._get_horizon_server()
        source_keypair = Keypair.from_secret(self.secret)

        source_account = self.load_account()

        base_fee = server.fetch_base_fee()
        transaction = (TransactionBuilder(
            source_account=source_account,
            network_passphrase=_NETWORK_PASSPHRASES[str(self.network)],
            base_fee=base_fee,
        ).append_create_account_op(destination=destination_address,
                                   starting_balance=starting_balance).build())
        transaction.sign(source_keypair)
        try:
            response = server.submit_transaction(transaction)
            self._log_info("Transaction hash: {}".format(response["hash"]))
            self._log_info(response)
        except BadRequestError as e:
            self._log_debug(e)
コード例 #15
0
def hello_world(request):
    """Responds to any HTTP request.
    Args:
        request (flask.Request): HTTP request object.
    Returns:
        The response text or any set of values that can be turned into a
        Response object using
        `make_response <http://flask.pocoo.org/docs/1.0/api/#flask.Flask.make_response>`.
    """
    if request.method == 'OPTIONS':
        # Allows GET requests from any origin with the Content-Type
        # header and caches preflight response for an 3600s
        headers = {
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Methods': 'GET,POST',
            'Access-Control-Allow-Headers': 'Content-Type',
            'Access-Control-Max-Age': '3600'
        }

        return ('okay done', 204, headers)

    from stellar_sdk import Server, Keypair, TransactionBuilder, Network, Asset

    request_json = request.get_json()
    cash = request_json["money"]
    print(cash)

    source_keypair = Keypair.from_secret("xxxxxxxxxxxxxxxxxxxxxxxxxxx")
    server = Server(horizon_url="https://horizon-testnet.stellar.org")
    source_account = server.load_account(account_id=source_keypair.public_key)

    base_fee = server.fetch_base_fee()
    path = []

    transaction = (TransactionBuilder(
        source_account=source_account,
        network_passphrase=Network.TESTNET_NETWORK_PASSPHRASE,
        base_fee=base_fee,
    ).append_path_payment_op(
        destination="GDYC7QBANT5HCU3CAJVYDBDMGKUMOSWRULN737XRSDV56HIGSIUEQ6WJ",
        send_code="XLM",
        send_issuer=None,
        send_max="100",
        dest_code="USD",
        dest_issuer="GACN4CNWBINPRWT2YKXXMEIPIBL5PEJNSKEBNOGCCXDKZBE5M44YFNXB",
        dest_amount=str(cash),
        path=path).set_timeout(30).build())
    transaction.sign(source_keypair)
    res = server.submit_transaction(transaction)
    print(res)
    import json
    import flask
    request_json = request.get_json()
    response = flask.jsonify(
        "https://horizon-testnet.stellar.org/accounts/GDYC7QBANT5HCU3CAJVYDBDMGKUMOSWRULN737XRSDV56HIGSIUEQ6WJ"
    )
    response.headers.set('Access-Control-Allow-Origin', '*')
    response.headers.set('Access-Control-Allow-Methods', 'GET, POST')
    response.headers.set('Access-Control-Allow-Headers', 'Content-Type')
    return response
コード例 #16
0
ファイル: makeaccount.py プロジェクト: ellieya/hacknyu2020
def make_account():
    keypair = Keypair.random()

    print("Public Key: " + keypair.public_key)
    print("Secret Seed: " + keypair.secret)

    server = Server(horizon_url="https://horizon-testnet.stellar.org")

    url = 'https://friendbot.stellar.org'
    response = requests.get(url, params={'addr': keypair.public_key})
    print(response)

    source_keypair = Keypair.from_secret(keypair.secret)
    source_public_key = source_keypair.public_key
    source_account = server.load_account(source_public_key)
    base_fee = server.fetch_base_fee()

    transaction = (
        TransactionBuilder(
            source_account=source_account,
            network_passphrase=Network.TESTNET_NETWORK_PASSPHRASE,
            base_fee=base_fee,
        ).append_change_trust_op(
            "SAVEPOINTS",
            "GDG4SRXHATOQPRDAMK45YHL42N3RMQ6UJYAS2ETJQ2I5XZYSIQLCSGV6").
        set_timeout(
            30)  # Make this transaction valid for the next 30 seconds only
        .build())

    transaction.sign(source_keypair)
    print(transaction.to_xdr())
    response = server.submit_transaction(transaction)
    #print(response)

    return keypair.public_key, keypair.secret
コード例 #17
0
 def crearAssets(self, codigo, monto, emisor):
     server = Server(horizon_url=self.Horizon_url)
     root_keypair = Keypair.from_secret(self.sLlave)
     root_account = server.load_account(account_id=root_keypair.public_key)
     transaction = TransactionBuilder(
         source_account=root_account,
         network_passphrase=self.networkTrabajar,
         base_fee=100).append_change_trust_op(limit=monto,
                                              asset_code=str(codigo),
                                              asset_issuer=emisor).build()
     transaction.sign(root_keypair)
     try:
         response = server.submit_transaction(transaction)
         return [True, response]
     except exceptions.BadRequestError as d:
         return [False, d]
コード例 #18
0
def make_bids(asset_code, issuing_keypair, distributing_keypair,
              market_supply):
    # Talk to Horizon testnet instance.
    server = Server(horizon_url=TESTNET)

    # Fetch the current sequence number for the source account from Horizon.
    source_account = server.load_account(distributing_keypair.public_key)

    # Build transaction around manage buy offer operation (setting market bids).
    transaction = (
        TransactionBuilder(
            source_account=source_account,
            network_passphrase=Network.TESTNET_NETWORK_PASSPHRASE,
            base_fee=100,  # too lazy to fetch :)
        ).append_manage_buy_offer_op(
            'XLM', None, asset_code, issuing_keypair.public_key,
            market_supply, '.08').append_manage_buy_offer_op(
                'XLM', None, asset_code, issuing_keypair.public_key,
                market_supply,
                '.09').append_manage_buy_offer_op('XLM', None, asset_code,
                                                  issuing_keypair.public_key,
                                                  market_supply,
                                                  '.10').build())

    # Sign transaction with distributor private key.
    transaction.sign(distributing_keypair)

    # Submit signed transaction to Horizon.
    response = server.submit_transaction(transaction)
    print(json.dumps(response, indent=2))
コード例 #19
0
def sendPayment(sender_sKey, destination_pKey, amount, asset_code):
    server - Server("https://horizon-testnet.stellar.org")
    source_key = Keypair.from_secret(sender_sKey)
    destination_id = destination_pKey

    try:
        server.load_account(destination_id)
    except NotFoundError:
        #Shouldn't be a problem since we're using fundraiser wallets (will verify when creating fundraisers/accounts)
        raise Exception("THe destination account is invalid")
    # If there was no error, load up-to-date information on your account.
    source_account = server.load_account(source_key.public_key)
    # Let's fetch base_fee from network
    base_fee = server.fetch_base_fee()
    transaction = (
        TransactionBuilder(
            source_account=source_account,
            network_passphrase=Network.TESTNET_NETWORK_PASSPHRASE,
            base_fee=base_fee).append_payment_op(destination=destination_id,
                                                 amount=str(amount),
                                                 asset_code=asset_code)
        # .add_text_memo() // COULD ADD DETAILS TO TRANSACTION
        .set_timeout(10).build())

    #Proof of identity of sender
    transaction.sign(source_key)

    try:
        #Sending the transaction to Stellar
        response = server.submit_transaction(transaction)
        print(f"Response: {response}")
    except (BadRequestError, BadResponseError) as err:
        print(f"Something went wrong!\n{err}")
コード例 #20
0
    def _change_trustline(self, asset_code, issuer, limit=None, secret=None):
        """Create a trustline between you and the issuer of an asset.
        :param asset_code: code which form the asset. For example: 'BTC', 'TFT', ...
        :type asset_code: str
        :param issuer: address of the asset issuer.
        :type issuer: str
        :param limit: The limit for the asset, defaults to max int64(922337203685.4775807). If the limit is set to “0” it deletes the trustline
        """
        # if no secret is provided we assume we change trustlines for this account
        if secret is None:
            secret = self.secret

        server = self._get_horizon_server()
        source_keypair = Keypair.from_secret(secret)
        source_public_key = source_keypair.public_key
        source_account = server.load_account(source_public_key)

        base_fee = server.fetch_base_fee()

        transaction = (TransactionBuilder(
            source_account=source_account,
            network_passphrase=_NETWORK_PASSPHRASES[str(self.network)],
            base_fee=base_fee,
        ).append_change_trust_op(asset_issuer=issuer,
                                 asset_code=asset_code,
                                 limit=limit).set_timeout(30).build())

        transaction.sign(source_keypair)

        try:
            response = server.submit_transaction(transaction)
            self._log_info("Transaction hash: {}".format(response["hash"]))
        except BadRequestError as e:
            self._log_debug(e)
            raise e
コード例 #21
0
 async def test_check_memo_required_with_fetch_account_error_raise_async(
         self, httpserver):
     self.__inject_mock_server(httpserver)
     horizon_url = httpserver.url_for("/")
     keypair = Keypair.from_secret(
         "SDQXFKA32UVQHUTLYJ42N56ZUEM5PNVVI4XE7EA5QFMLA2DHDCQX3GPY")
     account = Account(keypair.public_key, 1)
     async with Server(horizon_url, AiohttpClient()) as server:
         transaction = (TransactionBuilder(account).append_payment_op(
             self.DESTINATION_ACCOUNT_FETCH_ERROR, "10",
             "XLM").append_path_payment_strict_receive_op(
                 self.DESTINATION_ACCOUNT_NO_MEMO_REQUIRED,
                 "XLM",
                 None,
                 "10",
                 "BTC",
                 "GA7GYB3QGLTZNHNGXN3BMANS6TC7KJT3TCGTR763J4JOU4QHKL37RVV2",
                 "1",
                 [],
             ).append_path_payment_strict_send_op(
                 self.DESTINATION_ACCOUNT_NO_MEMO_REQUIRED,
                 "XLM",
                 None,
                 "10",
                 "BTC",
                 "GA7GYB3QGLTZNHNGXN3BMANS6TC7KJT3TCGTR763J4JOU4QHKL37RVV2",
                 "1",
                 [],
             ).append_account_merge_op(
                 self.DESTINATION_ACCOUNT_NO_MEMO_REQUIRED).build())
         transaction.sign(keypair)
         with pytest.raises(BadRequestError) as err:
             await server.submit_transaction(transaction)
         assert err.value.status == 400
コード例 #22
0
    def _set_escrow_account_signers(self, address, public_key_signer,
                                    preauth_tx_hash, signer_kp):
        horizon_server = self._get_horizon_server()
        if address == self.address:
            account = self.load_account()
        else:
            account = horizon_server.load_account(address)

        base_fee = horizon_server.fetch_base_fee()
        tx = (TransactionBuilder(
            account,
            network_passphrase=_NETWORK_PASSPHRASES[str(self.network)],
            base_fee=base_fee).append_pre_auth_tx_signer(
                preauth_tx_hash, 1).append_ed25519_public_key_signer(
                    public_key_signer,
                    1).append_set_options_op(master_weight=1,
                                             low_threshold=2,
                                             med_threshold=2,
                                             high_threshold=2).build())

        tx.sign(signer_kp)
        response = horizon_server.submit_transaction(tx)
        self._log_info(response)
        self._log_info(
            "Set the signers of {address} to {pk_signer} and {preauth_hash_signer}"
            .format(address=address,
                    pk_signer=public_key_signer,
                    preauth_hash_signer=preauth_tx_hash))
コード例 #23
0
ファイル: transaction.py プロジェクト: PyClin/gg
def employee_user_claimable_transaction(cbtxn: ClaimableBalanceTransaction):

    source_keypair = Keypair.from_secret(cbtxn.sender_private_key)
    source_account = server.load_account(source_keypair.public_key)

    receiver_address = cbtxn.recipient_public_key

    sponsor_keypair = Keypair.from_secret(cbtxn.sponsor_private_key)
    sponsor_account = server.load_account(sponsor_keypair.public_key)

    claimant = Claimant(destination=source_keypair.public_key)

    base_fee = server.fetch_base_fee()

    create_claimable_balance_te = (
        TransactionBuilder(source_account=source_account,
                           network_passphrase=Network.
                           TESTNET_NETWORK_PASSPHRASE).add_text_memo(
                               cbtxn.memo)  # less than 28 bytes
        .append_payment_op(
            receiver_address, cbtxn.amount, inr_asset.code,
            inr_asset.issuer).append_create_claimable_balance_op(
                inr_asset, cbtxn.amount, [claimant],
                sponsor_keypair.public_key)  # TODO: nested claims
        .build())

    create_claimable_balance_te.sign(source_keypair)
    create_claimable_balance_te.sign(sponsor_keypair)

    fee_bump_resp = fee_bumped_operation(create_claimable_balance_te,
                                         fee_source_private_key)

    return fee_bump_resp["hash"]
コード例 #24
0
    def test_to_xdr_with_inner_muxed_account_source(self):
        inner_keypair = Keypair.from_secret(
            "SBKTIFHJSS3JJWEZO2W74DZSA45WZU56LOL3AY7GAW63BXPEJQFYV53E"
        )
        inner_source = Account(inner_keypair.public_key, 7)
        destination = "GDQERENWDDSQZS7R7WKHZI3BSOYMV3FSWR7TFUYFTKQ447PIX6NREOJM"
        amount = "2000.0000000"
        inner_tx = (
            TransactionBuilder(
                inner_source, Network.TESTNET_NETWORK_PASSPHRASE, 200, v1=True
            )
            .append_payment_op(destination=destination, amount=amount, asset_code="XLM")
            .add_time_bounds(0, 0)
            .build()
        )
        inner_tx.sign(inner_keypair)
        fee_source = Keypair.from_secret(
            "SB7ZMPZB3YMMK5CUWENXVLZWBK4KYX4YU5JBXQNZSK2DP2Q7V3LVTO5V"
        )
        base_fee = 200
        fee_bump_tx = TransactionBuilder.build_fee_bump_transaction(
            "MAAAAAAAAAAAH2HAJCI3MGHFBTF7D7MUPSRWDE5QZLWLFND7GLJQLGVBZZ66RP43CKRMY",
            base_fee,
            inner_tx,
            Network.TESTNET_NETWORK_PASSPHRASE,
        )
        fee_bump_tx.sign(fee_source)
        # xdr = "AAAABQAAAADgSJG2GOUMy/H9lHyjYZOwyuyytH8y0wWaoc596L+bEgAAAAAAAAGQAAAAAgAAAAAcVPE+R/n1VnbIrAK3tu5yVfTkhkqVz04ShWk2SrF3wAAAAMgAAAAAAAAACAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAQAAAADgSJG2GOUMy/H9lHyjYZOwyuyytH8y0wWaoc596L+bEgAAAAAAAAAEqBfIAAAAAAAAAAABSrF3wAAAAEAordQh63kT50muRLVYaWW7Pgtt8i1tc4t9Bv9MWFWFN3WfTHSU2Jxv7hedjZEyfBPvaS/XnwvYJFcHgPDd1JkNAAAAAAAAAAHov5sSAAAAQKu/RuArXn/P13IIJ8WlnVDStwOquXM0CsWzA4ooZY6gqJ3k1EfmMVIJ0cir0bMTJD9r+g2IUZCANU7wdC38PA0="

        # assert fee_bump_tx.to_xdr() == xdr
        restore_te = FeeBumpTransactionEnvelope.from_xdr(
            fee_bump_tx.to_xdr(), Network.TESTNET_NETWORK_PASSPHRASE
        )
        assert (
            restore_te.to_xdr()
            == TransactionBuilder.from_xdr(
                fee_bump_tx.to_xdr(), Network.TESTNET_NETWORK_PASSPHRASE
            ).to_xdr()
        )
        assert isinstance(restore_te, FeeBumpTransactionEnvelope)
        restore_tx = restore_te.transaction
        assert isinstance(restore_tx, FeeBumpTransaction)
        assert restore_tx.fee_source == MuxedAccount.from_account(
            "MAAAAAAAAAAAH2HAJCI3MGHFBTF7D7MUPSRWDE5QZLWLFND7GLJQLGVBZZ66RP43CKRMY"
        )
        assert restore_tx.base_fee == base_fee
        assert restore_tx.inner_transaction_envelope.to_xdr() == inner_tx.to_xdr()
コード例 #25
0
    def stream_transaction_to_network(self,
                                      private_key: str,
                                      amount: str,
                                      tx_data: dict,
                                      dev_fee_status: bool = None):
        """
        Place Transaction on the network
        """
        key_pair = Keypair.from_secret(private_key)
        source_account = self.backoffice.stellar_wallet.server.load_account(
            key_pair.public_key)
        tx = TransactionBuilder(
            source_account=source_account,
            network_passphrase=Network.TESTNET_NETWORK_PASSPHRASE,
            base_fee=self.server.fetch_base_fee()).append_payment_op(
                destination=tx_data["toAddress"],
                asset_code="XLM",
                amount=tx_data["netValue"]).add_text_memo(
                    memo_text=tx_data["memo"])

        # Append Dev fee if selected
        if dev_fee_status:
            p = Payment(destination=self.backoffice.stellar_wallet.dev_key,
                        asset=Asset.native(),
                        amount=tx_data["devFee"])
            tx.append_operation(operation=p)

        new_tx = tx.set_timeout(10).build()
        new_tx.sign(signer=private_key)

        try:
            # Sign Submit transaction to server
            result = self.server.submit_transaction(new_tx)

            return True, result
        except BadRequestError as e:
            print(f'Bad request {e}')
            return False, e
        except BadResponseError as e:
            print(f'Bad response {e}')
            return False, e
        except MemoInvalidException as e:
            print(f'Invalid memo {e}')
            return False, e
        except Exception as e:
            print(f'Else: {e}')
            return False, e
コード例 #26
0
ファイル: managepoints.py プロジェクト: ellieya/hacknyu2020
def transfer_points(source_secret_key,
                    receiver_public_key,
                    num_points,
                    memo=""):
    #source is distributor

    source_keypair = Keypair.from_secret(source_secret_key)
    source_public_key = source_keypair.public_key

    server = Server(horizon_url="https://horizon-testnet.stellar.org")

    source_account = server.load_account(source_public_key)
    base_fee = server.fetch_base_fee()

    # if you want to submit to the public network, please use `Network.PUBLIC_NETWORK_PASSPHRASE`.

    if memo == "":
        transaction = (
            TransactionBuilder(
                source_account=source_account,
                network_passphrase=Network.TESTNET_NETWORK_PASSPHRASE,
                base_fee=base_fee,
            ).append_payment_op(
                receiver_public_key, str(num_points), "SAVEPOINTS",
                "GDG4SRXHATOQPRDAMK45YHL42N3RMQ6UJYAS2ETJQ2I5XZYSIQLCSGV6").
            set_timeout(
                30)  # Make this transaction valid for the next 30 seconds only
            .build())

    else:
        transaction = (
            TransactionBuilder(
                source_account=source_account,
                network_passphrase=Network.TESTNET_NETWORK_PASSPHRASE,
                base_fee=base_fee,
            ).append_payment_op(
                receiver_public_key, str(num_points), "SAVEPOINTS",
                "GDG4SRXHATOQPRDAMK45YHL42N3RMQ6UJYAS2ETJQ2I5XZYSIQLCSGV6").
            add_text_memo(memo).set_timeout(
                30)  # Make this transaction valid for the next 30 seconds only
            .build())

    transaction.sign(source_keypair)
    print(transaction.to_xdr())
    response = server.submit_transaction(transaction)
    print(response)
コード例 #27
0
ファイル: transaction.py プロジェクト: PyClin/gg
def claim_claimable_balance_operation(claimant_private_key, balance_ids):

    claimant_keypair = Keypair.from_secret(claimant_private_key)
    claimant_account = server.load_account(claimant_keypair.public_key)

    claim_claimable_balance_txn = TransactionBuilder(
        claimant_account, Network.TESTNET_NETWORK_PASSPHRASE)

    for balance_id in balance_ids:
        claim_claimable_balance_txn = (
            claim_claimable_balance_txn.append_claim_claimable_balance_op(
                balance_id, claimant_keypair.public_key))

    claim_claimable_balance_te = claim_claimable_balance_txn.build()
    claim_claimable_balance_te.sign(claimant_keypair)

    return claim_claimable_balance_te
コード例 #28
0
    def test_to_source_muxed_xdr(self):
        inner_keypair = Keypair.from_secret(
            "SBKTIFHJSS3JJWEZO2W74DZSA45WZU56LOL3AY7GAW63BXPEJQFYV53E")
        inner_source = Account(inner_keypair.public_key, 7)
        destination = "GDQERENWDDSQZS7R7WKHZI3BSOYMV3FSWR7TFUYFTKQ447PIX6NREOJM"
        amount = "2000.0000000"
        inner_tx = (TransactionBuilder(inner_source,
                                       Network.TESTNET_NETWORK_PASSPHRASE,
                                       200,
                                       v1=True).append_payment_op(
                                           destination=destination,
                                           amount=amount,
                                           asset_code="XLM").add_time_bounds(
                                               0, 0).build())
        inner_tx.sign(inner_keypair)
        fee_source = Keypair.from_secret(
            "SB7ZMPZB3YMMK5CUWENXVLZWBK4KYX4YU5JBXQNZSK2DP2Q7V3LVTO5V")
        fee_source2 = Keypair.from_secret(
            "SCVFDAOOXWR5TSPZF5U2MIE6V7M4LTOCNCD624Q6AEVBZ2XMH7HOWFZL")
        base_fee = 200
        fee_bump_tx = TransactionBuilder.build_fee_bump_transaction(
            fee_source.public_key,
            base_fee,
            inner_tx,
            Network.TESTNET_NETWORK_PASSPHRASE,
        )
        fee_bump_tx.sign(fee_source)
        xdr = "AAAABQAAAADgSJG2GOUMy/H9lHyjYZOwyuyytH8y0wWaoc596L+bEgAAAAAAAAGQAAAAAgAAAAAcVPE+R/n1VnbIrAK3tu5yVfTkhkqVz04ShWk2SrF3wAAAAMgAAAAAAAAACAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAQAAAADgSJG2GOUMy/H9lHyjYZOwyuyytH8y0wWaoc596L+bEgAAAAAAAAAEqBfIAAAAAAAAAAABSrF3wAAAAEAordQh63kT50muRLVYaWW7Pgtt8i1tc4t9Bv9MWFWFN3WfTHSU2Jxv7hedjZEyfBPvaS/XnwvYJFcHgPDd1JkNAAAAAAAAAAHov5sSAAAAQKu/RuArXn/P13IIJ8WlnVDStwOquXM0CsWzA4ooZY6gqJ3k1EfmMVIJ0cir0bMTJD9r+g2IUZCANU7wdC38PA0="

        assert fee_bump_tx.to_xdr() == xdr
        restore_te = FeeBumpTransactionEnvelope.from_xdr(
            xdr, Network.TESTNET_NETWORK_PASSPHRASE)
        assert restore_te == fee_bump_tx
        assert restore_te.transaction == fee_bump_tx.transaction
        assert restore_te.transaction == FeeBumpTransaction.from_xdr(
            fee_bump_tx.transaction.to_xdr_object().to_xdr(),
            Network.TESTNET_NETWORK_PASSPHRASE,
        )
        assert (restore_te.to_xdr() == TransactionBuilder.from_xdr(
            xdr, Network.TESTNET_NETWORK_PASSPHRASE).to_xdr())
        assert (restore_te.transaction._fee_source_muxed.to_xdr() ==
                fee_source.xdr_muxed_account().to_xdr())
        restore_te.transaction.fee_source = fee_source2.public_key
        assert restore_te.transaction.fee_source.public_key == fee_source2.public_key
        assert restore_te.transaction._fee_source_muxed is None
コード例 #29
0
    def configurarBilleteraPrimeraVez(self, listaUsuarios, umbralLista):
        server = Server(horizon_url=self.Horizon_url)
        root_keypair = Keypair.from_secret(self.sLlave)
        root_account = server.load_account(account_id=root_keypair.public_key)
        base_fee = server.fetch_base_fee()

        transaction = TransactionBuilder(
            base_fee=base_fee,
            network_passphrase=self.networkTrabajar,
            source_account=root_account)\
            .append_set_options_op(master_weight=1,
                                low_threshold=int(umbralLista[1])-1,
                                med_threshold=int(umbralLista[1]),
                                high_threshold=int(umbralLista[0]))\
            .set_timeout(30)
        for i in listaUsuarios:
            transaction.append_ed25519_public_key_signer(account_id=i[3],
                                                         weight=1)

        transaction = transaction.build()
        transaction.sign(root_keypair)
        try:
            response = server.submit_transaction(transaction)
            return [True, response]
        except exceptions.BadRequestError as d:
            return [False, d]
        except exceptions.NotFoundError as n:
            return [False, n]
コード例 #30
0
 async def test_submit_transaction_with_te(self):
     xdr = "AAAAAHI7fpgo+b7tgpiFyYWimjV7L7IOYLwmQS7k7F8SronXAAAAZAE+QT4AAAAJAAAAAQAAAAAAAAAAAAAAAF1MG8cAAAAAAAAAAQAAAAAAAAAAAAAAAOvi1O/HEn+QgZJw+EMZBtwvTVNmpgvE9p8IRfwp0GY4AAAAAAExLQAAAAAAAAAAARKuidcAAABAJVc1ASGp35hUquGNbzzSqWPoTG0zgc89zc4p+19QkgbPqsdyEfHs7+ng9VJA49YneEXRa6Fv7pfKpEigb3VTCg=="
     te = TransactionBuilder.from_xdr(xdr,
                                      Network.PUBLIC_NETWORK_PASSPHRASE)
     horizon_url = "https://horizon.stellar.org"
     client = AiohttpClient()
     async with Server(horizon_url, client) as server:
         resp = await server.submit_transaction(te)
         assert resp["envelope_xdr"] == xdr