示例#1
0
def test_dedup_signatures(stubbed_blockhash):
    """Test signature deduplication."""
    acc1, acc2 = Account(), Account()
    transfer1 = sp.transfer(sp.TransferParams(from_pubkey=acc1.public_key(), to_pubkey=acc2.public_key(), lamports=123))
    transfer2 = sp.transfer(sp.TransferParams(from_pubkey=acc1.public_key(), to_pubkey=acc2.public_key(), lamports=123))
    txn = txlib.Transaction(recent_blockhash=stubbed_blockhash).add(transfer1, transfer2)
    txn.sign(acc1)
def test_transfer():
    """Test creating a transaction for transfer."""
    params = sp.TransferParams(from_pubkey=Account().public_key(),
                               to_pubkey=Account().public_key(),
                               lamports=123)
    txn = sp.transfer(params)
    assert len(txn.instructions) == 1
    assert sp.decode_transfer(txn.instructions[0]) == params
示例#3
0
def test_account_keypair():
    """Validate account keypair against account's private and public key."""
    expected_account = Account()
    keypair = expected_account.keypair()
    decoded_keypair = b58decode(keypair)

    actual_account = Account(decoded_keypair[:32])
    assert expected_account.public_key() == actual_account.public_key()
    assert expected_account.secret_key() == actual_account.secret_key()
def test_create_account():
    """Test creating a transaction for creat account."""
    params = sp.CreateAccountParams(
        from_pubkey=Account().public_key(),
        new_account_pubkey=Account().public_key(),
        lamports=123,
        space=1,
        program_id=PublicKey(1),
    )
    assert sp.decode_create_account(sp.create_account(params)) == params
示例#5
0
def test_transfer_signatures(stubbed_blockhash):
    """Test signing transfer transactions."""
    acc1, acc2 = Account(), Account()
    transfer1 = sp.transfer(sp.TransferParams(from_pubkey=acc1.public_key(), to_pubkey=acc2.public_key(), lamports=123))
    transfer2 = sp.transfer(sp.TransferParams(from_pubkey=acc2.public_key(), to_pubkey=acc1.public_key(), lamports=123))
    txn = txlib.Transaction(recent_blockhash=stubbed_blockhash).add(transfer1, transfer2)
    txn.sign(acc1, acc2)

    expected = txlib.Transaction(recent_blockhash=stubbed_blockhash, signatures=txn.signatures).add(
        transfer1, transfer2
    )
    assert txn == expected
示例#6
0
def test_sign_partial(stubbed_blockhash):
    """Test paritally sigining a transaction."""
    acc1, acc2 = Account(), Account()
    transfer = sp.transfer(sp.TransferParams(from_pubkey=acc1.public_key(), to_pubkey=acc2.public_key(), lamports=123))
    partial_txn = txlib.Transaction(recent_blockhash=stubbed_blockhash).add(transfer)
    partial_txn.sign_partial(acc1, acc2.public_key())
    assert len(partial_txn.signature()) == txlib.SIG_LENGTH
    assert len(partial_txn.signatures) == 2
    assert not partial_txn.signatures[1].signature

    partial_txn.add_signer(acc2)
    expected_txn = txlib.Transaction(recent_blockhash=stubbed_blockhash).add(transfer)
    expected_txn.sign(acc1, acc2)
    assert partial_txn == expected_txn
示例#7
0
async def test_token(alt_stubbed_sender, test_http_client_async) -> AsyncToken:
    """Test create mint."""
    resp = await test_http_client_async.request_airdrop(alt_stubbed_sender.public_key(), AIRDROP_AMOUNT)
    confirmed = await aconfirm_transaction(test_http_client_async, resp["result"])
    assert_valid_response(confirmed)

    expected_decimals = 6
    expected_freeze_authority = Account()
    token_client = await AsyncToken.create_mint(
        test_http_client_async,
        alt_stubbed_sender,
        alt_stubbed_sender.public_key(),
        expected_decimals,
        TOKEN_PROGRAM_ID,
        expected_freeze_authority.public_key(),
    )

    assert token_client.pubkey
    assert token_client.program_id == TOKEN_PROGRAM_ID
    assert token_client.payer.public_key() == alt_stubbed_sender.public_key()

    resp = await test_http_client_async.get_account_info(token_client.pubkey)
    assert_valid_response(resp)
    assert resp["result"]["value"]["owner"] == str(TOKEN_PROGRAM_ID)

    mint_data = layouts.MINT_LAYOUT.parse(decode_byte_string(resp["result"]["value"]["data"][0]))
    assert mint_data.is_initialized
    assert mint_data.decimals == expected_decimals
    assert mint_data.supply == 0
    assert PublicKey(mint_data.mint_authority) == alt_stubbed_sender.public_key()
    assert PublicKey(mint_data.freeze_authority) == expected_freeze_authority.public_key()
    return token_client
