The TransactionFactory component of the SDK is outlined in the interface found here. This component allows the user to craft executable solana transactions.
Instantiating an TransactionFactory
Mainnet
import { clusterApiUrl, Connection } from"@solana/web3.js";import { TransactionFactoryImpl } from"@seabed-labs/pre-authorized-debit";// You can use any connection object you'd like, this is just an exampleconstconnection=newConnection(clusterApiUrl("mainnet-beta"));consttxFactory=TransactionFactoryImpl.mainnet(connection);
Devnet
import { clusterApiUrl, Connection } from"@solana/web3.js";import { TransactionFactoryImpl } from"@seabed-labs/pre-authorized-debit";// You can use any connection object you'd like, this is just an exampleconstconnection=newConnection(clusterApiUrl("devnet"));consttxFactory=TransactionFactoryImpl.devnet(connection);
Custom
Point the instruction factory to a custom deployment on any cluster:
import { clusterApiUrl, Connection } from"@solana/web3.js";import { TransactionFactoryImpl } from"@seabed-labs/pre-authorized-debit";constconnection=newConnection(/* your connection args */);constCUSTOM_PAD_PROGRAM_ID=/* your custom program ID */;consttxFactory=TransactionFactoryImpl.custom( connection,CUSTOM_PAD_PROGRAM_ID,// optionally, pass in a custom read client// (if not provided, our read client will be pointed to the custom program),// optionally, pass in a custom ix factory// (if not provided, our ix factory will be pointed to the custom program),);
Supported Methods
The transaction factory supports the following methods. These methods are 1:1 identical TX counterparts to the IX factory methods in the Instruction Factory. The main difference is that they return a different type TransactionWithMetadata which will be explored below.
Not all these transactions have instructions that map 1:1 to the instructions in the program. For example, pause and unpause are modeled as 2 methods here but utilize the same instruction with different parameters in the program.
Approve smart delegate has an instruction that is sent to the SPL token (or token 2022) program and not the pre-authorized-debit program.
These abstractions will hopefully make the SDK slightly easier to use.
All the methods listed above return the following generic type. This type will contain the instruction in the IX factory counterpart but might also contain additional setup/cleanup instructions such as SOL -> wSOL wrapping (or vice versa).
// Return TypetypeTransactionWithMetadata<T> = { setupInstructions:TransactionInstruction[]; coreInstructions:TransactionInstruction[]; cleanupInstructions:TransactionInstruction[]; expectedSigners:ExpectedSigner[]; meta:T;buildVersionedTransaction( params:BuildVersionedTransactionParams, ):Promise<VersionedTransaction>;simulate( params:SimulateParams, ):Promise<TransactionSimulationResultWithMeta<T>>;execute(params:ExecuteParams):Promise<TransactionResultWithMeta<T>>;}// Inner TypestypeExpectedSigner= { publicKey:PublicKey; // this pubkey needs to sign for IX to be successful reason:string; // human-readable reason for why this pubkey needs to sign};typeTransactionSimulationResultWithMeta<T> = { result:RpcResponseAndContext<SimulatedTransactionResponse>; meta:T;};typeTransactionResultWithMeta<T> = { signature:string; meta:T;};/** * Provide either signers[0] or txFeesPayer at minimum, else method will throw. */typeSignerAndTxFeePayerParams=| { signers:Signer[];/** * If this is undefined, signers[0] is used */ txFeesPayer?:PublicKey; }| { txFeesPayer:PublicKey };typeBuildVersionedTransactionParams=SignerAndTxFeePayerParams;typeSimulateParams=SignerAndTxFeePayerParams& { simulateConfig?:SimulateTransactionConfig;};typeExecuteParams=SignerAndTxFeePayerParams& { sendOptions?:SendOptions;};
You can simulate and/or execute the transaction by using the utility method attached to the return type.
You can also extract the TX from it and execute it yourself outside the SDK (for example, in a browser environment where you don't have the keypair directly and only the injected wallet/provider).
Both examples are shown below using buildDebitTx (this applies to all methods).
Direct execution example (same applies to simulate):
import { Connection, SendOptions,} from"@solana/web3.js";import { TransactionFactoryImpl } from"@seabed-labs/pre-authorized-debit";// You can use any connection object you'd like, this is just an exampleconstconnection=newConnection(clusterApiUrl("mainnet-beta"));consttxFactory=TransactionFactoryImpl.mainnet(connection);constdebitAuthorityKeypair=// load it however;consttxPayerKeypair=// load it however (can be same as above also);consttxSendOptions:SendOptions|undefined=// ...;consttxResult=awaittxFactory.buildDebitTx({ preAuthorization:// the pre-authorization account's pubkey, amount: // bigint, amount to debit, destinationTokenAccount: // destination token account pubkey to send "amount" to, checkSmartDelegateEnabled: // optional boolean, checks delegate is smart delegate and fails otherwise,// optional, unwrap params if mint is NATIVE_MINT unwrapNativeMintParams: { lamportsDestinationAccount:// any pubkey , },}).execute({ sendOptions: txSendOptions, signers: [txPayerKeypair, debitAuthorityKeypair], txFeesPayer:txPayerKeypair.publicKey,});const {signature,// tx signaturemeta,// undefined in this case since there's no metadata} = txResult;
Indirect execution example (same applies to simulate):
// ... (same code as example above)consttx=awaittxFactory.buildDebitTx({ preAuthorization:// the pre-authorization account's pubkey, amount: // bigint, amount to debit, destinationTokenAccount: // destination token account pubkey to send "amount" to, checkSmartDelegateEnabled: // optional boolean, checks delegate is smart delegate and fails otherwise,// optional, unwrap params if mint is NATIVE_MINT unwrapNativeMintParams: { lamportsDestinationAccount:// any pubkey , },});constversionedTx=awaittx.buildVersionedTransaction({ txFeesPayer:txPayerKeypair.publicKey // tx fees payer});// alternatively, use a provider to sign and send the TXversionedTx.sign(...);constsignature=awaitconnection.sendTransaction(versionedTx);
Build InitSmartDelegate transaction
Builds the init_smart_delegate instruction and wrap it in an executable TX. While this is available to SDK users, this instruction only needs to be run once and it will likely be run by us for any instances of the program we deploy.
The TX can also include IXs to wrap SOL into the token account if mint is SOL.
This transaction will initialize a pre_authorization account that represents a one-time pre-authorization.
consttx=awaittxFactory.buildInitOneTimePreAuthorizationTx({// pre-auth generic payer:// the pubkey paying for pre_authorization account creation, tokenAccount: // the token account pubkey, debitAuthority: // the debit authority pubkey, activation: // a Date instance representing the pre-auth's activation time// one-time specific amountAuthorized: // a bigint that represents the one-time pre-auth's amount expiry: // an optional Date instance representing the pre-auth's expiry time// optionally, wrap SOL if mint is NATIVE_MINT wrapNativeMintParams: { lamportsSourceAccount:// source of the lamports to wrap (has to sign), wrapLamportsAmount: // bigint, amount of lamports to wrap };});const {// datasetupInstructions,coreInstructions,cleanupInstructions,expectedSigners, meta: { preAuthorization: preAuthorizationPubkey },// methodsbuildVersionedTransaction,simulate,execute,} = tx;
The TX can also include IXs to wrap SOL into the token account if mint is SOL.
This transaction will initialize a pre_authorization account that represents a recurring pre-authorization.
consttx=awaittxFactory.buildInitOneTimePreAuthorizationTx({// pre-auth generic payer:// the pubkey paying for pre_authorization account creation, tokenAccount: // the token account pubkey, debitAuthority: // the debit authority pubkey, activation: // a Date instance representing the pre-auth's activation time// recurring specific repeatFrequencySeconds: // the recurring frequency in seconds (type: bigint), recurringAmountAuthorized: // amount authorized each cycle (type: bigint), numCycles: // optional, total cycles this pre-auth will be active (type: bigint), resetEveryCycle: // if false, the unused "recurringAmountAuthorized" will accrue across cycles (type: boolean)// optionally, wrap SOL if mint is NATIVE_MINT wrapNativeMintParams: { lamportsSourceAccount:// source of the lamports to wrap (has to sign), wrapLamportsAmount: // bigint, amount of lamports to wrap };});const {// datasetupInstructions,coreInstructions,cleanupInstructions,expectedSigners, meta: { preAuthorization: preAuthorizationPubkey },// methodsbuildVersionedTransaction,simulate,execute,} = tx;
consttx=awaittxFactory.buildPausePreAuthorizationTx({ preAuthorization:// the pre-authorization account's pubkey});const {// datasetupInstructions,coreInstructions,cleanupInstructions,expectedSigners,// no metadata for this// methodsbuildVersionedTransaction,simulate,execute,} = tx;
consttx=awaittxFactory.buildUnpausePreAuthorizationTx({ preAuthorization:// the pre-authorization account's pubkey});const {// datasetupInstructions,coreInstructions,cleanupInstructions,expectedSigners,// no metadata for this// methodsbuildVersionedTransaction,simulate,execute,} = tx;
consttx=awaittxFactory.buildClosePreAuthorizationAsOwnerTx({ preAuthorization:// the pre-authorization account's pubkey, rentReceiver: // optional, the account pubkey that'll receive the lamports in the pre-auth account// optional unwrap params if mint is NATIVE_MINT unwrapNativeMintParams: { lamportsDestinationAccount:// optionally, the destination for lamports };});const {// datasetupInstructions,coreInstructions,cleanupInstructions,expectedSigners,// no metadata for this// methodsbuildVersionedTransaction,simulate,execute,} = tx;
consttx=awaittxFactory.buildClosePreAuthorizationAsDebitAuthorityTx({ preAuthorization:// the pre-authorization account's pubkey,});const {// datasetupInstructions,coreInstructions,cleanupInstructions,expectedSigners,// no metadata for this// methodsbuildVersionedTransaction,simulate,execute,} = tx;
The TX can also include IXs to unwrap SOL from the destination token account if mint is SOL.
This transaction will debit the token account via the pre-authorization if it is valid.
consttx=awaittxFactory.buildDebitTx({ preAuthorization:// the pre-authorization account's pubkey, amount: // bigint, amount to debit, destinationTokenAccount: // destination token account pubkey to send "amount" to, checkSmartDelegateEnabled: // optional boolean, checks delegate is smart delegate and fails otherwise// optional unwrap params if mint is NATIVE_MINT unwrapNativeMintParams: { lamportsDestinationAccount:// optionally, the destination for lamports };});const {// datasetupInstructions,coreInstructions,cleanupInstructions,expectedSigners,// no metadata for this// methodsbuildVersionedTransaction,simulate,execute,} = tx;
When a pre-authorization account is created, the delegate of the token account is already configured as the smart_delegate and the delegated amount is set to u64::MAX. This instruction can be used to "reset" this delegation so that the token account's associated pre-authorizations are still valid if it was unset by another Dapp. Alternatively, if the delegated amount isn't sufficient anymore, this same method can be used to reset it back to u64::MAX.