### Install Ethers v5 Dependency for tBTC SDK Source: https://docs.threshold.network/app-development/tbtc-v2/tbtc-sdk/quickstart Commands to install the required ethers v5 library, which is a peer dependency for the tBTC SDK, using Yarn or npm. Proper support for newer ethers versions is not guaranteed. ```JavaScript yarn add ethers@legacy-v5 ``` ```JavaScript npm i ethers@legacy-v5 ``` -------------------------------- ### Initialize and Use tBTC SDK on Ethereum Mainnet Source: https://docs.threshold.network/app-development/tbtc-v2/tbtc-sdk/quickstart This example demonstrates how to import the tBTC SDK, initialize it for Ethereum mainnet using an ethers signer, and then access its various features for deposits, redemptions, smart contracts, and the Bitcoin client. ```TypeScript // Import SDK entrypoint component. import { TBTC } from "@keep-network/tbtc-v2.ts" // Create an instance of ethers signer. const signer = (...) // Initialize the SDK for Ethereum only. const sdk = await TBTC.initializeMainnet(signer) // Access SDK features. sdk.deposits.(...) sdk.redemptions.(...) // Access tBTC smart contracts directly. sdk.tbtcContracts.(...) // Access Bitcoin client directly. sdk.bitcoinClient.(...) ``` -------------------------------- ### Install tBTC SDK Package Source: https://docs.threshold.network/app-development/tbtc-v2/tbtc-sdk/quickstart Commands to add the core tBTC SDK package to your project's dependencies using either Yarn or npm. ```JavaScript yarn add @keep-network/tbtc-v2.ts ``` ```JavaScript npm i @keep-network/tbtc-v2.ts ``` -------------------------------- ### Check Installed Docker Version Source: https://docs.threshold.network/staking-and-running-a-node/tbtc-v2-node-setup/sepolia-testnet-staking/testnet-tbtc-v2-node-setup Executes the `docker --version` command to display the currently installed Docker client and server versions. This is a quick way to verify Docker installation and check its version for compatibility or troubleshooting purposes. ```bash docker --version ``` -------------------------------- ### tBTC SDK Initialization Guides Source: https://docs.threshold.network/app-development/random-beacon/random-beacon-api/randombeacongovernance This section provides guides for initializing the tBTC SDK across various network configurations. It covers setup for Ethereum and Bitcoin mainnets, testnets, cross-chain environments, and custom modes, enabling developers to integrate tBTC functionalities into their applications. ```APIDOC tBTC SDK Initialization: - Quickstart: Rapid setup guide for the tBTC SDK. - Architecture: Overview of the SDK's internal structure. - Guides: - Initialize SDK: - Ethereum and Bitcoin mainnet: Configuration for mainnet environments. - Ethereum and Bitcoin testnet: Configuration for testnet environments. - Crosschain: Setup for cross-chain interactions. - Custom mode: Advanced configuration for specific needs. - Deposit and mint: Guide for depositing BTC and minting tBTC. ``` -------------------------------- ### Initialize and Use tBTC SDK for Cross-chain (L2) Operations Source: https://docs.threshold.network/app-development/tbtc-v2/tbtc-sdk/quickstart This example illustrates how to configure the tBTC SDK for use in a cross-chain environment, such as Arbitrum. It involves initializing the SDK with an Ethereum provider and a specific L2 signer, enabling access to SDK features across different chains. ```TypeScript // Import SDK entrypoint component. import { TBTC } from "@keep-network/tbtc-v2.ts" // Create an instance of ethers provider. const ethProvider = (...) // Create an instance of ethers signer. const arbitrumSigner = (...) // Initialize the SDK for Ethereum only. const sdk = await TBTC.initializeMainnet(ethProvider, true) // Initialize it for any L2 (E.g., Arbitrum) await sdk.initializeCrossChain("Arbitrum", arbitrumSigner); // Access SDK features. sdk.deposits.(...) sdk.redemptions.(...) // Access tBTC smart contracts directly. sdk.tbtcContracts.(...) // Access Bitcoin client directly. sdk.bitcoinClient.(...) ``` -------------------------------- ### keep-client start Command-Line Interface Options Source: https://docs.threshold.network/staking-and-running-a-node/tbtc-v2-node-setup/advanced-options/cli-options This entry details the available command-line flags for starting the `keep-client` application. It covers configuration parameters for connecting to Ethereum and Bitcoin Electrum networks, network settings, storage paths, client information services, tBTC pre-parameters, and developer-specific smart contract addresses. These options allow operators to customize the client's behavior and connectivity. ```APIDOC $ keep-client start --help Starts the Keep Client in the foreground Usage: keep-client start [flags] Flags: --ethereum.url string WS connection URL for Ethereum client. --ethereum.keyFile string The local filesystem path to Keep operator account keyfile. --ethereum.miningCheckInterval duration The time interval in seconds in which transaction mining status is checked. If the transaction is not mined within this time, the gas price is increased and transaction is resubmitted. (default 1m0s) --ethereum.maxGasFeeCap wei The maximum gas fee the client is willing to pay for the transaction to be mined. If reached, no resubmission attempts are performed. (default 500 gwei) --ethereum.requestPerSecondLimit int Request per second limit for all types of Ethereum client requests. (default 150) --ethereum.concurrencyLimit int The maximum number of concurrent requests which can be executed against Ethereum client. (default 30) --ethereum.balanceAlertThreshold wei The minimum balance of operator account below which client starts reporting errors in logs. (default 500000000 gwei) --bitcoin.electrum.url scheme://hostname:port URL to the Electrum server in format: scheme://hostname:port. --bitcoin.electrum.connectTimeout duration Timeout for a single attempt of Electrum connection establishment. (default 10s) --bitcoin.electrum.connectRetryTimeout duration Timeout for Electrum connection establishment retries. (default 1m0s) --bitcoin.electrum.requestTimeout duration Timeout for a single attempt of Electrum protocol request. (default 30s) --bitcoin.electrum.requestRetryTimeout duration Timeout for Electrum protocol request retries. (default 2m0s) --bitcoin.electrum.keepAliveInterval duration Interval for connection keep alive requests. (default 5m0s) --network.bootstrap Run the client in bootstrap mode. --network.peers strings Addresses of the network bootstrap nodes. -p, --network.port int Keep client listening port. (default 3919) --network.announcedAddresses strings Overwrites the default Keep client address announced in the network. Should be used for NAT or when more advanced firewall rules are applied. --network.disseminationTime int Specifies courtesy message dissemination time in seconds for topics the node is not subscribed to. Should be used only on selected bootstrap nodes. (0 = none) --storage.dir string Location to store the Keep client key shares and other sensitive data. --clientInfo.port int Client Info HTTP server listening port. (default 9601) --clientInfo.networkMetricsTick duration Client Info network metrics check tick in seconds. (default 1m0s) --clientInfo.ethereumMetricsTick duration Client info Ethereum metrics check tick in seconds. (default 10m0s) --tbtc.preParamsPoolSize int tECDSA pre-parameters pool size. (default 1000) --tbtc.preParamsGenerationTimeout duration tECDSA pre-parameters generation timeout. (default 2m0s) --tbtc.preParamsGenerationDelay duration tECDSA pre-parameters generation delay. (default 10s) --tbtc.preParamsGenerationConcurrency int tECDSA pre-parameters generation concurrency. (default 1) --tbtc.keyGenerationConcurrency int tECDSA key generation concurrency. (default number of cores) --developer.bridgeAddress string Address of the Bridge smart contract --developer.lightRelayAddress string Address of the LightRelay smart contract --developer.lightRelayMaintainerProxyAddress string Address of the LightRelayMaintainerProxy smart contract --developer.randomBeaconAddress string Address of the RandomBeacon smart contract --developer.tokenStakingAddress string Address of the TokenStaking smart contract --developer.walletRegistryAddress string Address of the WalletRegistry smart contract --developer.walletCoordinatorAddress string Address of the WalletCoordinator smart contract Global Flags: ``` -------------------------------- ### tBTC Client Docker Compose Configuration Source: https://docs.threshold.network/staking-and-running-a-node/tbtc-v2-node-setup/installation/docker-installation This YAML configuration defines a Docker Compose setup for the tBTC client. It specifies the Docker image, container name, restart policy, port mappings, volume mounts for configuration and storage, environment variables for Ethereum password and log level, and logging options. It also includes the full command to start the client with placeholders for specific details. ```YAML version: '3' services: keep-client: image: keepnetwork/keep-client:latest container_name: keep-client restart: on-failure ports: - "3919:3919" - "9601:9601" volumes: - /home/$USER/keep/config/:/mnt/keep/config - /home/$USER/keep/storage/:/mnt/keep/storage environment: - KEEP_ETHEREUM_PASSWORD= - LOG_LEVEL=info logging: options: max-size: "100m" max-file: "3" command: start --ethereum.url "" --ethereum.keyFile "/mnt/keep/config/" --storage.dir "/mnt/keep/storage" --network.announcedAddresses "/ip4//tcp/3919" ``` -------------------------------- ### Comprehensive TOML Configuration Example for Keep Client Source: https://docs.threshold.network/staking-and-running-a-node/tbtc-v2-node-setup/advanced-options/config-file This extensive TOML configuration file provides a detailed example for setting up the Keep client. It covers essential parameters for Ethereum node interaction, including URL, keystore file, transaction monitoring (MiningCheckInterval, MaxGasFeeCap), and rate limiting (RequestsPerSecondLimit, ConcurrencyLimit). Additionally, it includes settings for Bitcoin Electrum server connectivity, network peer management, and local storage paths, with comments explaining each option. ```toml # This is a sample TOML configuration file for the Keep client. [ethereum] URL = "ws://127.0.0.1:8546" KeyFile = "/Users/someuser/ethereum/data/keystore/UTC--2018-03-11T01-37-33.202765887Z--AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA8AAAAAAAAA" # Uncomment to override the defaults for transaction status monitoring. # MiningCheckInterval is the interval in which transaction # mining status is checked. If the transaction is not mined within this # time, the gas price is increased and transaction is resubmitted. # # MiningCheckInterval = 60 # 60 sec (default value) # MaxGasFeeCap specifies the maximum gas fee cap the client is # willing to pay for the transaction to be mined. The offered transaction # gas cost can not be higher than the max gas fee cap value. If the maximum # allowed gas fee cap is reached, no further resubmission attempts are # performed. This property should be set only for Ethereum. In case of # legacy non-EIP-1559 transactions, this field works in the same way as # `MaxGasPrice` property. # # MaxGasFeeCap = "500 Gwei" # 500 Gwei (default value) # Uncomment to enable Ethereum node rate limiting. Both properties can be # used together or separately. # # RequestsPerSecondLimit sets the maximum average number of requests # per second which can be executed against the Ethereum node. # All types of Ethereum node requests are rate-limited, # including view function calls. # # RequestsPerSecondLimit = 150 # ConcurrencyLimit sets the maximum number of concurrent requests which # can be executed against the Ethereum node at the same time. # This limit affects all types of Ethereum node requests, # including view function calls. # # ConcurrencyLimit = 30 # BalanceAlertThreshold defines a minimum value of the operator's account # balance below which the client will start reporting errors in logs. # A value can be provided in `wei`, `Gwei` or `ether`, e.g. `7.5 ether`, # `7500000000 Gwei`. # # BalanceAlertThreshold = "0.5 ether" # 0.5 ether (default value) [bitcoin.electrum] # URL to the Electrum server in format: `scheme://hostname:port`. # Should be uncommented only when using a custom Electrum server. Otherwise, # one of the default embedded servers is selected randomly at startup. # URL = "tcp://127.0.0.1:50001" # Timeout for a single attempt of Electrum connection establishment. # ConnectTimeout = "10s" # Timeout for Electrum connection establishment retries. # ConnectRetryTimeout = "1m" # Timeout for a single attempt of Electrum protocol request. # RequestTimeout = "30s" # Timeout for Electrum protocol request retries. # RequestRetryTimeout = "2m" # Interval for connection keep alive requests. # KeepAliveInterval = "5m" [network] Bootstrap = false Peers = [ "/ip4/127.0.0.1/tcp/3919/ipfs/16Uiu2HAmFRJtCWfdXhZEZHWb4tUpH1QMMgzH1oiamCfUuK6NgqWX", ] Port = 3920 # Uncomment to override the node's default addresses announced in the network # AnnouncedAddresses = ["/dns4/example.com/tcp/3919", "/ip4/80.70.60.50/tcp/3919"] # Uncomment to enable courtesy message dissemination for topics this node is # not subscribed to. Messages will be forwarded to peers for the duration # specified as a value in seconds. # Message dissemination is disabled by default and should be enabled only # on selected bootstrap nodes. It is not a good idea to enable dissemination # on non-bootstrap node as it may clutter communication and eventually lead # to blacklisting the node. The maximum allowed value is 90 seconds. # # DisseminationTime = 90 [storage] Dir = "/my/secure/location" ``` -------------------------------- ### List Downloaded Files Source: https://docs.threshold.network/staking-and-running-a-node/tbtc-v2-node-setup/installation/binary-installation Displays a detailed list of files and directories in the current location after downloading the binary. This command is useful for verifying the presence and name of the downloaded archive. ```bash ls -la ``` -------------------------------- ### Navigate to Operator Key Directory Source: https://docs.threshold.network/staking-and-running-a-node/tbtc-v2-node-setup/sepolia-testnet-staking/testnet-tbtc-v2-node-setup Changes the current working directory to `~/operator-key`. This is the expected location of the operator account key file after Geth installation, from where it needs to be copied for client configuration. ```bash cd ~/operator-key ``` -------------------------------- ### Enable Systemd Service for Docker Compose Source: https://docs.threshold.network/staking-and-running-a-node/tbtc-v2-node-setup/installation/docker-installation This command enables the previously created Systemd service, ensuring that the Docker Compose application starts automatically upon system boot. It integrates the service into the system's startup process. ```Shell sudo systemctl enable docker-compose-app ``` -------------------------------- ### Making Launch Script Executable Source: https://docs.threshold.network/staking-and-running-a-node/tbtc-v2-node-setup/installation/docker-installation This command grants execute permissions to the 'keep.sh' script, allowing it to be run as a program from the command line. ```Shell sudo chmod +x keep.sh ``` -------------------------------- ### Create tBTC v2 Systemd Service File Source: https://docs.threshold.network/staking-and-running-a-node/tbtc-v2-node-setup/installation/docker-installation These commands guide the user to the Systemd service directory and open a new file named `tbtcv2.service` for editing. This file will contain the Systemd unit definition for the tBTC v2 client. ```Shell cd /etc/systemd/system/ ``` ```Shell nano tbtcv2.service ``` -------------------------------- ### Systemd Service for Docker Compose Auto-Start Source: https://docs.threshold.network/staking-and-running-a-node/tbtc-v2-node-setup/installation/docker-installation This Systemd service unit file ensures that a Docker Compose application, such as the tBTC client, starts automatically after a server reboot. It defines dependencies on the Docker service, specifies the working directory, and includes commands for starting and stopping the Docker Compose application. ```Shell # /etc/systemd/system/docker-compose-app.service [Unit] Description=Docker Compose Application Service Requires=docker.service After=docker.service StartLimitIntervalSec=60 [Service] WorkingDirectory=/home/$USER/keep/ ExecStart=/usr/local/bin/docker-compose up ExecStop=/usr/local/bin/docker-compose down TimeoutStartSec=0 Restart=on-failure StartLimitBurst=3 [Install] WantedBy=multi-user.target ``` -------------------------------- ### Check Docker Version Source: https://docs.threshold.network/staking-and-running-a-node/tbtc-v2-node-setup/installation/docker-installation This command allows users to verify the currently installed version of Docker on their system, which is useful for ensuring compatibility and troubleshooting. ```Shell docker --version ``` -------------------------------- ### Managing tBTC v2 Systemd Service Source: https://docs.threshold.network/staking-and-running-a-node/tbtc-v2-node-setup/installation/docker-installation These commands are used to control and monitor the tBTC v2 systemd service. They allow starting the service, checking its current status, and enabling it to start automatically upon system boot. ```Shell sudo systemctl start tbtcv2 sudo systemctl status tbtcv2 systemctl enable tbtcv2 ``` -------------------------------- ### tBTC v2 Client Systemd Service Configuration Source: https://docs.threshold.network/staking-and-running-a-node/tbtc-v2-node-setup/installation/docker-installation This Systemd service unit configuration defines how the tBTC v2 client runs as a system service. It specifies dependencies, sets various environment variables required by the client (such as Ethereum URL, operator key details, and directories), and ensures the service starts after network availability. ```Shell [Unit] Description=tBTC v2 client After=network.target Wants=network.target [Service] Environment="ETHEREUM_WS_URL=" Environment="OPERATOR_KEY_FILE_NAME=" Environment="OPERATOR_KEY_FILE_PASSWORD=" Environment="PUBLIC_IP=/ip4//tcp/3919" Environment="CONFIG_DIR=/home//keep/config" Environment="STORAGE_DIR=/home//keep/storage" # These items only apply if you setup rootless-mode. ``` -------------------------------- ### Creating tBTC v2 Client Launch Script Source: https://docs.threshold.network/staking-and-running-a-node/tbtc-v2-node-setup/installation/docker-installation This command opens the 'keep.sh' file in the nano text editor, allowing the user to create or edit the bash script for launching the tBTC v2 Docker client. ```Shell nano keep.sh ``` -------------------------------- ### Rebooting System Source: https://docs.threshold.network/staking-and-running-a-node/tbtc-v2-node-setup/installation/docker-installation This command immediately reboots the system. It is used to test if the tBTC v2 service, once enabled, correctly starts up automatically after a system restart. ```Shell reboot now ``` -------------------------------- ### Executing tBTC v2 Client Launch Script Source: https://docs.threshold.network/staking-and-running-a-node/tbtc-v2-node-setup/installation/docker-installation This command executes the 'keep.sh' bash script with superuser privileges, which in turn launches the tBTC v2 Docker client as configured within the script. ```Shell sudo bash keep.sh ``` -------------------------------- ### Make tBTC v2 Client Launch Script Executable Source: https://docs.threshold.network/staking-and-running-a-node/tbtc-v2-node-setup/sepolia-testnet-staking/testnet-tbtc-v2-node-setup Grants execute permissions to the `keep.sh` script using `sudo chmod +x`. This is a necessary step to allow the script to be run directly from the command line. ```bash sudo chmod +x keep.sh ``` -------------------------------- ### Execute tBTC v2 Client Launch Script Source: https://docs.threshold.network/staking-and-running-a-node/tbtc-v2-node-setup/sepolia-testnet-staking/testnet-tbtc-v2-node-setup Runs the `keep.sh` bash script with superuser privileges. This command initiates the tBTC v2 client as a Docker container based on the configurations defined within the script. ```bash sudo bash keep.sh ``` -------------------------------- ### Checking Running Docker Containers Source: https://docs.threshold.network/staking-and-running-a-node/tbtc-v2-node-setup/installation/docker-installation This command lists all currently running Docker containers. It is useful for verifying that the tBTC v2 client Docker container is active and operational. ```Shell docker ps ``` -------------------------------- ### Relay Genesis Initialization Source: https://docs.threshold.network/app-development/tbtc-v2/tbtc-contracts-api/tbtc-v2-api/lightrelay Establishes the initial state and starting point for the relay, defining the first block of the genesis epoch. This function sets the foundational parameters for the relay's operation. ```APIDOC function genesis(bytes genesisHeader, uint256 genesisHeight, uint64 genesisProofLength) external - Establishes a starting point for the relay by providing the target, timestamp and blockheight of the first block of the relay genesis epoch. - Parameters: - genesisHeader (bytes): The first block header of the genesis epoch. - genesisHeight (uint256): The block number of the first block of the epoch. - genesisProofLength (uint64): The number of blocks required to accept a proof. ``` -------------------------------- ### Extract tBTC v2 Client Binary Archive Source: https://docs.threshold.network/staking-and-running-a-node/tbtc-v2-node-setup/installation/binary-installation Extracts the downloaded gzipped tar archive using the 'tar' command. Users should replace 'downloaded-file-name-here.tar.gz' with the actual filename of the downloaded binary archive. ```bash tar xzvf downloaded-file-name-here.tar.gz ``` -------------------------------- ### List Running Docker Containers Source: https://docs.threshold.network/staking-and-running-a-node/tbtc-v2-node-setup/installation/docker-installation This command lists all currently running Docker containers, displaying their IDs, names, images, and other relevant details. It is essential for identifying the specific container instance (e.g., 'stinky_brownie') whose logs you wish to retrieve. ```Shell sudo docker ps ``` -------------------------------- ### Download tBTC v2 Client Binary Source: https://docs.threshold.network/staking-and-running-a-node/tbtc-v2-node-setup/installation/binary-installation Changes the current directory to '/home/keep' and downloads the tBTC v2 client binary from the specified GitHub release URL using 'wget'. Users must replace 'XX.X.X-XX' with the actual version number. ```bash cd /home/keep wget https://github.com/keep-network/keep-core/releases/download/XX.X.X-XX/keep-client-mainnet-XX.X.X-XX-linux-amd64.tar.gz ``` -------------------------------- ### Create tBTC v2 Client Launch Script File Source: https://docs.threshold.network/staking-and-running-a-node/tbtc-v2-node-setup/sepolia-testnet-staking/testnet-tbtc-v2-node-setup Opens a new file named `keep.sh` in the `nano` text editor. This file will contain the bash script used to launch the tBTC v2 client via Docker, simplifying the execution process by encapsulating all necessary configuration flags and environment variables. ```bash nano keep.sh ``` -------------------------------- ### Configure tBTC v2 Client Command-Line Flags Source: https://docs.threshold.network/staking-and-running-a-node/tbtc-v2-node-setup/installation/binary-installation Defines essential command-line flags for configuring the tBTC v2 client. These flags specify the Ethereum URL, storage directory, operator key file, and network announced addresses (either IP or DNS). These parameters are typically passed when launching the client. ```bash --ethereum.url "wss://mainnet-ETH-enpoint-here" --storage.dir "/home/keep/storage" --ethereum.keyFile "/home/keep/config/UTC--Your-Operator-Key-Name" # to configure your node to use your machine's public IP --network.announcedAddresses "/ip4/your.ipv4.address.here/tcp/3919" # to configure your node to use DNS, provide your DNS in the following # format ``` -------------------------------- ### tBTC v2 Client Docker Launch Script Source: https://docs.threshold.network/staking-and-running-a-node/tbtc-v2-node-setup/sepolia-testnet-staking/testnet-tbtc-v2-node-setup A comprehensive bash script designed to launch the tBTC v2 client as a Docker container. It configures essential environment variables such as the Ethereum WebSocket URL, operator key file name and password, and the machine's public IP. The script then mounts persistent storage and configuration directories, exposes necessary ports, and runs the `keep-client` Docker image with specified parameters. ```bash # Keep Testnet tBTC v2 Client # # Ethereum endpoint WebSocket URL # This can be a provider such as Infura, Alchemy, Ankr, etc or your own Geth Nodeq # ETHEREUM_WS_URL="wss://sepolia.infura.io/ws/v3/redacted_credentials" # note: only replace characters inside the " ". The Quotation marks must be retained ETHEREUM_WS_URL="" # copied to home/keep/config earlier OPERATOR_KEY_FILE_NAME="" # password set during Operator Account Address creation OPERATOR_KEY_FILE_PASSWORD="" # To configure your node with a Public IP, enter it below. PUBLIC_IP="" # Alternatively, you can use DNS. # To configure DNS, modify the last line of the script # and add your DNS in the following format: # /dns4/bootstrap-1.test.keep.network/tcp/3919 # Setup configuration and storage directories # THESE MUST BE PERSISTENT STORAGE CONFIG_DIR="/home/keep/config" STORAGE_DIR="/home/keep/storage" docker run \ --detach \ --restart on-failure \ --volume $CONFIG_DIR:/mnt/keep/config \ --volume $STORAGE_DIR:/mnt/keep/storage \ --env KEEP_ETHEREUM_PASSWORD=$OPERATOR_KEY_FILE_PASSWORD \ --env LOG_LEVEL=info \ --log-opt max-size=100m \ --log-opt max-file=3 \ -p 3919:3919 \ -p 9601:9601 \ us-docker.pkg.dev/keep-test-f3e0/public/keep-client \ start \ --testnet \ --ethereum.url $ETHEREUM_WS_URL \ --ethereum.keyFile /mnt/keep/config/$OPERATOR_KEY_FILE_NAME \ --storage.dir /mnt/keep/storage \ --network.announcedAddresses /ip4/$PUBLIC_IP/tcp/3919 ``` -------------------------------- ### Create tBTC v2 Client Directories Source: https://docs.threshold.network/staking-and-running-a-node/tbtc-v2-node-setup/sepolia-testnet-staking/testnet-tbtc-v2-node-setup This snippet creates the essential `keep`, `storage`, and `config` directories required for the tBTC v2 client. The `storage` directory is designed to house `keystore` (sensitive key material) and `work` (persistent client data) subdirectories, which are critical for the client's operation and data integrity. ```bash cd /home mkdir keep cd keep mkdir storage config ``` -------------------------------- ### Get Wallet Information Source: https://docs.threshold.network/app-development/tbtc-v2/tbtc-contracts-api/ecdsa-api/walletregistry Retrieves the full `Wallet` struct associated with a given wallet ID. This provides comprehensive details about a registered wallet. ```Solidity function getWallet(bytes32 walletID) external view returns (struct Wallets.Wallet) ``` ```APIDOC getWallet(walletID: bytes32) Description: Retrieves the full wallet struct for a given wallet ID. Parameters: - walletID: ID of the wallet. Returns: struct Wallets.Wallet: The wallet struct containing its details. ``` -------------------------------- ### Get Pending Authorization Decrease Source: https://docs.threshold.network/app-development/tbtc-v2/tbtc-contracts-api/ecdsa-api/walletregistry Provides the amount of stake for which an authorization decrease has been requested but not yet finalized. If no such request is active, the function returns zero. ```Solidity function pendingAuthorizationDecrease(address stakingProvider) external view returns (uint96) ``` ```APIDOC pendingAuthorizationDecrease(stakingProvider: address) Description: Returns the amount of stake that is pending authorization decrease for the given staking provider. If no authorization decrease has been requested, returns zero. Parameters: - stakingProvider: The address of the staking provider. Returns: uint96: The amount of pending authorization decrease. ``` -------------------------------- ### Run Keep Client with External Configuration File Source: https://docs.threshold.network/staking-and-running-a-node/tbtc-v2-node-setup/advanced-options/config-file This snippet illustrates the command-line usage of the `keep-client` application, showing how to specify an external configuration file (e.g., TOML) using the `--config` flag. This method enables the client to load its operational parameters from a designated file, supporting flexible deployment and management. ```bash ./keep-client --config /path/to/your/config.toml start ``` -------------------------------- ### Solidity Get Field Modulus 'p' Source: https://docs.threshold.network/app-development/random-beacon/random-beacon-api/altbn128 A simple function to retrieve the field modulus 'p' used in the AltBn128 curve operations. ```Solidity function getP() internal pure returns (uint256) - Description: Returns the field modulus 'p' for the AltBn128 curve. - Returns: - uint256: The value of 'p'. ``` -------------------------------- ### Get Wallet Public Key Source: https://docs.threshold.network/app-development/tbtc-v2/tbtc-contracts-api/ecdsa-api/walletregistry Fetches the public key for a specified wallet ID. The public key is returned in an uncompressed format, consisting of the concatenated X and Y coordinates. ```Solidity function getWalletPublicKey(bytes32 walletID) external view returns (bytes) ``` ```APIDOC getWalletPublicKey(walletID: bytes32) Description: Gets public key of a wallet with a given wallet ID. The public key is returned in an uncompressed format as a 64-byte concatenation of X and Y coordinates. Parameters: - walletID: ID of the wallet. Returns: bytes: Uncompressed public key of the wallet. ``` -------------------------------- ### Copy Operator Account Key File to Configuration Source: https://docs.threshold.network/staking-and-running-a-node/tbtc-v2-node-setup/sepolia-testnet-staking/testnet-tbtc-v2-node-setup Lists files in the current directory (`ls -la`) to help identify the operator account key file, then copies it to the `/home/keep/config` directory. This step is crucial for the tBTC v2 client to access the necessary cryptographic keys for operation. ```bash ls -la cp name_of_account_key_file /home/keep/config/name_of_account_key_file ``` -------------------------------- ### Launch Keep Client Node with Specific Configuration Source: https://docs.threshold.network/staking-and-running-a-node/tbtc-v2-node-setup/installation/binary-installation This shell command initiates the Keep client node, connecting it to the specified Ethereum network endpoint. It configures the local storage directory for client data, points to the operator's Ethereum key file for authentication, and declares the node's announced network addresses. The client will prompt for the operator account password upon execution. ```shell ./keep-client start --ethereum.url "wss://mainnet-ETH-enpoint-here" --storage.dir "/home/keep/storage" --ethereum.keyFile "/home/keep/config/UTC--Your-Operator-Key-Name" --network.announcedAddresses "/ip4/your.ipv4.address.here/tcp/3919" ``` -------------------------------- ### Get Count of Active Groups (Solidity) Source: https://docs.threshold.network/app-development/random-beacon/random-beacon-api/groups This function returns the total number of groups that are currently considered active. It specifically excludes groups that have expired or been terminated from the count. ```Solidity function numberOfActiveGroups(struct Groups.Data self) internal view returns (uint64) ``` ```APIDOC numberOfActiveGroups(self: Groups.Data) -> uint64 Gets the number of active groups. Expired and terminated groups are not counted as active. Parameters: self: The Groups.Data storage struct. Returns: uint64: The total count of active groups. ``` -------------------------------- ### Retrieve Voting Period Source: https://docs.threshold.network/app-development/staking-contract-and-dao/staking-contract-and-dao-api/governorparameters Retrieves the duration, in number of blocks, between the vote's start and end. It's important to consider the `votingDelay` when setting this period to ensure proper timing. ```Solidity function votingPeriod() public view virtual returns (uint256) ``` -------------------------------- ### Get Operator for Staking Provider Source: https://docs.threshold.network/app-development/tbtc-v2/tbtc-contracts-api/ecdsa-api/walletregistry Returns the operator address that has been registered and associated with a given staking provider address. This mapping is crucial for linking staking entities to their operational counterparts. ```Solidity function stakingProviderToOperator(address stakingProvider) public view returns (address) ``` ```APIDOC stakingProviderToOperator(stakingProvider: address) Description: Returns operator registered for the given staking provider. Parameters: - stakingProvider: The address of the staking provider. Returns: address: The operator address registered for the staking provider. ``` -------------------------------- ### List Running Docker Containers (Bash) Source: https://docs.threshold.network/staking-and-running-a-node/tbtc-v2-node-setup/sepolia-testnet-staking/testnet-tbtc-v2-node-setup This command displays a list of all active Docker containers, providing essential details like container ID, image, command, creation time, status, and assigned name. It is crucial for identifying the specific container name required for subsequent log retrieval. ```bash sudo docker ps ``` -------------------------------- ### Initialize TBTC SDK for Ethereum and Bitcoin Mainnet Source: https://docs.threshold.network/app-development/tbtc-v2/tbtc-sdk/guides/initialize-sdk/ethereum-and-bitcoin-mainnet This JavaScript code demonstrates how to initialize the tBTC SDK using the `TBTC.initializeMainnet` function. It shows how to create an Ethers `JsonRpcProvider` for read-only access and an Ethers `Wallet` (signer) for transactional capabilities, connecting the SDK to the Ethereum mainnet and configuring a Bitcoin Electrum client. ```javascript import * as ethers from "ethers" import { TBTC } from "@keep-network/tbtc-v2.ts" // Create an Ethers provider. Pass the URL of an Ethereum mainnet node. // For example, Alchemy or Infura. const provider = new ethers.providers.JsonRpcProvider("...") // Create an Ethers signer. Pass the private key and the above provider. const signer = new ethers.Wallet("...", provider) // If you want to initialize the SDK just for read-only actions, it is // enough to pass the provider. const sdkReadonly = await TBTC.initializeMainnet(provider) // If you want to make transactions as well, you have to pass the signer. const sdk = await TBTC.initializeMainnet(signer) ``` -------------------------------- ### Redemption Timeout Notifier Reward Multiplier Update Events Source: https://docs.threshold.network/app-development/tbtc-v2/tbtc-contracts-api/tbtc-v2-api/bridgegovernance These events are emitted when the reward multiplier for notifiers of redemption timeouts is being updated. They track the start and completion of this parameter change. ```Solidity event RedemptionTimeoutNotifierRewardMultiplierUpdateStarted(uint32 newRedemptionTimeoutNotifierRewardMultiplier, uint256 timestamp) ``` ```Solidity event RedemptionTimeoutNotifierRewardMultiplierUpdated(uint32 redemptionTimeoutNotifierRewardMultiplier) ``` -------------------------------- ### Threshold Network Client Configuration Source: https://docs.threshold.network/staking-and-running-a-node/tbtc-v2-node-setup/advanced-options/cli-options This section details the command-line arguments and environment variables available for configuring the Threshold Network client. These options allow users to specify configuration file paths, select network environments, and manage operational parameters like log levels and decryption passwords. ```APIDOC Threshold Network Configuration Options: Command-line Arguments: -c, --config string - Description: Path to the configuration file. - Supported formats: TOML, YAML, JSON. --developer - Description: Specifies the developer network. --testnet - Description: Specifies the testnet network. Environment Variables: KEEP_ETHEREUM_PASSWORD - Description: Password for Keep operator account keyfile decryption. LOG_LEVEL - Description: Space-delimited set of log level directives; set to "help" for help. ``` -------------------------------- ### Redemption Timeout Update Events Source: https://docs.threshold.network/app-development/tbtc-v2/tbtc-contracts-api/tbtc-v2-api/bridgegovernance These events track the process of updating the redemption timeout period. They are emitted when the update is started and when it is successfully applied, affecting the time limit for redemptions. ```Solidity event RedemptionTimeoutUpdateStarted(uint32 newRedemptionTimeout, uint256 timestamp) ``` ```Solidity event RedemptionTimeoutUpdated(uint32 redemptionTimeout) ``` -------------------------------- ### Threshold Network Smart Contract Constructor Source: https://docs.threshold.network/app-development/random-beacon/random-beacon-api/randombeacon Initializes the smart contract with essential dependencies and default parameters. These parameters are proposed defaults and can be updated using `update*` functions after deployment and before transferring ownership to the governance contract. ```APIDOC constructor(contract SortitionPool _sortitionPool, contract IERC20 _tToken, contract IStaking _staking, contract BeaconDkgValidator _dkgValidator, contract ReimbursementPool _reimbursementPool) public - Parameters: - _sortitionPool: The address of the SortitionPool contract. - _tToken: The address of the T Token (IERC20) contract. - _staking: The address of the Staking contract. - _dkgValidator: The address of the BeaconDkgValidator contract. - _reimbursementPool: The address of the ReimbursementPool contract. ``` -------------------------------- ### Redemption Transaction Max Fee Update Events Source: https://docs.threshold.network/app-development/tbtc-v2/tbtc-contracts-api/tbtc-v2-api/bridgegovernance These events are emitted when the maximum fee allowed for a redemption transaction is being updated. They track the start and completion of this critical parameter change. ```Solidity event RedemptionTxMaxFeeUpdateStarted(uint64 newRedemptionTxMaxFee, uint256 timestamp) ``` ```Solidity event RedemptionTxMaxFeeUpdated(uint64 redemptionTxMaxFee) ``` -------------------------------- ### Authorization Decrease Change Period Events Source: https://docs.threshold.network/app-development/random-beacon/random-beacon-api/randombeacongovernance These events track changes to the period during which authorization decreases can be applied. 'UpdateStarted' signals the start of an update, and 'Updated' confirms the new period. ```Solidity event AuthorizationDecreaseChangePeriodUpdateStarted(uint64 authorizationDecreaseChangePeriod, uint256 timestamp) event AuthorizationDecreaseChangePeriodUpdated(uint64 authorizationDecreaseChangePeriod) ``` -------------------------------- ### Bash Script for tBTC v2 Docker Client Launch Source: https://docs.threshold.network/staking-and-running-a-node/tbtc-v2-node-setup/installation/docker-installation This bash script defines essential configuration variables and executes the Docker run command to launch the tBTC v2 client. It includes settings for Ethereum endpoint, operator key file, public IP, and persistent storage directories, running the container in detached mode with automatic restart on failure. ```Shell # Keep tBTC v2 Client # # Ethereum endpoint WebSocket URL # This can be a provider such as Infura, Alchemy, Ankr, etc or your own Geth Nodeq # ETHEREUM_WS_URL="wss://mainnet.infura.io/ws/v3/redacted_credentials" # note: only replace characters inside the " ". The Quotation marks must be retained ETHEREUM_WS_URL="" # copied to home/keep/config earlier OPERATOR_KEY_FILE_NAME="" # password set during Operator Account Address creation OPERATOR_KEY_FILE_PASSWORD="" # To configure your node with a Public IP, enter it below. PUBLIC_IP="" # Alternatively, you can use DNS. # To configure DNS, modify the last line of the script # and add your DNS in the following format: # /dns4/bootstrap-1.test.keep.network/tcp/3919 # Setup configuration and storage directories # THESE MUST BE PERSISTENT STORAGE CONFIG_DIR="/home/$USER/keep/config" STORAGE_DIR="/home/$USER/keep/storage" docker run \ --detach \ --restart on-failure \ --volume $CONFIG_DIR:/mnt/keep/config \ --volume $STORAGE_DIR:/mnt/keep/storage \ --env KEEP_ETHEREUM_PASSWORD=$OPERATOR_KEY_FILE_PASSWORD \ --env LOG_LEVEL=info \ --log-opt max-size=100m \ --log-opt max-file=3 \ -p 3919:3919 \ -p 9601:9601 \ keepnetwork/keep-client:latest \ start \ --ethereum.url $ETHEREUM_WS_URL \ --ethereum.keyFile /mnt/keep/config/$OPERATOR_KEY_FILE_NAME \ --storage.dir /mnt/keep/storage \ --network.announcedAddresses /ip4/$PUBLIC_IP/tcp/3919 ``` -------------------------------- ### Get Minimum Authorization Amount Source: https://docs.threshold.network/app-development/tbtc-v2/tbtc-contracts-api/ecdsa-api/walletregistry Returns the minimum amount of authorization (stake) required for an operator to be eligible to participate in ECDSA Wallet operations. This value sets a baseline for operator eligibility. ```Solidity function minimumAuthorization() external view returns (uint96) ``` ```APIDOC minimumAuthorization() Description: The minimum authorization amount required so that operator can participate in ECDSA Wallet operations. Returns: uint96: The minimum authorization amount. ``` -------------------------------- ### Moving Funds Timeout Reset Delay Update Events Source: https://docs.threshold.network/app-development/tbtc-v2/tbtc-contracts-api/tbtc-v2-api/bridgegovernance These events track the process of updating the delay before a moving funds timeout can be reset. They are emitted when the update is started and when it is successfully applied. ```Solidity event MovingFundsTimeoutResetDelayUpdateStarted(uint32 newMovingFundsTimeoutResetDelay, uint256 timestamp) ``` ```Solidity event MovingFundsTimeoutResetDelayUpdated(uint32 movingFundsTimeoutResetDelay) ``` -------------------------------- ### Manage tBTC Client with Docker Compose Source: https://docs.threshold.network/staking-and-running-a-node/tbtc-v2-node-setup/installation/docker-installation These commands are used to control the tBTC client container via Docker Compose. They cover initial startup, running the container in detached mode (background), and gracefully stopping the container. Users should verify client operation after initial startup before detaching. ```Shell sudo docker compose up ``` ```Shell sudo docker compose up -d ``` ```Shell sudo docker compose down ``` -------------------------------- ### Retrieve Voting Delay Source: https://docs.threshold.network/app-development/staking-contract-and-dao/staking-contract-and-dao-api/governorparameters Retrieves the delay, in number of blocks, between a proposal's creation and the start of its voting period. This delay allows users to acquire or delegate voting power before voting commences. ```Solidity function votingDelay() public view virtual returns (uint256) ``` -------------------------------- ### Initiate tBTC Deposit with SDK Source: https://docs.threshold.network/app-development/tbtc-v2/tbtc-sdk/guides/deposit-and-mint This snippet demonstrates how to initialize the tBTC SDK and initiate a deposit. It involves setting a Bitcoin recovery address for emergency recovery and then obtaining the unique Bitcoin deposit address where BTC should be sent. ```typescript import { TBTC } from "@keep-network/tbtc-v2.ts" // Initialized SDK. const sdk: TBTC // Set the P2WPKH/P2PKH Bitcoin recovery address. It can be used to recover // deposited BTC in case something exceptional happens. const bitcoinRecoveryAddress: string = "..." // Initiate the deposit. const deposit = await sdk.deposits.initiateDeposit(bitcoinRecoveryAddress) // Take the Bitcoin deposit address. BTC must be sent here. const bitcoinDepositAddress = await deposit.getBitcoinAddress() ``` -------------------------------- ### Group Lifetime Update Events Source: https://docs.threshold.network/app-development/random-beacon/random-beacon-api/randombeacongovernance Events emitted when the group lifetime update process starts and when it is successfully completed. These events provide transparency into changes in the duration for which groups remain active. ```APIDOC event GroupLifetimeUpdateStarted(uint256 groupLifetime, uint256 timestamp) event GroupLifetimeUpdated(uint256 groupLifetime) ``` -------------------------------- ### Governance Delay Update Events Source: https://docs.threshold.network/app-development/random-beacon/random-beacon-api/randombeacongovernance Events emitted when the governance delay update process starts and when it is successfully completed. These events provide transparency into changes in the contract's governance parameters. ```APIDOC event GovernanceDelayUpdateStarted(uint256 governanceDelay, uint256 timestamp) event GovernanceDelayUpdated(uint256 governanceDelay) ``` -------------------------------- ### Initialize TBTC SDK with Custom Electrum Bitcoin Client Source: https://docs.threshold.network/app-development/tbtc-v2/tbtc-sdk/guides/initialize-sdk/custom-mode This TypeScript example shows how to initialize the TBTC SDK for mainnet or testnet while overriding the default Bitcoin client with a custom Electrum server. It involves creating an Ethers provider and signer for an Ethereum mainnet node, loading standard tBTC Ethereum contracts, and then passing a custom `ElectrumClient` instance to `TBTC.initializeCustom`. ```TypeScript import * as ethers from "ethers" import { TBTC, TBTCContracts, loadEthereumContracts, ElectrumClient } from "@keep-network/tbtc-v2.ts" // Create an Ethers provider. Pass a URL of an Ethereum mainnet node. // For example, Alchemy or Infura. const provider = new ethers.providers.JsonRpcProvider("...") // Create an Ethers signer. Pass the private key and the above provider. const signer = new ethers.Wallet("...", provider) // Load tBTC Ethereum mainnet contracts manually. const tbtcContracts: TBTCContracts = await loadEthereumContracts(signer, "mainnet") // Create an Electrum Bitcoin client pointing to your own mainnet server. const bitcoinClient = ElectrumClient.fromUrl("...") // Initialize the SDK with Electrum Bitcoin client pointing to your own server. const sdk = await TBTC.initializeCustom(tbtcContracts, bitcoinClient) ``` -------------------------------- ### Get Available Rewards for Staking Provider Source: https://docs.threshold.network/app-development/tbtc-v2/tbtc-contracts-api/ecdsa-api/walletregistry Retrieves the amount of rewards that are currently available for withdrawal by a specified staking provider. This function will revert if the staking provider has not registered an associated operator address. ```Solidity function availableRewards(address stakingProvider) external view returns (uint96) ``` ```APIDOC availableRewards(stakingProvider: address) Description: Returns the amount of rewards available for withdrawal for the given staking provider. Reverts if staking provider has not registered the operator address. Parameters: - stakingProvider: The address of the staking provider. Returns: uint96: The amount of available rewards. ``` -------------------------------- ### Initialize Contract Source: https://docs.threshold.network/app-development/staking-contract-and-dao/staking-contract-and-dao-api/tokenstaking The `initialize` function is typically called once after deployment to set up initial contract states or configurations that cannot be handled by the constructor. ```Solidity function initialize() external ``` -------------------------------- ### Navigate to Operator Keystore Directory Source: https://docs.threshold.network/staking-and-running-a-node/tbtc-v2-node-setup/data-storage This command changes the current directory to the location where the operator key file is expected to be found. This directory, typically `/.operator-key` within the user's home, contains the sensitive account key file required for client operation. ```bash cd /home/$USER/.operator-key ``` -------------------------------- ### Solidity Redemption Dust Threshold Update Events Source: https://docs.threshold.network/app-development/tbtc-v2/tbtc-contracts-api/tbtc-v2-api/bridgegovernanceparameters Events for updates to the redemption dust threshold. `RedemptionDustThresholdUpdateStarted` indicates the start of an update process, and `RedemptionDustThresholdUpdated` confirms the new threshold value. ```Solidity event RedemptionDustThresholdUpdateStarted(uint64 newRedemptionDustThreshold, uint256 timestamp) event RedemptionDustThresholdUpdated(uint64 redemptionDustThreshold) ``` -------------------------------- ### Moving Funds Timeout Notifier Reward Multiplier Update Events Source: https://docs.threshold.network/app-development/tbtc-v2/tbtc-contracts-api/tbtc-v2-api/bridgegovernance These events are emitted when the reward multiplier for notifiers of moving funds timeouts is being updated. They track the start and completion of this parameter change. ```Solidity event MovingFundsTimeoutNotifierRewardMultiplierUpdateStarted(uint32 newMovingFundsTimeoutNotifierRewardMultiplier, uint256 timestamp) ``` ```Solidity event MovingFundsTimeoutNotifierRewardMultiplierUpdated(uint32 movingFundsTimeoutNotifierRewardMultiplier) ``` -------------------------------- ### Initialize tBTC SDK with Mock Contracts and Bitcoin Client Source: https://docs.threshold.network/app-development/tbtc-v2/tbtc-sdk/guides/initialize-sdk/custom-mode This TypeScript code demonstrates how to initialize the tBTC SDK using custom mock implementations of `Bridge`, `TBTCToken`, `TBTCVault`, `WalletRegistry` contracts, and a `BitcoinClient`. This approach is useful for testing purposes, allowing developers to simulate contract interactions and Bitcoin network behavior without relying on actual blockchain deployments. ```TypeScript import { TBTC, TBTCContracts, Bridge, TBTCToken, TBTCVault, WalletRegistry, BitcoinClient, } from "@keep-network/tbtc-v2.ts" // Create mock Bridge contract implementation. class MockBridge implements Bridge { // Implement all required methods } // Create mock TBTCToken contract implementation. class MockTBTCToken implements TBTCToken { // Implement all required methods } // Create mock TBTCVault contract implementation. class MockTBTCVault implements TBTCVault { // Implement all required methods } // Create mock WalletRegistry contract implementation. class MockWalletRegistry implements WalletRegistry { // Implement all required methods } // Create mock BitcoinClient contract implementation. class MockBitcoinClient implements BitcoinClient { // Implement all required methods } // Create instances of the mock contracts. const tbtcContracts: TBTCContracts = { bridge: new MockBridge(), tbtcToken: new MockTBTCToken(), tbtcVault: new MockTBTCVault(), walletRegistry: new MockWalletRegistry() } // Create an instance of the mock Bitcoin client. const bitcoinClient = new MockBitcoinClient() // Initialize the SDK. const sdk = await TBTC.initializeCustom(tbtcContracts, bitcoinClient) ```