示例#8
0
def test_verify_confirmed_block(stubbed_blockhash):
    """Test verifying signature in a confirmed block."""
    acc0, acc1, acc2, acc3 = (Account() for _ in range(4))
    # Create a couple signed transaction
    txn1 = txlib.Transaction(recent_blockhash=stubbed_blockhash).add(
        transfer(
            TransferParams(from_pubkey=acc0.public_key(),
                           to_pubkey=acc1.public_key(),
                           lamports=123)))
    txn1.sign(acc0)
    txn2 = txlib.Transaction(recent_blockhash=stubbed_blockhash).add(
        transfer(
            TransferParams(from_pubkey=acc2.public_key(),
                           to_pubkey=acc3.public_key(),
                           lamports=456)))
    txn2.sign(acc2)
    # Build confirmed_block with dummy data for blockhases and balances
    confirmed_block = {
        "blockhash":
        stubbed_blockhash,
        "previousBlockhash":
        stubbed_blockhash,
        "transactions": [
            {
                "transaction": txn1,
                "meta": {
                    "fee": 0,
                    "preBalances": [100000, 100000, 1, 1, 1],
                    "postBalances": [99877, 100123, 1, 1, 1],
                    "status": {
                        "Ok": None
                    },
                    "err": None,
                },
            },
            {
                "transaction": txn2,
                "meta": {
                    "fee": 0,
                    "preBalances": [100000, 100000, 1, 1, 1],
                    "postBalances": [99544, 100456, 1, 1, 1],
                    "status": {
                        "Ok": None
                    },
                    "err": None,
                },
            },
        ],
        "rewards": [],
    }
    # Verify signatures in confirmed_block
    assert all(tx_with_meta["transaction"].verify_signatures()
               for tx_with_meta in confirmed_block["transactions"])
    # Test block with bogus signature
    bogus_signature = txlib._SigPubkeyPair(acc2.public_key(), bytes([9] * 64))  # pylint: disable=protected-access
    txn1.signatures[0] = bogus_signature
    bad_confirmed_block = confirmed_block
    bad_confirmed_block["transactions"][0]["transaction"] = txn1
    assert not all(tx_with_meta["transaction"].verify_signatures()
                   for tx_with_meta in confirmed_block["transactions"])
def test_assign():
    """Test creating a transaction for transfer."""
    params = sp.AssignParams(
        account_pubkey=Account().public_key(),
        program_id=PublicKey(1),
    )
    assert sp.decode_assign(sp.assign(params)) == params
示例#10
0
    def _create_account_args(
        self,
        owner: PublicKey,
        skip_confirmation: bool,
        balance_needed: int,
    ) -> Tuple[PublicKey, Transaction, Account, Account, TxOpts]:
        new_account = Account()
        # Allocate memory for the account

        # Construct transaction
        txn = Transaction()
        txn.add(
            sp.create_account(
                sp.CreateAccountParams(
                    from_pubkey=self.payer.public_key(),
                    new_account_pubkey=new_account.public_key(),
                    lamports=balance_needed,
                    space=ACCOUNT_LAYOUT.sizeof(),
                    program_id=self.program_id,
                )))
        txn.add(
            spl_token.initialize_account(
                spl_token.InitializeAccountParams(
                    account=new_account.public_key(),
                    mint=self.pubkey,
                    owner=owner,
                    program_id=self.program_id)))
        return (
            new_account.public_key(),
            txn,
            self.payer,
            new_account,
            TxOpts(skip_preflight=True, skip_confirmation=skip_confirmation),
        )
示例#11
0
def test_allocate():
    """Test creating a transaction for allocate."""
    params = sp.AllocateParams(
        account_pubkey=Account().public_key(),
        space=12345,
    )
    assert sp.decode_allocate(sp.allocate(params)) == params
