Package: cardano-mass-payments
Cardano Mass PaymentsCardano Mass Payments is a Cardano python package that automates and optimizes the sending of large numbers of transactions using a single command.Table of contentsRequirementsInstallationFeaturesPackage UsageParameter DetailsFlag DetailsExample CommandCode for Transaction Plan GenerationCode for Mass Payments Script GenerationAlgorithmPossible ErrorsRequirementsThe package can only be run onpython >= 3.7.These are the minimum required versions of the required tools:pycardano >= 0.7.0Currently, all Script methods requires the following cardano tools:Cardano Node:>=1.35.5InstallationInstall the library usingpip:pip install cardano-mass-paymentsFeaturesCan be used as a Python script- Mass Payments Script can be generated just by calling thecardano-mass-payments-generatecommand.Can be used as a Python library- Mass Payments Script can be generated by incorporating thecardano-mass-paymentslibrary in your python code.Fee optimization- The library groups the payments into transaction groups, making fees significantly less than the total fees when sending these payments individually.Support for both Cardano CLI and PyCardano- Currently,cardano-mass-paymentssupports communication to Cardano viacardano-cliandpycardanoTransaction plan generation- Alongside the scripts,cardano-mass-paymentsalso includes generation of a file which contains the final and adjusted transaction plan which will be the basis of the mass payments script. The script also includes commands that update the transaction plan file.Can recover and continue in case of an error during execution- Whenever an error is encountered in the script, the library can create an updated script using the updated transaction plan file (which skips already submitted transactions) and can go straight to pending transactions.Support for custom metadata and messages to be included in the transactions- Cardano Metadata is supported and Transaction Messages will be automatically fixed by the script to satisfy Cardano's policy regarding transaction messages.Structured JSON output- With JSON Output Type, script output will be on a structured JSON format, from the final output, to the error messages as well.Dust collection- Allows for handling Input UTxOs with less than a specified amount (dust) and combining them into one Input UTxO.Immediate execution- Allows for automatically executing the newly generated script from thecardano-mass-payments-generatecommand.Package UsageParameter DetailsParameterDescription--cardano-networkDictates which Cardano network the package will connect to.Possible values:-MAINNET-TESTNET--script-methodDictates which method to use for handling the internal logic (getting protocol parameters, getting user utxos).Possible values:-HOST_CLI- connects package to the Cardano CLI installed in the machine-DOCKER_CLI- connects package to the Cardano CLI Docker Image-PYCARDANO- uses Pycardano in the package--output-typeDictates the type of the generated output.Possible values:-BASH_SCRIPT- Creates a bash file and displays the file name in the console-CONSOLE- Displays the script contents in console-JSON- Display a JSON object in console containing the script file name-TRANSACTION_PLAN- Only create the transaction plan and display the file name in the console--sources-csvCSV File containing the source address detailsFormat per line:<source_address>,<signing_key_file_of_address_1>,<signing_key_file_of_address_2>,...,<signing_key_file_of_address_n>--payments-csvCSV File containing the payment details that will be sent to Cardano.Format per line:<destination_address>,<amount_in_lovelace>--allowed-ttl-slotsNumber of slots allowed before the transaction to be deemed invalid.Default:1000--dust-collection-methodMethod used for dust collection.Possible values:-COLLECT_TO_SOURCE- dust will all be collected and sent to the primary source address-COLLECT_PER_ADDRESS- dust will be collected and sent per address--dust-collection-thresholdAllowable amount in lovelace that will be used for checking if the transaction is deemed as a dust.Default:10000000--source-addressPrimary Source Address (should be in the--sources-csvfile). If not provided, will use the first address in the--sources-csvfile.--source-signing-key-fileSigning Key File of Primary Source Address. If not provided, will use the corresponding signing key file of the primary source address in the--sources-csvfile.--metadata-json-fileJSON File containing the metadata template that will be included in the cardano transaction.--metadata-message-fileTXT File containing the message that will be added in the transaction metadata.--transaction-plan-fileTXT Transaction Plan File which can be used to generate the script.--magic-numberCardano Network Magic Number where the python script will connect to.--cardano-node-docker-imageDocker Image name of the Cardano node.--reward-withdrawal-amountAmount of lovelace that will be withdrawn from the source's rewardsFlag DetailsFlagDescription--add-commentsAdd comments in the generated bash script--use-docker-cli-for-pycardanoBy default, Pycardano connects to Cardano CLI. This flag is used if the connected cli is the host one or the docker one--enable-dust-collectionEnable Dust Collection (Additional Step of combining small utxos into 1 utxo)--execute-script-nowExecute the script right after it's generated--include-rewardsWithdraw rewards of source address and include it in the transactionExample Commandcardano-mass-payments-generate --sources-csv source.csv --payments-csv payments.csv --cardano-network TESTNET
--add-comments --output-type BASH_SCRIPT --metadata-message-file metadata.txt --metadata-json-file metadata.json
--execute-script-now --enable-dust-collection --script-method PYCARDANO --use-docker-cli-for-pycardanoCode for Transaction Plan GenerationUsing the python package, we can generate the transaction plan object and save it in as a json filefrom cardano_mass_payments.masspayments import generate_transaction_plan
from cardano_mass_payments.constants.common import (
    ScriptOutputFormats,
    CardanoNetwork,
    ScriptMethod,
    DustCollectionMethod,
)

