How to opt an application address into an asset ID

The problem is that if an application address AA is generated from application ID AID, then AA would not exist as an address on the blockchain until after the TEAL program is deployed.

This means the TEAL program must allow the developer to send a transaction to the application to allow AA to execute the optin transaction.

I have tried creating a funding transaction. This would allow the developer to call the application and then fund the escrow with 1 ALGO, which would also trigger the internal transaction.

    ############################################################
    # Optin Logic
    ############################################################
    # Detect the funding transaction (1 Algo sent to the escrow)
    ##############################
    funding_amount = Int(1000000)  
    is_funding_txn = And(
        Txn.type_enum() == TxnType.Payment,                         
        Txn.amount() >= funding_amount,                             
        Txn.receiver() == Global.current_application_address()     
    )

This would initiate the inner transaction.

    ##############################
    # Logic for opt-in to the asset_id using an inner transaction
    ##############################
    escrow_opt_in = Seq([
        InnerTxnBuilder.Begin(),
        InnerTxnBuilder.SetFields({
            TxnField.type_enum: TxnType.AssetTransfer,
            TxnField.xfer_asset: asset_id,
            TxnField.asset_receiver: Global.current_application_address(),  
            TxnField.asset_amount: Int(0),  
        }),
        InnerTxnBuilder.Submit(),
        Approve()  
    ])
    ##############################

But, this is not working. I have not been able to find any examples of this in the docs or in the developer forum. Any suggestions would be appreciated, thanks.

I launched the app with the associated app account, but my call transaction to initiate the optin:

txn_0 = ApplicationCallTxn(sender=Address, sp=params, index=app_id, on_complete=OnComplete.NoOpOC, app_args=app_args, foreign_assets=[asset_id], accounts=[App_Address, Address])

Returns a blank rejection error:

algosdk.error.AlgodHTTPError: TransactionPool.Remember: transaction GAAITCDA5CVEDTNS7NVANJPXALVWW6RST45KDKWV4LWAT22DAYHQ: transaction rejected by ApprovalProgram

I think I have to go back through another round of debugging the PyTeal and approval program. Probably the most difficult part is that I have no way to figure out if the error is coming from the PyTeal, Teal, or the user transaction. I tried to set it up where the app automatically optedin on create, but then the app address also has to be funded on creation, which creates another host of bugs to work through.

This is done in steps.

  1. create the app.
  2. run program to get app address.
  3. send algo to app address.
  4. run program to optin.
  5. send asset to address.