示例#12
0
 def topup(self, api_endpoint, to, amount=None, skip_confirmation=True):
     """
     Send a small amount of native currency to the specified wallet to handle gas fees. Return a status flag of success or fail and the native transaction data.
     """
     msg = ""
     try:
         # Connect to the api_endpoint
         client = Client(api_endpoint)
         msg += "Initialized client"
         # List accounts
         sender_account = Account(self.private_key)
         dest_account = PublicKey(to)
         msg += " | Gathered accounts"
         # List signers
         signers = [sender_account]
         # Start transaction
         tx = Transaction()
         # Determine the amount to send
         try:
             if amount is None:
                 min_rent_reseponse = client.get_minimum_balance_for_rent_exemption(
                     ACCOUNT_LAYOUT.sizeof())
                 lamports = min_rent_reseponse["result"]
             else:
                 lamports = int(amount)
             msg += f" | Fetched lamports: {lamports * 1e-9} SOL"
         except Exception as e:
             msg += " | ERROR: couldn't process lamports"
             raise (e)
         # Generate transaction
         transfer_ix = transfer(
             TransferParams(from_pubkey=sender_account.public_key(),
                            to_pubkey=dest_account,
                            lamports=lamports))
         tx = tx.add(transfer_ix)
         msg += f" | Transferring funds"
         # Send request
         try:
             response = client.send_transaction(
                 tx,
                 *signers,
                 opts=types.TxOpts(skip_confirmation=skip_confirmation))
             return json.dumps({
                 'status':
                 HTTPStatus.OK,
                 'msg':
                 f"Successfully sent {lamports * 1e-9} SOL to {to}",
                 'tx':
                 response.get('result') if skip_confirmation else
                 response['result']['transaction']['signatures'],
             })
         except Exception as e:
             msg += f" | ERROR: Encountered exception while attempting to send transaction: {e}"
             raise (e)
     except Exception as e:
         return json.dumps({
             'status': HTTPStatus.BAD_REQUEST,
             'msg': msg,
         })
示例#13
0
 def mint_to(self,
             api_endpoint,
             pool_account,
             dest,
             amount,
             skip_confirmation=True):
     msg = ""
     client = Client(api_endpoint)
     msg += "Initialized client"
     # Create account objects
     source_account = Account(self.private_key)
     signers = [source_account]
     pool = self.load_binary_option(api_endpoint, pool_account)
     # List non-derived accounts
     pool_account = PublicKey(pool_account)
     dest_account = PublicKey(dest)
     escrow_mint_account = PublicKey(pool["escrow_mint"])
     mint_authority_account = source_account.public_key()
     payer_account = source_account.public_key()
     token_account = PublicKey(TOKEN_PROGRAM_ID)
     tx = Transaction()
     token_pda_address = get_associated_token_address(
         dest_account, escrow_mint_account)
     associated_token_account_ix = create_associated_token_account(
         payer=payer_account,
         owner=dest_account,
         mint=escrow_mint_account,
     )
     tx = tx.add(associated_token_account_ix)
     mint_to_ix = mint_to(
         MintToParams(
             program_id=token_account,
             mint=escrow_mint_account,
             dest=token_pda_address,
             mint_authority=mint_authority_account,
             amount=int(amount),
             signers=[mint_authority_account],
         ))
     tx = tx.add(mint_to_ix)
     # Send request
     try:
         response = client.send_transaction(
             tx,
             *signers,
             opts=types.TxOpts(skip_confirmation=skip_confirmation))
         return json.dumps({
             'status':
             HTTPStatus.OK,
             'msg':
             msg + f" | MintTo {dest} successful",
             'tx':
             response.get('result') if skip_confirmation else
             response['result']['transaction']['signatures'],
         })
     except Exception as e:
         msg += f" | ERROR: Encountered exception while attempting to send transaction: {e}"
         raise (e)
示例#14
0
    def create_mint(
        conn: Client,
        payer: Account,
        mint_authority: PublicKey,
        decimals: int,
        program_id: PublicKey,
        freeze_authority: Optional[PublicKey] = None,
        skip_confirmation: bool = False,
    ) -> Token:
        """Create and initialize a token.

        :param conn: RPC connection to a solana cluster.
        :param payer: Fee payer for transaction.
        :param mint_authority: Account or multisig that will control minting.
        :param decimals: Location of the decimal place.
        :param program_id: SPL Token program account.
        :param freeze_authority: (optional) Account or multisig that can freeze token accounts.
        :param skip_confirmation: (optional) Option to skip transaction confirmation.
        :return: Token object for the newly minted token.

        If skip confirmation is set to `False`, this method will block for at most 30 seconds
        or until the transaction is confirmed.
        """
        mint_account = Account()
        token = Token(conn, mint_account.public_key(), program_id, payer)
        # Allocate memory for the account
        balance_needed = Token.get_min_balance_rent_for_exempt_for_mint(conn)
        # Construct transaction
        txn = Transaction()
        txn.add(
            sp.create_account(
                sp.CreateAccountParams(
                    from_pubkey=payer.public_key(),
                    new_account_pubkey=mint_account.public_key(),
                    lamports=balance_needed,
                    space=MINT_LAYOUT.sizeof(),
                    program_id=program_id,
                )
            )
        )
        txn.add(
            spl_token.initialize_mint(
                spl_token.InitializeMintParams(
                    program_id=program_id,
                    mint=mint_account.public_key(),
                    decimals=decimals,
                    mint_authority=mint_authority,
                    freeze_authority=freeze_authority,
                )
            )
        )
        # Send the two instructions
        conn.send_transaction(
            txn, payer, mint_account, opts=TxOpts(skip_confirmation=skip_confirmation, skip_preflight=True)
        )
        return token