transaction_plan = generate_transaction_plan(
    output_format=ScriptOutputFormats.BASH_SCRIPT,
    source_address="test_source_address",
    source_details={
        "test_source_address": "test_signing_key_file"
    },
    payments_csv_file="payments.csv",
    cardano_network=CardanoNetwork.TESTNET,
    script_method=ScriptMethod.METHOD_DOCKER_CLI,
    allowed_ttl_slots=1000,
    dust_collection_method=DustCollectionMethod.COLLECT_TO_SOURCE,
    dust_collection_threshold=10000000,
    enable_dust_collection=True,
)
with open("transaction_plan_filename", "w+") as transaction_plan_file:
    transaction_plan_file.write(transaction_plan.json())Code for Mass Payments Script GenerationUsing the python package, we can also generate the mass payments scriptfrom cardano_mass_payments.masspayments import generate_bash_script
from cardano_mass_payments.constants.common import (
    CardanoNetwork,
    ScriptMethod,
)

bash_script_result = generate_bash_script(
    transaction_plan=transaction_plan,  # Generated transaction plan from generate_transaction_plan
    source_details={
        "test_source_address": "test_signing_key_file"
    },
    source_address="test_source_address",
    metadata_file="metadata.json",
    allow_ttl_slots=1000,
    add_comments=True,
    store_in_file=False,
    network=CardanoNetwork.TESTNET,
    method=ScriptMethod.METHOD_DOCKER_CLI,
)AlgorithmParse the source and payment CSV files.If--transaction-plan-fileis provided, parse the transaction plan file.Else, generate a transaction plan based on the parsed source and payment details.Create the initial transaction plan setup.Check the initial transaction byte size of the possible payment group UTxO (1 input, n payments).If the transaction size is greater than the maximum, adjust the number of payments until the transaction size satisfies the size check.Divide the payments into k groups with n (obtained from step3.1.2) payments.Select Input UTxOs that can satisfy the total transaction amounts and fees.Create a mock transaction with the selected input utxos and payments based on the payment groups + 1 payment utxo for the change.Get the size of the mock transaction. This will determine if dust collection is required or not.If it's greater than the maximum, dust collection is required.Dust Collection StepWhile all selected input utxos are not yet used,Select Input UTxOs that can satisfy the maximum transaction byte sizen inputs, 1 payment for 1st groupn+1 inputs, 1 payment for the remaining groups (the additional input is the input utxo from the previous dust group)Create a Dust Group with the selected inputsAdjust UTxO StepClassify the payment groups on whether their transaction size is above/below the maximum transaction size.For those above the maximum,Remove payments until transaction satisfy the maximum size.Move the removed payments in a temporary list.For those below the maximum,Get payments from the temporary list and add them until transaction doesn't satisfy the maximum size.If there are payments in the temporary list,If the preparation transaction size is less than the maximum, add payments until transaction doesn't satisfy the maximum size.If there are remaining payments in the temporary list, treat them as a new payment group.Generate the transaction plan using the adjusted details obtained in step3.3.Create a transaction plan file from the generated transaction plan.If--output-typeisTRANSACTION_PLAN, return the transaction plan filename.Else, create a bash script from the transaction plan and print the corresponding--output-type.BASH_SCRIPT- Display the file name in the console.CONSOLE- Displays the script contents in console.JSON- Display a JSON object in console containing the script file name.If--execute-script-now,Display transaction plan details.Transaction Plan FilenameNumber of Dust Transactions to be GeneratedNumber of Payment Transaction Groups GeneratedTotal Amount RequiredExpected Maximum Change ReturnedA prompt will be displayed asking the user to review the plan and asks to continue with the execution.Repeat asking for input if the user inputs any value other than yes/no.If yes, execute the script.If no, a "Thank You" message will be displayed.Possible ErrorsErrorJSON OutputDescriptionScriptError{"code": 500001,"message": STR,"context": DICT}Unexpected Errors encountered during any part of the mass payments script generationInsufficientBalance{"code": 400001,"message": STR,"context": {"required_amount": INT,"current_amount": INT}}Current Balance doesn't satisfy the total transaction amount and fee required for submissionInvalidMethod{"code": 400002,"message": "Invalid Method","context": {"allowed_methods": STR[],"method": STR}}Method is not included in the allowed methods. This will show on invalid command argument value.InvalidNetwork{"code": 400003,"message": "Invalid Network","context": {"allowed_networks": STR[],"network": STR}}Network is not included in the allowed networks. This will show on invalid command argument value.InvalidFileError{"code": 400004,"message": STR,"context": {"file":STR}}Unexpected Errors encountered while doing file related function (Source and Payment CSV Files, Signing Key Files, Metadata Files, Transaction Plan Files)InvalidType{"code": 400005,"message": STR,"context": {"type":STR}}Value Type doesn't match with the required field type. This will show on invalid command argument values.EmptyList{"code": 400006,"message": STR}List is empty.