Create Custom SPL Tokens

Effortlessly deploy new SPL tokens with customized parameters using the TokenDeploymentManager class. This utility simplifies token creation for any project on the Solana blockchain.

Code Breakdown

1. Determine Rent Exemption

Calculate the minimum balance required for rent exemption to initialize the token account:

Copy

lamports = await connection.get_minimum_balance_for_rent_exemption(MINT_LEN)  

2. Mint Keypair Generation

A new keypair is generated to serve as the token's mint address:

Copy

mint = Keypair()  
logger.info(f"Generated mint address: {mint.pubkey()}")  

3. Create Account for Token Mint

An account is created with the calculated lamports for rent exemption and linked to the token program:

Copy

create_account_ix = create_account(  
    CreateAccountParams(  
        from_pubkey=agent.wallet_address,  
        to_pubkey=mint.pubkey(),  
        lamports=lamports,  
        space=MINT_LEN,  
        program_id=TOKEN_PROGRAM_ID,  
    )  
)  

4. Initialize the Token Mint

The mint is initialized with the specified decimals and authorities:

Copy

initialize_mint_ix = initialize_mint(  
    program_id=TOKEN_PROGRAM_ID,  
    mint=mint.pubkey(),  
    decimals=decimals,  
    mint_authority=Pubkey.from_string(agent.wallet_address),  
    freeze_authority=Pubkey.from_string(agent.wallet_address),  
)  

5. Submit and Confirm the Transaction

Both instructions are added to a transaction, signed, and submitted to the blockchain:

Copy

transaction = Transaction()  
transaction.add(create_account_ix, initialize_mint_ix)  

tx_signature = await agent.connection.send_transaction(  
    transaction, agent.wallet, mint, opts={"preflight_commitment": Confirmed}  
)  

6. Error Handling

If an error occurs during the process, it is logged and raised:

Copy

except Exception as e:  
    logger.error(f"Token deployment failed: {str(e)}")  
    raise Exception(f"Token deployment failed: {str(e)}")  

Key Features

  1. Customizable Parameters

    • Define the number of decimals to suit the token's utility (default: 9).

  2. Efficient Resource Management

    • Automatically calculates the required lamports for rent exemption.

  3. Seamless Integration

    • Combines account creation and mint initialization into a single transaction.

  4. Error Logging

    • Comprehensive logs ensure smooth debugging and transparency.

  5. Simplified Outputs

    • Returns the new token's mint address and transaction signature.

Last updated