示例#15
0
    def __init__(self, upper: float, lower: float, amount: float, grid: int,
                 pair: str, base: str, quote: str, owner: str, private: str):
        """
        :params upper: price up
        :params lower: price down
        :params amount: amount of the order
        :params grid: amount of grid
        :params pair: dexlab trading pair address
        :params base: youur base coin address for trading
        :params quote: your quote coin address for trading
        :params owner: your solana wallet address
        :params private: your private key for pay the transaction gas
        """

        self.upper = upper
        self.lower = lower
        self.amount = amount
        self.grid = grid
        self.pair = pair
        self.base = base
        self.quote = quote
        self.owner = owner
        self.key = base58.b58decode(private)
        self.payer = Account(self.key[:32])
        self.client = Client('', '')
        self.cc = conn('https://api.mainnet-beta.solana.com/')
        self.market = Market.load(
            self.cc,
            PublicKey(self.pair),
            program_id=PublicKey(
                '9xQeWvG816bUx9EPjHmaT23yvVM2ZWbrrpZb9PusVFin'))
        try:
            self.open_acc = self.market.find_open_orders_accounts_for_owner(
                self.payer.public_key())[0].address
        except:
            self.open_acc = ''
        self.base_decimal = self.market.state.base_spl_token_decimals()
        self.quote_decimal = self.market.state.quote_spl_token_decimals()
        print(f'Initialize...\n\n'
              f'----parameters----\n\n'
              f'upper: {self.upper}\n'
              f'lower: {self.lower}\n'
              f'amount: {self.amount}\n'
              f'grid: {self.grid}\n'
              f'base decimal: {self.base_decimal}\n'
              f'quote decimal: {self.quote_decimal}\n'
              f'pair: {self.pair}\n'
              f'base: {self.base}\n'
              f'quote: {self.quote}\n'
              f'owner: {self.owner}\n'
              f'open orders account: {self.open_acc}\n'
              f'key: {self.key[:32]}\n\n'
              f'----start----\n')
示例#16
0
def test_allocate_with_seed():
    """Test creating a transaction for allocate with seed."""
    params = sp.AllocateWithSeedParams(
        account_pubkey=Account().public_key(),
        base_pubkey=PublicKey(1),
        seed={
            "length": 4,
            "chars": "gqln"
        },
        space=65537,
        program_id=PublicKey(2),
    )
    assert sp.decode_allocate_with_seed(sp.allocate(params)) == params
示例#17
0
    def create_account(
        self,
        owner: PublicKey,
        skip_confirmation: bool = False,
    ) -> PublicKey:
        """Create and initialize a new account.

        This account may then be used as a `transfer()` or `approve()` destination.

        :param owner: User account that will own the new account.
        :param skip_confirmation: (optional) Option to skip transaction confirmation.
        :return: Public key of the new empty account.

        If skip confirmation is set to `False`, this method will block for at most 30 seconds
        or until the transaction is confirmed.
        """
        new_account = Account()
        # Allocate memory for the account
        balance_needed = Token.get_min_balance_rent_for_exempt_for_account(
            self._conn)
        # Construct transaction
        txn = Transaction()
        txn.add(
            sp.create_account(
                sp.CreateAccountParams(
                    from_pubkey=self.payer.public_key(),
                    new_account_pubkey=new_account.public_key(),
                    lamports=balance_needed,
                    space=ACCOUNT_LAYOUT.sizeof(),
                    program_id=self.program_id,
                )))
        txn.add(
            spl_token.initialize_account(
                spl_token.InitializeAccountParams(
                    account=new_account.public_key(),
                    mint=self.pubkey,
                    owner=owner,
                    program_id=self.program_id)))
        # Send the two instructions
        self._conn.send_transaction(txn,
                                    self.payer,
                                    new_account,
                                    opts=TxOpts(
                                        skip_preflight=True,
                                        skip_confirmation=skip_confirmation))
        return new_account.public_key()
