### Install Defichain Python Package Source: https://github.com/eric-volz/defichainpython/blob/main/docs/source/main/quickstart.md Installation methods for the library using pip or cloning the repository. ```bash pip install defichain -U ``` ```bash git clone https://github.com/eric-volz/DefichainPython.git ``` -------------------------------- ### Initialize Testnet Wallet Source: https://github.com/eric-volz/defichainpython/blob/main/docs/source/guides/guides/basicUsageOfRawTransactions.md Setup a wallet instance using a mnemonic seed on the testnet. ```python from defichain.networks import DefichainTestnet from defichain import Wallet MNEMONIC = "deputy army pluck artwork gallery supply bracket dilemma increase section silent coconut chimney auction ridge gravity cloth foot secret worry brother capital spread cheap" wallet = Wallet(DefichainTestnet) # Initializing the wallet as a testnet wallet wallet.from_mnemonic(MNEMONIC) # Setting the wallet mnemonic seed ``` -------------------------------- ### Install test requirements Source: https://github.com/eric-volz/defichainpython/blob/main/tests/README.md Install the necessary dependencies for running the test suite. ```bash pip install -r requirements_tests.txt ``` -------------------------------- ### Full Poolswap Transaction Workflow Source: https://github.com/eric-volz/defichainpython/blob/main/docs/source/guides/guides/basicUsageOfRawTransactions.md Complete example demonstrating wallet initialization, transaction construction, signing, and broadcasting to the testnet. ```python # Imports from defichain.networks import DefichainTestnet from defichain import Wallet from defichain import Ocean from defichain import TxBuilder MNEMONIC = "deputy army pluck artwork gallery supply bracket dilemma increase section silent coconut chimney auction ridge gravity cloth foot secret worry brother capital spread cheap" wallet = Wallet(DefichainTestnet) # Initializing the wallet as a testnet wallet wallet.from_mnemonic(MNEMONIC) # Setting the wallet mnemonic seed account = wallet.get_account(0) # Extracting the first account of the wallet dataSource = Ocean(network="testnet") # Initializing the remote data source -> testnet ocean address = account.get_p2wpkh() # Extracting the P2WPKH address from the account builder = TxBuilder(address, account, dataSource, 1.0) # Creating the transaction builder object tx_poolswap = builder.pool.poolswap(address, "DFI", 0.001, address, "BTC", 99.99999999) # Create a poolswap transaction with the specified parameters print(tx_poolswap) # Prints the raw transaction in a deserialized format to the console txid = builder.send_tx(tx_poolswap) # Broadcasts the created transaction to the blockchain print(txid) # prints the txid ``` -------------------------------- ### Build Documentation Commands Source: https://github.com/eric-volz/defichainpython/blob/main/docs/README.md Commands to install documentation dependencies and compile the source files into HTML format. ```bash cd docs # change directory to docs pip install -r requirements_docs.txt # install dependencies make clean html # builds the documentation as html ``` -------------------------------- ### Example Address Amount Source: https://github.com/eric-volz/defichainpython/blob/main/docs/source/api/node/index.md An example of the address amount format, showing a single token amount for one address and multiple token amounts for another. ```text { "dcTKz5SQrqf4vGVsgra76ptXeNBcxPrenP": "1@DFI", "df1qzkf582h0sgfksj0yn0wxz0r9amyqfferm5wycs": ["2.0@BTC", "3.0@ETH"] } ``` -------------------------------- ### Setup Wallet and Retrieve Address Source: https://github.com/eric-volz/defichainpython/blob/main/docs/source/main/quickstart.md Generates a mnemonic seed to create a new wallet and derive a bech32 address. ```pycon >>> from defichain import Wallet >>> from defichain.networks import DefichainMainnet >>> from defichain.hdwallet.utils import generate_mnemonic >>> wallet = Wallet(DefichainMainnet) >>> mnemonic = generate_mnemonic() wisdom path obscure scrub travel vessel boring solar truth original quiz letter exhibit spy point mail else entire involve announce vault outer mirror rug >>> wallet.from_mnemonic(mnemonic) >>> wallet.bech32_address() df1q95vyvvu05sgpaem7w8lwufxwnzdchwk9xr7j0y ``` -------------------------------- ### Setup Transaction Builder Source: https://context7.com/eric-volz/defichainpython/llms.txt Initializes the Ocean connection, wallet from mnemonic, and TxBuilder for creating custom transactions. Sets fee per byte and RBF flag. ```python from defichain import Ocean, Wallet, TxBuilder from defichain.networks import DefichainMainnet # Setup Ocean connection ocean = Ocean(network="mainnet") # Create wallet and get account mnemonic = "avocado key fan step egg engage winter upper attitude carry regret mixed utility body party trip valid oppose gas ensure deputy suspect blur trade" wallet = Wallet(DefichainMainnet) wallet.from_mnemonic(mnemonic) account = wallet.get_account(0) # Create transaction builder builder = TxBuilder( address=account.get_p2wpkh(), account=account, dataSource=ocean, feePerByte=1.0, # Fee in satoshis per byte replaceable=False # RBF flag ) print(f"Builder address: {builder.get_address()}") print(f"Fee per byte: {builder.get_feePerByte()}") ``` -------------------------------- ### Install Defichain Python Package Source: https://github.com/eric-volz/defichainpython/blob/main/README.rst Install the Defichain Python package using pip. This command ensures you have the latest version. ```bash pip install defichain -U ``` -------------------------------- ### Chain Transactions Example Source: https://github.com/eric-volz/defichainpython/blob/main/docs/source/guides/example/chainedTransactions.md Demonstrates how to take a loan and immediately use the resulting unspent outputs to perform a poolswap. Requires a configured wallet and connection to the Ocean API. ```python import time from defichain import TxBuilder, Ocean, Wallet from defichain.networks import DefichainTestnet """ Example to show how you can chain transactions with the DefichainPython Library! -------------------------------------------------------------------------------- Chaining transactions, in this case, means that they depend on each other. The second chained transaction uses the unspent inputs of the first transaction, the third transaction uses the unspent inputs of the second transaction ... It's mostly used to include multiple transactions in the same block. It's important to point out that there are two layers of coins. There are UTXO DFI and Token. The UTXO can always be spent in the next transaction. The Token on the other hand, can only be spent in a following transaction inside the same block ifthe outcome of the used DefiTx is pre determined. Example: When executing a takeloan, you want to have exactly 5 DUSD. The system knows that you will get exactly 5 DUSD and you can use them in the next tx. When executing a poolswap you want to exchange 1 DFI into BTC. But the system only knows how much BTC you will get when the next block has been minted. So the transactions that should be executed after the poolswap cannot continue with the BTC output of the poolswap. Installation: pip install defichain -U """ """Script Setup""" PRIVATE_KEY = "cTBazS4LCqitNniS3zW34UmhtQgBWSiuUeTCKFHfPkXyaLGPoy6b" # wif private key wallet = Wallet(DefichainTestnet).from_wif(PRIVATE_KEY) # create testnet wallet account = wallet.get_account() # get account ADDRESS = account.get_p2wpkh() # address to use VAULT_ID = "9429280b52dff4784465b3b00174fc12722907d6459bb7c50f2fad0dc5c20083" # vault to use ocean = Ocean(network="testnet") # testnet ocean connection builder = TxBuilder(ADDRESS, account, ocean, 1.0) # transaction builder """Account Setup""" # tx_utxos_to_account = builder.accounts.utxostoaccount(ADDRESS, 700) # Convert UTXOS to Token # tx_create_vault = builder.vault.createvault(ADDRESS, "C150") # Create Vault with 150% Loan Scheme (Mainnet: MIN150) # tx_deposit_to_vault = builder.vault.deposittovault(VAULT_ID, ADDRESS, "500@DFI") # Deposit to vault """Create multiple transactions for one block""" tx_take_loan = builder.loans.takeloan(VAULT_ID, ADDRESS, "5@DUSD") # Take Loan tx_take_loan_unspent = tx_take_loan.get_unspent() # Takes the unspent inputs from the created transaction # poolswapt with the inputs of the previously created transaction tx_poolswap = builder.pool.poolswap(ADDRESS, "DUSD", 5, ADDRESS, "GOOGL", 99999999, tx_take_loan_unspent) """Submit multiple transactions in one block""" txid_take_loan = builder.send_tx(tx_take_loan) # Submit first tx to the network while True: # Ocean needs a few seconds to index the first transaction. After the second transaction can be submitted. try: txid_poolswap = builder.send_tx(tx_poolswap) # Submit second tx to the network break except Exception as e: print(e) # print exception time.sleep(0.5) # wait 0.5 seconds for next try """Print TXID's""" print(f"Take Loan: {txid_take_loan}") print(f"PoolSwap: {txid_poolswap}") ``` -------------------------------- ### Get Network Configurations Source: https://github.com/eric-volz/defichainpython/blob/main/docs/source/sdk/hdwallet/index.md Access the network constants for Mainnet, Testnet, and Regtest. ```pycon >>> from defichain.networks import DefichainMainnet >>> DefichainMainnet.NETWORK mainnet >>> from defichain.networks import DefichainTestnet >>> DefichainTestnet.NETWORK testnet >>> from defichain.networks import DefichainRegtest >>> DefichainRegtest.NETWORK regtest ``` -------------------------------- ### Add Liquidity to Pool Source: https://context7.com/eric-volz/defichainpython/llms.txt Adds liquidity to a specified pool by providing amounts of two tokens. Requires Ocean, Wallet, and TxBuilder setup. The transaction is then broadcast. ```python from defichain import Ocean, Wallet, TxBuilder from defichain.networks import DefichainMainnet ocean = Ocean(network="mainnet") wallet = Wallet(DefichainMainnet) wallet.from_mnemonic("your mnemonic words here") account = wallet.get_account(0) builder = TxBuilder(account.get_p2wpkh(), account, ocean) address = account.get_p2wpkh() # Add liquidity to BTC-DFI pool tx = builder.pool.addpoolliquidity( addressAmountFrom={address: ["1@DFI", "0.0001@BTC"]}, shareAddress=address ) txid = builder.send_tx(tx) print(f"Add liquidity TX: {txid}") ``` -------------------------------- ### Create and Broadcast Pool Swap Transaction Source: https://context7.com/eric-volz/defichainpython/llms.txt Creates a pool swap transaction for specified tokens and amounts, tests its validity, and then broadcasts it to the blockchain. Requires Ocean, Wallet, and TxBuilder setup. ```python from defichain import Ocean, Wallet, TxBuilder from defichain.networks import DefichainMainnet ocean = Ocean(network="mainnet") wallet = Wallet(DefichainMainnet) wallet.from_mnemonic("your mnemonic words here") account = wallet.get_account(0) builder = TxBuilder(account.get_p2wpkh(), account, ocean) # Create a pool swap transaction address = account.get_p2wpkh() tx = builder.pool.poolswap( addressFrom=address, tokenFrom="BTC", amountFrom=0.00001, addressTo=address, tokenTo="DFI", maxPrice=9999999999 ) # Test if transaction would be accepted is_valid = builder.test_tx(tx) print(f"Transaction valid: {is_valid}") # Broadcast transaction to blockchain txid = builder.send_tx(tx) print(f"Transaction ID: {txid}") ``` -------------------------------- ### Initialize Defichain Automation Script Source: https://github.com/eric-volz/defichainpython/blob/main/docs/source/guides/guides/automateAddress.md Sets up the Ocean connection, Account object with a WIF key, and the TxBuilder for transaction management. ```python # Import ocean, wallet, network and txbuilder from defichain import Ocean from defichain import Account from defichain.networks import DefichainMainnet from defichain import TxBuilder # Specify ocean connection ocean = Ocean(network="mainnet") # Create account wif = "Kya4bk1kVzWrbwPy1hanNGxa1maMQH9pgmWKwhHms23cRHi6XBnu" account = Account(network=DefichainMainnet, key=wif) # Derive correct address address = account.get_p2wpkh() # Create TxBuilder builder = TxBuilder(address, account, ocean) ``` -------------------------------- ### Mnemonic Seed Example Source: https://github.com/eric-volz/defichainpython/blob/main/docs/source/guides/guides/basicUsageOfRawTransactions.md Example mnemonic seed used for testnet development. ```text deputy army pluck artwork gallery supply bracket dilemma increase section silent coconut chimney auction ridge gravity cloth foot secret worry brother capital spread cheap ``` -------------------------------- ### Prepare Swap Inputs and Query Best Path Source: https://github.com/eric-volz/defichainpython/blob/main/docs/source/guides/guides/automateAddress.md Iterates through tokens to be converted, setting up swap variables and querying the best available swap path from Ocean for each token to DFI. ```python for convert_token in convert_tokens: # Variables for composite swap address_from = address token_from = convert_token.get("symbol") amount = float(convert_token.get("amount")) address_to = address token_to = "DFI" max_price = 999999999 # Get best swap path for different tokens from ocean token_from_id = Token.get_id_from_symbol(DefichainMainnet, token_from) token_to_id = Token.get_id_from_symbol(DefichainMainnet, token_to) pools = ocean.poolpairs.getBestPath(token_from_id, token_to_id) paths = pools.get("data").get("bestPath") bestPath = [] for path in paths: bestPath.append(path.get("symbol")) ``` -------------------------------- ### GET /getzmqnotifications Source: https://github.com/eric-volz/defichainpython/blob/main/docs/additionalInfos/rawMethodsOverview.txt Returns information about the active ZMQ notifications. ```APIDOC ## GET /getzmqnotifications ### Description Returns information about the active ZMQ notifications. ### Method GET ### Endpoint /getzmqnotifications ``` -------------------------------- ### Initialize Transaction Builder Source: https://github.com/eric-volz/defichainpython/blob/main/README.rst Prepare to build, sign, and broadcast DeFichain transactions by initializing the TxBuilder with Ocean, Wallet, and Network configurations. ```python # Import ocean, wallet, network and txbuilder from defichain import Ocean from defichain import Wallet from defichain.networks import DefichainMainnet from defichain import TxBuilder # Specify ocean connection ocean = Ocean(network="mainnet") # Create wallet and account mnemonic = "avocado key fan step egg engage winter upper attitude carry regret mixed utility body party trip valid oppose gas ensure deputy suspect blur trade" wallet = Wallet(DefichainMainnet) wallet.from_mnemonic(mnemonic) account = wallet.get_account(0) # Create TxBuilder ``` -------------------------------- ### Configure Network Environments Source: https://context7.com/eric-volz/defichainpython/llms.txt Initialize wallets for specific network environments like mainnet or testnet to derive correct addresses. ```python from defichain import Wallet from defichain.networks import DefichainMainnet, DefichainTestnet # Mainnet wallet mainnet_wallet = Wallet(DefichainMainnet) mainnet_wallet.from_mnemonic("your mnemonic here") print(f"Mainnet address: {mainnet_wallet.get_account(0).get_p2wpkh()}") # Output: df1q... # Testnet wallet (same mnemonic, different addresses) testnet_wallet = Wallet(DefichainTestnet) testnet_wallet.from_mnemonic("your mnemonic here") print(f"Testnet address: {testnet_wallet.get_account(0).get_p2wpkh()}") # Output: tf1q... # Network information print(f"Symbol: {mainnet_wallet.symbol()}") # DFI print(f"Network: {mainnet_wallet.network()}") # mainnet print(f"Name: {mainnet_wallet.cryptocurrency()}") # Defichain ``` -------------------------------- ### Raw Transaction Hexadecimal Representation Source: https://github.com/eric-volz/defichainpython/blob/main/docs/additionalInfos/reddit/announcement03.md Example of a hexadecimal data string representing a poolswap transaction on the blockchain. ```text 040000000001018605b44cda16f8828a406f4e4377c75b9508930b7cd343729dab1f56fbe19d1d0100000000ffffffff020000000000000000506a 4c4d446654787316001404c7767d2009c6dabe47d27a77406141c289376a0000e1f5050000000016001404c7767d2009c6dabe47d27a77406141c2 89376a016300000000000000ffe0f5050000000000fced052a0100000016001404c7767d2009c6dabe47d27a77406141c289376a00024830450221 00b11e61ff38835e09e5f4b4e5417808b99e1ddd3ccf792a60f929db22d3a93a2802203a3a69be756a4451e9461b1d795a13f0c837e104cc708101 7c3dfd844529c21c012103a5c791ba2a9c2668fc10b095e742b971d7acd50ffa77d6b40b9974937cb6064e00000000 ``` -------------------------------- ### Initialize Ocean Data Source Source: https://github.com/eric-volz/defichainpython/blob/main/docs/source/guides/guides/basicUsageOfRawTransactions.md Configure the remote data source using Ocean for testnet. ```python from defichain import Ocean dataSource = Ocean(network="testnet") # Initializing the remote data source -> testnet ocean ``` -------------------------------- ### Initialize Wallet from Private Key Source: https://github.com/eric-volz/defichainpython/blob/main/docs/source/sdk/hdwallet/index.md Create a wallet from a single private key. Note that this method does not support path iteration. ```pycon >>> from defichain import Wallet >>> from defichain.networks import DefichainMainnet >>> wallet = Wallet(DefichainMainnet) >>> wallet.wif("Kzn333NbqsAASpycmNTB8ssuZQJjiaj8wDrBzAaGPNoJCDTNJqfQ") >>> wallet.bech32_address() df1qwhruysa0t04vtcmyezrc6feddwg0f8fdc5dwy7 ``` -------------------------------- ### Get UTXO Balance using Ocean API Source: https://github.com/eric-volz/defichainpython/blob/main/README.rst Retrieve the UTXO balance for a given DeFichain address using the Ocean API. Specify 'mainnet' or 'testnet'. ```python # Import ocean object from defichain import Ocean # Specify connection ocean = Ocean(network="mainnet") # Execute getBalace method utxo_balance = ocean.address.getBalance("df1qn6utdvuaq0yshc4sah6puzf0dnlfkc2c8ryme8") # Print the utxo balance of the requested address print(utxo_balance) ``` -------------------------------- ### Initialize Wallet from Mnemonic Seed Source: https://github.com/eric-volz/defichainpython/blob/main/docs/source/sdk/hdwallet/index.md Create a wallet instance using a provided mnemonic seed string. ```pycon >>> from defichain import Wallet >>> from defichain.networks import DefichainMainnet >>> wallet = Wallet(DefichainMainnet) >>> wallet.from_mnemonic("sceptre capter séquence girafe absolu relatif fleur zoologie muscle sirop saboter parure") ``` -------------------------------- ### Connect to Node and Execute RPC Source: https://github.com/eric-volz/defichainpython/blob/main/docs/source/main/quickstart.md Establishes a connection to a local node and demonstrates blockchain and poolpair requests. ```pycon >>> from defichain import Node >>> node = Node("user", "password", "127.0.0.1", 8554) >>> node.blockchain.getblockcount() # returns block height of the latest block >>> node.poolpair.compositeswap("fromAddress", "BTC", 0.01, "toAddress", "DFI") # swaps 0.01 BTC to DFI ``` -------------------------------- ### Send All DFI UTXO Balance Source: https://context7.com/eric-volz/defichainpython/llms.txt Sends the entire available UTXO balance of DFI to a recipient address. Requires Ocean, Wallet, and TxBuilder setup. The transaction is then broadcast. ```python from defichain import Ocean, Wallet, TxBuilder from defichain.networks import DefichainMainnet ocean = Ocean(network="mainnet") wallet = Wallet(DefichainMainnet) wallet.from_mnemonic("your mnemonic words here") account = wallet.get_account(0) builder = TxBuilder(account.get_p2wpkh(), account, ocean) # Send all available UTXO balance tx = builder.utxo.sendall( address="df1qrecipientaddresshere" ) txid = builder.send_tx(tx) print(f"Send all TX: {txid}") ``` -------------------------------- ### Run all tests Source: https://github.com/eric-volz/defichainpython/blob/main/tests/README.md Execute the entire test suite from the tests directory. ```bash cd tests pytest ``` -------------------------------- ### Send DFI UTXO Transaction Source: https://context7.com/eric-volz/defichainpython/llms.txt Sends a specified amount of DFI as a UTXO transaction to a recipient address. Requires Ocean, Wallet, and TxBuilder setup. The transaction is then broadcast. ```python from defichain import Ocean, Wallet, TxBuilder from defichain.networks import DefichainMainnet ocean = Ocean(network="mainnet") wallet = Wallet(DefichainMainnet) wallet.from_mnemonic("your mnemonic words here") account = wallet.get_account(0) builder = TxBuilder(account.get_p2wpkh(), account, ocean) # Send DFI to another address tx = builder.utxo.send( amount=1.0, address="df1qrecipientaddresshere" ) txid = builder.send_tx(tx) print(f"Send TX: {txid}") ``` -------------------------------- ### Execute a Poolswap Transaction with DefichainPython Source: https://github.com/eric-volz/defichainpython/blob/main/docs/source/index.md Initializes the Ocean connection, configures a wallet from a mnemonic, and builds/sends a poolswap transaction. ```python # Import ocean, wallet, network and txbuilder from defichain import Ocean from defichain import Wallet from defichain.networks import DefichainMainnet from defichain import TxBuilder # Specify ocean connection ocean = Ocean(network="mainnet") # Create wallet and account mnemonic = "avocado key fan step egg engage winter upper attitude carry regret mixed utility body party trip valid oppose gas ensure deputy suspect blur trade" wallet = Wallet(DefichainMainnet) wallet.from_mnemonic(mnemonic) account = wallet.get_account(0) # Create TxBuilder builder = TxBuilder(account.get_p2wpkh(), account, ocean) addressFrom = account.get_p2wpkh() tokenFrom = "BTC" amount = 0.1 addressTo = account.get_p2wpkh() tokenTo = "DFI" maxprice = 3000 # Build poolswap transaction tx = builder.pool.poolswap(addressFrom, tokenFrom, amount, addressTo, tokenTo, maxprice) # Send transaction into the blockchain txid = builder.send_tx(tx) # Print txid print(txid) ``` -------------------------------- ### Remove Liquidity from Pool Source: https://context7.com/eric-volz/defichainpython/llms.txt Removes liquidity from a specified pool by providing the amount of LP tokens to withdraw. Requires Ocean, Wallet, and TxBuilder setup. The transaction is then broadcast. ```python from defichain import Ocean, Wallet, TxBuilder from defichain.networks import DefichainMainnet ocean = Ocean(network="mainnet") wallet = Wallet(DefichainMainnet) wallet.from_mnemonic("your mnemonic words here") account = wallet.get_account(0) builder = TxBuilder(account.get_p2wpkh(), account, ocean) address = account.get_p2wpkh() # Remove liquidity from pool tx = builder.pool.removepoolliquidity( addressFrom=address, amount="0.0001@BTC-DFI" ) txid = builder.send_tx(tx) print(f"Remove liquidity TX: {txid}") ``` -------------------------------- ### Fetch Blocks from Next Pointer Source: https://github.com/eric-volz/defichainpython/blob/main/docs/source/api/ocean/index.md Retrieves 30 blocks starting from a specific 'next' pointer. The 'next' pointer is obtained from the 'page.next' field of a previous API response. ```python ocean = Ocean() # creates the connection to Ocean ocean.blocks.list(next="2269079") # returns 30 blocks from next pointer 2269079 ``` -------------------------------- ### Create Node Object and Call Blockchain Method Source: https://github.com/eric-volz/defichainpython/blob/main/docs/source/api/node/index.md Demonstrates how to instantiate the Node class and call a method within the blockchain module. Ensure you have the correct connection details. ```python from defichain import Node # Import node = Node("user", "password", "127.0.0.1", 8554) # creating the node object # 1 2 3 node.blockchain.getblockcount() ``` -------------------------------- ### Initialize Ocean Object and Call Method Source: https://github.com/eric-volz/defichainpython/blob/main/docs/source/api/ocean/index.md Demonstrates the basic structure for creating an Ocean object and calling a method within a specific module. Ensure the Ocean class is imported. ```python from defichain import Ocean # Import ocean = Ocean() # creating the ocean object # 1 2 3 ocean.blocks.list() ``` -------------------------------- ### Create Transaction Builder Source: https://github.com/eric-volz/defichainpython/blob/main/docs/source/guides/guides/basicUsageOfRawTransactions.md Initialize the TxBuilder object with address, account, and data source. ```python from defichain import TxBuilder builder = TxBuilder(address, account, dataSource, 1.0) # Creating the transaction builder object ``` -------------------------------- ### Create Composite Swap Transaction Source: https://context7.com/eric-volz/defichainpython/llms.txt Executes a composite swap through multiple pools for tokens that do not have a direct pool pair. The swap path is defined by the 'pools' argument. Requires Ocean, Wallet, and TxBuilder setup. ```python from defichain import Ocean, Wallet, TxBuilder from defichain.networks import DefichainMainnet ocean = Ocean(network="mainnet") wallet = Wallet(DefichainMainnet) wallet.from_mnemonic("your mnemonic words here") account = wallet.get_account(0) builder = TxBuilder(account.get_p2wpkh(), account, ocean) # Create composite swap (e.g., BTC -> TSLA via DFI and DUSD) address = account.get_p2wpkh() tx = builder.pool.compositeswap( addressFrom=address, tokenFrom="BTC", amountFrom=0.00001, addressTo=address, tokenTo="TSLA", maxPrice=9999999999, pools=["BTC-DFI", "DUSD-DFI", "TSLA-DUSD"] # Swap path ) txid = builder.send_tx(tx) print(f"Composite swap TX: {txid}") ``` -------------------------------- ### Iterate Addresses and Private Keys Source: https://github.com/eric-volz/defichainpython/blob/main/docs/source/sdk/hdwallet/index.md Derive and print the first ten bech32 addresses and private keys from a mnemonic seed using path iteration. ```pycon >>> from defichain import Wallet >>> from defichain.networks import DefichainMainnet >>> wallet = Wallet(DefichainMainnet) >>> wallet.from_mnemonic("sceptre capter séquence girafe absolu relatif fleur zoologie muscle sirop saboter parure") >>> for i in range(10): >>> wallet.from_path(f"m/1129/0/0/{i}") >>> print(f"{i+1}. Bech32 Address: {wallet.bech32_address()}") >>> print(f"{i+1}. Private Key {wallet.wif()}") 1. Bech32 Address: df1qwhruysa0t04vtcmyezrc6feddwg0f8fdc5dwy7 1. Private Key Kzn333NbqsAASpycmNTB8ssuZQJjiaj8wDrBzAaGPNoJCDTNJqfQ 2. Bech32 Address: df1q8ysut4vvchwzfz852w2tw8mc0ev6az5twhv7fh 2. Private Key L4CSqWy2iaeWQqz5mDSU8pyLS3PPp756aQdLrKmsfmg8h3GDkkWD 3. Bech32 Address: df1q93qkyxapl3crdgyum2xw8yc6w7fzyf7k8qx7rh 3. Private Key KxBPXweWK2M1W1NBjBpdhpR2NHGqNAdWQ4Fb2G7LUdW46xSA9653 4. Bech32 Address: df1q8tyn7e05hnzqzhg2rm2xntu8t74y79lqrk0vm6 4. Private Key L4Q5ThuGq6zL5hREqUaW8wbSnmUEc6yLApkWYm4PgocSkQ7NuM5W 5. Bech32 Address: df1q8h3geevwhqmk7njsrq80dqf7uzsshgrdr583zj 5. Private Key L5X97wjMsQdFJwbJwdTeZbU1pF7wosHhFh5ijBBx5PjfGgidwpYD 6. Bech32 Address: df1qmnqh6j9p55y56cws5vnuu3lrr9k8dwhvrwzqmj 6. Private Key Kza8sb5exVwu5FT5JBdjAJgky7iivVCt2t3h2MwBD8oqjKeUHBzL 7. Bech32 Address: df1qmzusk8ns4evrduu5phmr0vc2exectum38qc27h 7. Private Key L2hrsrMeMufMnYgHCvBofkc4Tcm8jS8Td4xtW1qg6hWmHyXRBeaK 8. Bech32 Address: df1qy4pq4m6aq8rcdr7mhd34urzrarpnulsd5udd0c 8. Private Key Kww1ciPxUkDFBhY5mcXTcUzkXZEYHafFi1eSJUfMveiCZ2b2a8NM 9. Bech32 Address: df1quk3sjkw7sy3jyu7j74uugxt3fcg9juh7myhzga 9. Private Key L4hfAjm13EjCik8krttsGAFzsZ7f4h65E2ch2Q36ZVSW1T9Sf9KR 10. Bech32 Address: df1qhzd5vka5lyvwvaqntpn8yzpr7af6nddr7m5llx 10. Private Key L23iH2udEUpaUZnJzNpsRHJAtsEhQf6T4x9EWEond72s5Z5bzbLq ``` -------------------------------- ### POST /createvault Source: https://github.com/eric-volz/defichainpython/blob/main/docs/additionalInfos/rawMethodsOverview.txt Creates a new vault for loan management. ```APIDOC ## POST /createvault ### Description Creates a new vault owned by the specified address. ### Method POST ### Endpoint createvault "ownerAddress" ( "loanSchemeId" [{"txid":"hex","vout":n},...] ) ### Parameters #### Path Parameters - **ownerAddress** (string) - Required - The address that owns the vault. - **loanSchemeId** (string) - Optional - The ID of the loan scheme. ``` -------------------------------- ### Swap all tokens to DFI Source: https://github.com/eric-volz/defichainpython/blob/main/docs/source/guides/guides/automateAddress.md Iterates through a list of tokens to perform composite swaps. Requires pre-configured ocean and builder instances. ```python for convert_token in convert_tokens: # Variables for composite swap address_from = address token_from = convert_token.get("symbol") amount = float(convert_token.get("amount")) address_to = address token_to = "DFI" max_price = 999999999 # Get best swap path for different tokens from ocean token_from_id = Token.get_id_from_symbol(DefichainMainnet, token_from) token_to_id = Token.get_id_from_symbol(DefichainMainnet, token_to) pools = ocean.poolpairs.getBestPath(token_from_id, token_to_id) paths = pools.get("data").get("bestPath") bestPath = [] for path in paths: bestPath.append(path.get("symbol")) if not unspent: # First transaction uses the inputs from ocean (automatic) tx = builder.pool.compositeswap( addressFrom=address_from, tokenFrom=token_from, amountFrom=amount, addressTo=address_to, tokenTo=token_to, maxPrice=max_price, pools=bestPath ) else: # Following transactions are using the unspent inputs from the transaction before them tx = builder.pool.compositeswap( addressFrom=address_from, tokenFrom=token_from, amountFrom=amount, addressTo=address_to, tokenTo=token_to, maxPrice=max_price, pools=bestPath, inputs=unspent ) unspent = tx.get_unspent() # set unspent inputs from the last transaction time.sleep(10) # wait 10 seconds for the transaction to be inserted txid = builder.send_tx(tx) # insert transaction print(txid) ``` -------------------------------- ### Create and send a poolswap transaction Source: https://github.com/eric-volz/defichainpython/blob/main/docs/source/sdk/transactions/builder/index.md Demonstrates the full lifecycle of a transaction, including initialization, building a poolswap, and broadcasting to the network. ```python # 1. Import ocean, wallet, txbuilder and the network from defichain import Ocean, Wallet, TxBuilder from defichain.networks import DefichainMainnet # 2. Specify ocean connection ocean = Ocean(network="mainnet") # 3. Create wallet and account mnemonic = "avocado key fan step egg engage winter upper attitude carry regret mixed utility body party trip valid oppose gas ensure deputy suspect blur trade" wallet = Wallet(DefichainMainnet) wallet.from_mnemonic(mnemonic) account = wallet.get_account(0) # 4. Create TxBuilder builder = TxBuilder(account.get_p2wpkh(), account, ocean) addressFrom = account.get_p2wpkh() tokenFrom = "BTC" amount = 0.1 addressTo = account.get_p2wpkh() tokenTo = "DFI" maxprice = 3000 # 5. Build poolswap transaction tx = builder.pool.poolswap(addressFrom, tokenFrom, amount, addressTo, tokenTo, maxprice) # 6. Send transaction into the blockchain txid = builder.send_tx(tx) # 7. Print txid print(txid) ``` -------------------------------- ### Build DefiTx Poolswap Source: https://github.com/eric-volz/defichainpython/blob/main/docs/source/guides/guides/basicUsageOfRawTransactions.md Create a poolswap transaction using the builder. ```python tx_poolswap = builder.pool.poolswap(address, "DFI", 1, address, "BTC", 99.99999999) # Create a poolswap transaction with the specified parameters ``` -------------------------------- ### Connect to Defichain Node Source: https://context7.com/eric-volz/defichainpython/llms.txt Initialize a Node object with RPC credentials to perform blockchain operations. ```python from defichain import Node # Connect to your Defichain node node = Node( user="your_rpc_user", password="your_rpc_password", url="127.0.0.1", port=8554, wallet_name="myWallet", wallet_password="walletPassword", wallet_timeout=60 ) # Get current block height block_count = node.blockchain.getblockcount() print(f"Current block height: {block_count}") # Get blockchain info blockchain_info = node.blockchain.getblockchaininfo() print(f"Chain: {blockchain_info['chain']}") ``` -------------------------------- ### Run specific tests Source: https://github.com/eric-volz/defichainpython/blob/main/tests/README.md Execute tests for individual components by specifying the directory. ```bash cd tests pytest node pytest ocean pytest hdwallet ```