pythonsolanacontract

solana-python call contract method


Currently, I trying to access the contract of solana with python based env. I want to try simple test like that.

  1. Access the contract of solana
  2. Access the function(hello) with solana-py

The solana contract info is here (devnet): https://explorer.solana.com/address/78PoQT2bBAJiQxk3qBshvxvFEiPeARDAzYE6zwqpbnUv?cluster=devnet

I searched some related information in StackOverflow are below:

How to access the contract function in solana using python? In the solidity env, I just create an instance with abi and contract address. However, I thought that solana contract is a little complex.


Solution

  • I just find a simple example for transferring tokens. I guess that is helping some who want to handle tokens in Solana.

    from solana.publickey import PublicKey
    from solana.keypair import Keypair
    from solana.system_program import TransferParams, transfer
    from solana.transaction import Transaction
    from solana.rpc.api import Client
    
    import base58
    
    http_client = Client("https://api.devnet.solana.com")
    sender_pri = ''
    receiver_pub = ''
    
    def load_wallet():
        byte_array = base58.b58decode(sender_pri)
        account = Keypair.from_secret_key(byte_array)
        return account
    
    def send_sol(receiver, amount):
        try:
            sender = load_wallet()
    
            txn = Transaction().add(transfer(TransferParams(
                from_pubkey=sender.public_key, to_pubkey=PublicKey(receiver), lamports=amount)))
            resp = http_client.send_transaction(txn, sender)
    
            transaction_id = resp['result']
            if transaction_id != None:
                return transaction_id
            else:
                return None
    
        except Exception as e:
            print('error:', e)
            return None
    
    if __name__ == '__main__':
        send_sol(receiver_pub, 1)