示例#18
0
 def settle(self,
            api_endpoint,
            pool_account,
            winning_mint,
            skip_confirmation=True):
     msg = ""
     client = Client(api_endpoint)
     msg += "Initialized client"
     # Create account objects
     source_account = Account(self.private_key)
     # Signers
     signers = [source_account]
     # List non-derived accounts
     pool_account = PublicKey(pool_account)
     winning_mint_account = PublicKey(winning_mint)
     tx = Transaction()
     settle_ix = settle_instruction(
         pool_account,
         winning_mint_account,
         source_account.public_key(),
     )
     tx = tx.add(settle_ix)
     # Send request
     try:
         response = client.send_transaction(
             tx,
             *signers,
             opts=types.TxOpts(skip_confirmation=skip_confirmation))
         return json.dumps({
             'status':
             HTTPStatus.OK,
             'msg':
             msg +
             f" | Settle successful, winner: {str(winning_mint_account)}",
             'tx':
             response.get('result') if skip_confirmation else
             response['result']['transaction']['signatures'],
         })
     except Exception as e:
         msg += f" | ERROR: Encountered exception while attempting to send transaction: {e}"
         raise (e)
示例#19
0
def test_generate_account_from_secret_key():
    """Generate an account with provided secret key."""
    secret_key = bytes(
        [
            153,
            218,
            149,
            89,
            225,
            94,
            145,
            62,
            233,
            171,
            46,
            83,
            227,
            223,
            173,
            87,
            93,
            163,
            59,
            73,
            190,
            17,
            37,
            187,
            146,
            46,
            51,
            73,
            79,
            73,
            136,
            40,
        ]
    )
    acc = Account(secret_key)
    assert str(acc.public_key()) == "2q7pyhPwAwZ3QMfZrnAbDhnh9mDUqycszcpf86VgQxhF"
示例#20
0
    def _create_wrapped_native_account_args(
        program_id: PublicKey,
        owner: PublicKey,
        payer: Account,
        amount: int,
        skip_confirmation: bool,
        balance_needed: int,
    ) -> Tuple[PublicKey, Transaction, Account, Account, TxOpts]:
        new_account = Account()
        # Allocate memory for the account
        # Construct transaction
        txn = Transaction()
        txn.add(
            sp.create_account(
                sp.CreateAccountParams(
                    from_pubkey=payer.public_key(),
                    new_account_pubkey=new_account.public_key(),
                    lamports=balance_needed,
                    space=ACCOUNT_LAYOUT.sizeof(),
                    program_id=program_id,
                )))

        txn.add(
            sp.transfer(
                sp.TransferParams(from_pubkey=payer.public_key(),
                                  to_pubkey=new_account.public_key(),
                                  lamports=amount)))

        txn.add(
            spl_token.initialize_account(
                spl_token.InitializeAccountParams(
                    account=new_account.public_key(),
                    mint=WRAPPED_SOL_MINT,
                    owner=owner,
                    program_id=program_id)))

        return new_account.public_key(), txn, payer, new_account, TxOpts(
            skip_confirmation=skip_confirmation)
示例#21
0
 def _create_mint_args(
     conn: Union[Client, AsyncClient],
     payer: Account,
     mint_authority: PublicKey,
     decimals: int,
     program_id: PublicKey,
     freeze_authority: Optional[PublicKey],
     skip_confirmation: bool,
     balance_needed: int,
     cls: Union[Type[Token], Type[AsyncToken]],
 ) -> Tuple[Union[Token, AsyncToken], Transaction, Account, Account,
            TxOpts]:
     mint_account = Account()
     token = cls(conn, mint_account.public_key(), program_id,
                 payer)  # type: ignore
     # Construct transaction
     txn = Transaction()
     txn.add(
         sp.create_account(
             sp.CreateAccountParams(
                 from_pubkey=payer.public_key(),
                 new_account_pubkey=mint_account.public_key(),
                 lamports=balance_needed,
                 space=MINT_LAYOUT.sizeof(),
                 program_id=program_id,
             )))
     txn.add(
         spl_token.initialize_mint(
             spl_token.InitializeMintParams(
                 program_id=program_id,
                 mint=mint_account.public_key(),
                 decimals=decimals,
                 mint_authority=mint_authority,
                 freeze_authority=freeze_authority,
             )))
     return token, txn, payer, mint_account, TxOpts(
         skip_confirmation=skip_confirmation, skip_preflight=True)
