예제 #1
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)
예제 #2
0
async def create_associated_token_account(client: AsyncClient, payer: Keypair,
                                          owner: PublicKey,
                                          mint: PublicKey) -> PublicKey:
    txn = Transaction()
    create_txn = spl_token.create_associated_token_account(
        payer=payer.public_key, owner=owner, mint=mint)
    txn.add(create_txn)
    await client.send_transaction(txn,
                                  payer,
                                  opts=TxOpts(skip_confirmation=False,
                                              preflight_commitment=Confirmed))
    return create_txn.keys[1].pubkey
예제 #3
0
    def _create_associated_token_account_args(
        self,
        owner: PublicKey,
        skip_confirmation: bool,
    ) -> Tuple[PublicKey, Transaction, Keypair, TxOpts]:

        # Construct transaction
        txn = Transaction()
        create_txn = spl_token.create_associated_token_account(
            payer=self.payer.public_key, owner=owner, mint=self.pubkey
        )
        txn.add(create_txn)
        return create_txn.keys[1].pubkey, txn, self.payer, TxOpts(skip_confirmation=skip_confirmation)
예제 #4
0
 def create_associated_token_account(self, owner: PublicKey,
                                     payer: SolanaAccount):
     # Construct transaction
     # This part of code is based on original implementation of Token.create_associated_token_account
     # except that skip_preflight is set to True
     txn = Transaction()
     create_txn = spl_token.create_associated_token_account(
         payer=payer.public_key(), owner=owner, mint=self.token.pubkey)
     txn.add(create_txn)
     self.token._conn.send_transaction(txn,
                                       payer,
                                       opts=TxOpts(skip_preflight=True,
                                                   skip_confirmation=False))
     return create_txn.keys[1].pubkey
예제 #5
0
    def create_account_if_needed(self, ether_addr: Union[str,
                                                         EthereumAddress]):
        token_account = self.get_token_account_address(ether_addr)
        info = self.solana.get_account_info(token_account)
        if info is not None:
            return token_account

        txn = Transaction()
        create_txn = spl_token.create_associated_token_account(
            payer=self.signer.public_key(),
            owner=PublicKey(ether2program(ether_addr)[0]),
            mint=self.token_mint)
        txn.add(create_txn)
        SolTxListSender(self, [txn],
                        'CreateAssociatedTokenAccount(1)',
                        skip_preflight=True).send()
        return token_account
예제 #6
0
    def create_associated_token_account(
        self,
        owner: PublicKey,
        skip_confirmation: bool = False,
    ) -> PublicKey:
        """Create an associated token account.

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

        If skip confirmation is set to `False`, this method will block for at most 30 seconds
        or until the transaction is confirmed.
        """
        # Construct transaction
        txn = Transaction()
        create_txn = spl_token.create_associated_token_account(
            payer=self.payer.public_key(), owner=owner, mint=self.pubkey)
        txn.add(create_txn)
        self._conn.send_transaction(
            txn, self.payer, opts=TxOpts(skip_confirmation=skip_confirmation))
        return create_txn.keys[1].pubkey
예제 #7
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)