示例#22
0
def test_generate_account():
    """Generate an account."""
    acc = Account()
    assert len(acc.secret_key()) == crypto_box_SECRETKEYBYTES
示例#23
0
 def create() -> "Wallet":
     new_account = Account()
     new_secret_key = new_account.secret_key()
     return Wallet(new_secret_key)
def test_transfer():
    """Test creating a transaction for transfer."""
    params = sp.TransferParams(from_pubkey=Account().public_key(),
                               to_pubkey=Account().public_key(),
                               lamports=123)
    assert sp.decode_transfer(sp.transfer(params)) == params
示例#25
0
    def place_order(  # pylint: disable=too-many-arguments,too-many-locals
        self,
        payer: PublicKey,
        owner: Account,
        order_type: OrderType,
        side: Side,
        limit_price: int,
        max_quantity: int,
        client_id: int = 0,
        opts: TxOpts = TxOpts(),
    ) -> RPCResponse:  # TODO: Add open_orders_address_key param and fee_discount_pubkey
        transaction = Transaction()
        signers: List[Account] = [owner]
        open_order_accounts = self.find_open_orders_accounts_for_owner(
            owner.public_key())
        if not open_order_accounts:
            new_open_orders_account = Account()
            mbfre_resp = self._conn.get_minimum_balance_for_rent_exemption(
                OPEN_ORDERS_LAYOUT.sizeof())
            balanced_needed = mbfre_resp["result"]
            transaction.add(
                make_create_account_instruction(
                    owner.public_key(),
                    new_open_orders_account.public_key(),
                    balanced_needed,
                    self.state.program_id(),
                ))
            signers.append(new_open_orders_account)
            # TODO: Cache new_open_orders_account

        # TODO: Handle open_orders_address_key
        # TODO: Handle fee_discount_pubkey

        if payer == owner.public_key():
            raise ValueError("Invalid payer account")

        # TODO: add integration test for SOL wrapping.
        should_wrap_sol = (side == side.Buy and self.state.quote_mint()
                           == WRAPPED_SOL_MINT) or (side == side.Sell
                                                    and self.state.base_mint
                                                    == WRAPPED_SOL_MINT)
        wrapped_sol_account = Account()
        if should_wrap_sol:
            transaction.add(
                create_account(
                    CreateAccountParams(
                        from_pubkey=owner.public_key(),
                        new_account_pubkey=wrapped_sol_account.public_key(),
                        lamports=Market._get_lamport_need_for_sol_wrapping(
                            limit_price, max_quantity, side,
                            open_order_accounts),
                        space=ACCOUNT_LEN,
                        program_id=TOKEN_PROGRAM_ID,
                    )))
            transaction.add(
                initialize_account(
                    InitializeAccountParams(
                        account=wrapped_sol_account.public_key(),
                        mint=WRAPPED_SOL_MINT,
                        owner=owner.public_key(),
                        program_id=SYSVAR_RENT_PUBKEY,
                    )))

        transaction.add(
            self.make_place_order_instruction(
                wrapped_sol_account.public_key() if should_wrap_sol else payer,
                owner,
                order_type,
                side,
                limit_price,
                max_quantity,
                client_id,
                open_order_accounts[0].address if open_order_accounts else
                new_open_orders_account.public_key(),
            ))

        if should_wrap_sol:
            transaction.add(
                close_account(
                    CloseAccountParams(
                        account=wrapped_sol_account.public_key(),
                        owner=owner.public_key(),
                        dest=owner.public_key(),
                    )))
        # TODO: extract `make_place_order_transaction`.
        return self._conn.send_transaction(transaction, *signers, opts=opts)
示例#26
0
def stubbed_sender() -> Account:
    """Arbitrary known account to be used as sender."""
    return Account(bytes([8] * PublicKey.LENGTH))
示例#27
0
 def trade(self,
           api_endpoint,
           pool_account,
           buyer_encrypted_private_key,
           seller_encrypted_private_key,
           size,
           buyer_price,
           seller_price,
           skip_confirmation=True):
     msg = ""
     client = Client(api_endpoint)
     msg += "Initialized client"
     # Create account objects
     buyer_private_key = list(
         self.cipher.decrypt(buyer_encrypted_private_key))
     seller_private_key = list(
         self.cipher.decrypt(seller_encrypted_private_key))
     assert (len(buyer_private_key) == 32)
     assert (len(seller_private_key) == 32)
     source_account = Account(self.private_key)
     buyer = Account(buyer_private_key)
     seller = Account(seller_private_key)
     # Signers
     signers = [buyer, seller, source_account]
     pool = self.load_binary_option(api_endpoint, pool_account)
     # List non-derived accounts
     pool_account = PublicKey(pool_account)
     escrow_account = PublicKey(pool["escrow"])
     escrow_mint_account = PublicKey(pool["escrow_mint"])
     long_token_mint_account = PublicKey(pool["long_mint"])
     short_token_mint_account = PublicKey(pool["short_mint"])
     buyer_account = buyer.public_key()
     seller_account = seller.public_key()
     token_account = PublicKey(TOKEN_PROGRAM_ID)
     escrow_owner_account = PublicKey.find_program_address(
         [
             bytes(long_token_mint_account),
             bytes(short_token_mint_account),
             bytes(token_account),
             bytes(PublicKey(BINARY_OPTION_PROGRAM_ID))
         ],
         PublicKey(BINARY_OPTION_PROGRAM_ID),
     )[0]
     # Transaction
     tx = Transaction()
     atas = []
     for acct in [buyer_account, seller_account]:
         acct_atas = []
         for mint_account in (long_token_mint_account,
                              short_token_mint_account,
                              escrow_mint_account):
             token_pda_address = get_associated_token_address(
                 acct, mint_account)
             associated_token_account_info = client.get_account_info(
                 token_pda_address)
             account_info = associated_token_account_info['result']['value']
             if account_info is not None:
                 account_state = ACCOUNT_LAYOUT.parse(
                     base64.b64decode(account_info['data'][0])).state
             else:
                 account_state = 0
             if account_state == 0:
                 msg += f" | Creating PDA: {token_pda_address}"
                 associated_token_account_ix = create_associated_token_account(
                     payer=source_account.public_key(),
                     owner=acct,
                     mint=mint_account,
                 )
                 tx = tx.add(associated_token_account_ix)
             else:
                 msg += f" | Fetched PDA: {token_pda_address}"
             acct_atas.append(token_pda_address)
         atas.append(acct_atas)
     trade_ix = trade_instruction(
         pool_account,
         escrow_account,
         long_token_mint_account,
         short_token_mint_account,
         buyer_account,
         seller_account,
         atas[0][2],
         atas[1][2],
         atas[0][0],
         atas[0][1],
         atas[1][0],
         atas[1][1],
         escrow_owner_account,
         token_account,
         int(size),
         int(buyer_price),
         int(seller_price),
     )
     tx = tx.add(trade_ix)
     # Send request
     try:
         response = client.send_transaction(
             tx,
             *signers,
             opts=types.TxOpts(skip_confirmation=skip_confirmation))
         return json.dumps({
             'status':
             HTTPStatus.OK,
             'msg':
             msg + f" | Trade successful",
             'tx':
             response.get('result') if skip_confirmation else
             response['result']['transaction']['signatures'],
         })
     except Exception as e:
         msg += f" | ERROR: Encountered exception while attempting to send transaction: {e}"
         raise (e)
示例#28
0
 def collect(self,
             api_endpoint,
             pool_account,
             collector,
             skip_confirmation=True):
     msg = ""
     client = Client(api_endpoint)
     msg += "Initialized client"
     signers = [Account(self.private_key)]
     pool = self.load_binary_option(api_endpoint, pool_account)
     pool_account = PublicKey(pool_account)
     collector_account = PublicKey(collector)
     escrow_account = PublicKey(pool["escrow"])
     escrow_mint_account = PublicKey(pool["escrow_mint"])
     long_token_mint_account = PublicKey(pool["long_mint"])
     short_token_mint_account = PublicKey(pool["short_mint"])
     token_account = PublicKey(TOKEN_PROGRAM_ID)
     escrow_authority_account = PublicKey.find_program_address(
         [
             bytes(long_token_mint_account),
             bytes(short_token_mint_account),
             bytes(token_account),
             bytes(PublicKey(BINARY_OPTION_PROGRAM_ID))
         ],
         PublicKey(BINARY_OPTION_PROGRAM_ID),
     )[0]
     # Transaction
     tx = Transaction()
     atas = []
     for mint_account in (long_token_mint_account, short_token_mint_account,
                          escrow_mint_account):
         token_pda_address = get_associated_token_address(
             collector_account, mint_account)
         associated_token_account_info = client.get_account_info(
             token_pda_address)
         account_info = associated_token_account_info['result']['value']
         if account_info is not None:
             account_state = ACCOUNT_LAYOUT.parse(
                 base64.b64decode(account_info['data'][0])).state
         else:
             account_state = 0
         if account_state == 0:
             msg += f" | Error Fetching PDA: {token_pda_address}"
             raise Exception()
         else:
             msg += f" | Fetched PDA: {token_pda_address}"
         atas.append(token_pda_address)
     collect_ix = collect_instruction(
         pool_account,
         collector_account,
         atas[0],
         atas[1],
         atas[2],
         long_token_mint_account,
         short_token_mint_account,
         escrow_account,
         escrow_authority_account,
         token_account,
     )
     tx = tx.add(collect_ix)
     try:
         response = client.send_transaction(
             tx,
             *signers,
             opts=types.TxOpts(skip_confirmation=skip_confirmation))
         return json.dumps({
             'status':
             HTTPStatus.OK,
             'msg':
             msg + f" | Collect successful",
             'tx':
             response.get('result') if skip_confirmation else
             response['result']['transaction']['signatures'],
         })
     except Exception as e:
         msg += f" | ERROR: Encountered exception while attempting to send transaction: {e}"
         print(msg)
         raise (e)
示例#29
0
quote_ccy = pair.split("/")[0]
quote_ccy_mint = {}
for mkt in get_token_mints():
    quote_ccy_mint.update({mkt.name: mkt.address})
print("Token Mint is: {}".format(quote_ccy_mint[quote_ccy]))

# %%

# Get private key and use that the create a new account
#pubkey = "GKksmU6hSJ2X7zz1mcE3Qhr7DDEpvxqbygzb17SxygUD"
f = open('./my-solana-wallet/my-keypair.json')
private_key = json.load(f)
mid = len(private_key) // 2
private_key = private_key[:mid]  # to 32 bytes
payer = Account(private_key)  # Your account to pay fees
print("Public Key is: {}".format(payer.public_key()))

# %%

cc = conn("https://api.mainnet-beta.solana.com/")

quote_token = Token(
    cc,
    pubkey=PublicKey(quote_ccy_mint[quote_ccy]),  # mint address of token
    program_id=TOKEN_PROGRAM_ID,
    payer=payer,
)

quote_wallet = quote_token.create_account(
    payer.public_key(),
示例#30
0
 def initialize(self,
                api_endpoint,
                escrow_mint,
                decimals=2,
                skip_confirmation=True):
     msg = ""
     # Initialize Clinet
     client = Client(api_endpoint)
     msg += "Initialized client"
     # Create account objects
     source_account = Account(self.private_key)
     pool = Account()
     long_escrow = Account()
     short_escrow = Account()
     long_mint = Account()
     short_mint = Account()
     # List non-derived accounts
     pool_account = pool.public_key()
     escrow_mint_account = PublicKey(escrow_mint)
     escrow_account = long_escrow.public_key()
     long_token_mint_account = long_mint.public_key()
     short_token_mint_account = short_mint.public_key()
     mint_authority_account = source_account.public_key()
     update_authority_account = source_account.public_key()
     token_account = PublicKey(TOKEN_PROGRAM_ID)
     system_account = PublicKey(SYSTEM_PROGRAM_ID)
     rent_account = PublicKey(SYSVAR_RENT_ID)
     msg += " | Gathered accounts"
     # List signers
     signers = [
         source_account, long_mint, short_mint, long_escrow, short_escrow,
         pool
     ]
     # Start transaction
     tx = Transaction()
     # Create Token Metadata
     init_binary_option_ix = initialize_binary_option_instruction(
         pool_account,
         escrow_mint_account,
         escrow_account,
         long_token_mint_account,
         short_token_mint_account,
         mint_authority_account,
         update_authority_account,
         token_account,
         system_account,
         rent_account,
         decimals,
     )
     tx = tx.add(init_binary_option_ix)
     msg += f" | Creating binary option"
     # Send request
     try:
         response = client.send_transaction(
             tx,
             *signers,
             opts=types.TxOpts(skip_confirmation=skip_confirmation))
         return json.dumps({
             'status':
             HTTPStatus.OK,
             'binary_option':
             str(pool_account),
             'msg':
             msg +
             f" | Successfully created binary option {str(pool_account)}",
             'tx':
             response.get('result') if skip_confirmation else
             response['result']['transaction']['signatures'],
         })
     except Exception as e:
         msg += f" | ERROR: Encountered exception while attempting to send transaction: {e}"
         raise (e)