### Install Union SDK with npm Source: https://docs.union.build/integrations/typescript Installs the Union SDK package version 2.0.0-beta.0 using the npm package manager. Ensure npm is installed and configured correctly. ```bash npm install @unionlabs/sdk@^2.0.0-beta.0 ``` -------------------------------- ### Install Union SDK with yarn Source: https://docs.union.build/integrations/typescript Installs the Union SDK package version 2.0.0-beta.0 using the yarn package manager. Ensure yarn is installed and configured correctly. ```bash yarn add @unionlabs/sdk@^2.0.0-beta.0 ``` -------------------------------- ### Install Union SDK with pnpm Source: https://docs.union.build/integrations/typescript Installs the Union SDK package version 2.0.0-beta.0 using the pnpm package manager. Ensure pnpm is installed and configured correctly. ```bash pnpm add @unionlabs/sdk@^2.0.0-beta.0 ``` -------------------------------- ### Start Uniond Node with Docker Compose Source: https://docs.union.build/joining-testnet/obtaining-uniond Starts the uniond node defined in a Docker Compose file in detached mode. Requires a 'compose.yaml' file with the service definition and Docker Compose installed. ```bash docker compose --file path/to/compose.yaml up --detach ``` -------------------------------- ### Verify uniond Binary Source: https://docs.union.build/infrastructure/node-operators/getting-started Executes the uniond binary with the --help flag to verify its functionality on the server. This is a basic check to ensure the binary is executable and responsive. ```bash ./uniond --help ``` -------------------------------- ### Configure Genesis File Source: https://docs.union.build/infrastructure/node-operators/getting-started Downloads the genesis.json file from the specified GENESIS_URL and pipes it through jq to extract the genesis configuration, saving it to the uniond config directory. ```bash curl $GENESIS_URL | jq '.result.genesis' > ~/.union/config/genesis.json ``` -------------------------------- ### Example Solver Implementation (Solidity) Source: https://docs.union.build/ucs/03 A practical example of a Solidity solver contract, MultiDEXSolver, demonstrating how to implement the ISolver interface and handle beneficiary address configuration. ```APIDOC ## Example Solver Implementation (Solidity) ### Description Provides a concrete example of a Solidity contract, `MultiDEXSolver`, that implements the `ISolver` interface, showcasing how to manage beneficiary addresses and execute trades. ### Method N/A (Contract Example) ### Endpoint N/A (Contract Example) ### Parameters N/A (Contract Example) ### Request Example N/A (Contract Example) ### Response N/A (Contract Example) ### Solidity Implementation Example ```solidity contract MultiDEXSolver is ISolver { // Beneficiary addresses configured per path/channel/token // Using bytes to support addresses from different chains (not just 20-byte addresses) mapping(uint256 => mapping(uint32 => mapping(bytes => bytes))) public beneficiaries; struct DEXParams { uint256 maxSlippage; address[] routePath; uint256 deadline; } function solve( IBCPacket calldata packet, TokenOrderV2 calldata order, uint256 path, address caller, address relayer, bytes calldata relayerMsg, bool intent ) external override returns (bytes memory) { require(!intent, "only finalized txs are currently supported"); // Decode the SolverMetadata from the order SolverMetadata memory solverMeta = abi.decode(order.metadata, (SolverMetadata)); // Decode custom parameters from the solver metadata's metadata field DEXParams memory params = abi.decode(solverMeta.metadata, (DEXParams)); // Validate deadline require(block.timestamp <= params.deadline, "Order expired"); // The quoteToken from the order specifies what token to provide address quoteToken = address(bytes20(order.quoteToken)); address receiver = address(bytes20(order.receiver)); // Validate that we support this quote token require(isSupported(quoteToken), "Unsupported quote token"); // Perform the trade to obtain the quote tokens // ... (rest of the trade logic) return bytes(receiver); // Example return } function isSupported(address token) internal pure returns (bool) { // Placeholder for token support check return true; } } ``` ### Important Implementation Detail Solvers typically configure different beneficiary addresses per path/channel/token combination. This allows them to: * Route base tokens to different vaults or addresses on different chains. * Manage liquidity separately for different trading pairs. * Coordinate with counterparty contracts on the source chain. ``` -------------------------------- ### Download uniond Binary for x86_64 Linux Source: https://docs.union.build/infrastructure/node-operators/getting-started Downloads the uniond release binary for x86_64 Linux architecture. Requires setting the UNIOND_VERSION environment variable. The output is saved to a file named 'uniond'. ```bash curl --output uniond --location https://github.com/unionlabs/union/releases/download/$UNIOND_VERSION/uniond-release-x86_64-linux ``` -------------------------------- ### Create Validator JSON File Source: https://docs.union.build/infrastructure/node-operators/getting-started Creates an empty file named 'validator.json' which will be populated with validator details for submission. ```bash touch validator.json ``` -------------------------------- ### Add uniond Binary to PATH Source: https://docs.union.build/infrastructure/node-operators/getting-started Moves the downloaded uniond binary to the /usr/bin directory, making it accessible from any location in the terminal by adding it to the system's PATH. ```bash mv ./uniond /usr/bin/ ``` -------------------------------- ### Configure uniond as a Systemd Service Source: https://docs.union.build/infrastructure/node-operators/getting-started This configuration sets up the uniond daemon to run as a systemd service. It defines the service description, restart policy, user, and the command to start the daemon. This ensures that uniond runs reliably in the background and restarts automatically if it fails. ```systemd [Unit] Description=uniond [Service] Type=simple Restart=always RestartSec=1 User=$USER ExecStart=/usr/bin/uniond start [Install] WantedBy=multi-user.target ``` -------------------------------- ### Set Initialization Environment Variables Source: https://docs.union.build/infrastructure/node-operators/getting-started Sets essential environment variables for node initialization, including chain ID, validator moniker, key name, and the genesis file URL. ```bash export CHAIN_ID=union-1 export MONIKER="unionized-goblin" export KEY_NAME=alice export GENESIS_URL="https://union.build/genesis.json" ``` -------------------------------- ### Download uniond Binary for aarch64 Linux Source: https://docs.union.build/infrastructure/node-operators/getting-started Downloads the uniond release binary for aarch64 Linux architecture. Requires setting the UNIOND_VERSION environment variable. The output is saved to a file named 'uniond'. ```bash curl --output uniond --location https://github.com/unionlabs/union/releases/download/$UNIOND_VERSION/uniond-release-aarch64-linux ``` -------------------------------- ### Solidity MultiDEXSolver Example Implementation Source: https://docs.union.build/ucs/03 An example implementation of a Solidity solver contract named `MultiDEXSolver` that adheres to the `ISolver` interface. This contract demonstrates how to configure beneficiary addresses per path/channel/token and decode custom parameters for DEX trades, including slippage, route, and deadline. ```solidity contract MultiDEXSolver is ISolver { // Beneficiary addresses configured per path/channel/token // Using bytes to support addresses from different chains (not just 20-byte addresses) mapping(uint256 => mapping(uint32 => mapping(bytes => bytes))) public beneficiaries; struct DEXParams { uint256 maxSlippage; address[] routePath; uint256 deadline; } function solve( IBCPacket calldata packet, TokenOrderV2 calldata order, uint256 path, address caller, address relayer, bytes calldata relayerMsg, bool intent ) external override returns (bytes memory) { require(!intent, "only finalized txs are currently supported"); // Decode the SolverMetadata from the order SolverMetadata memory solverMeta = abi.decode(order.metadata, (SolverMetadata)); // Decode custom parameters from the solver metadata's metadata field DEXParams memory params = abi.decode(solverMeta.metadata, (DEXParams)); // Validate deadline require(block.timestamp <= params.deadline, "Order expired"); // The quoteToken from the order specifies what token to provide address quoteToken = address(bytes20(order.quoteToken)); address receiver = address(bytes20(order.receiver)); // Validate that we support this quote token require(isSupported(quoteToken), "Unsupported quote token"); // Perform the trade to obtain the quote tokens ``` -------------------------------- ### Initialize uniond Node Source: https://docs.union.build/infrastructure/node-operators/getting-started Initializes the uniond data and configuration directories using the provided moniker and chain ID. By default, it uses /User/{USER}/.uniond as the home directory. ```bash uniond init $MONIKER --chain-id $CHAIN_ID ``` -------------------------------- ### Example Batching Logic Visualization Source: https://docs.union.build/architecture/voyager/plugins/transaction-batch This example illustrates how messages are sorted by age within batches. It shows a nested array structure where each inner array represents a batch of messages, ordered chronologically. ```plaintext [[1, 2, 3], [4, 5, 6]] ``` -------------------------------- ### Create Union Validator with uniond CLI Source: https://docs.union.build/infrastructure/node-operators/getting-started This command creates a validator for the union network using the uniond CLI. It requires the path to the validator configuration file, a possession proof, and the key name. Optional flags like --node-id and --node can be used to specify node details if keys are on a different machine or if the RPC request needs to be sent to another node. Manual gas and fees must be provided. ```bash uniond tx union-staking create-union-validator /.unionvisor/validator.json $POSSESSION_PROOF \ --from $KEY_NAME \ --chain-id union-1 ``` -------------------------------- ### Example: Composing Writer Computations in TypeScript Source: https://docs.union.build/reference/unionlabs/sdk/typeclass/writerts Demonstrates how to compose Writer computations using `getMonad` and `composeK`. This example shows chaining functions that return Writer types, accumulating string outputs. ```typescript import * as Writer from "@unionlabs/sdk/typeclass/Writer" import * as StringInstances from "@effect/typeclass/data/String" import * as FlatMap from "@effect/typeclass/FlatMap" import { pipe } from "effect/Function" const composeK = pipe(StringInstances.Monoid, Writer.getMonad, FlatMap.composeK) const f = (s: string): [number, string] => [s.length, "[length]"] const g = (n: number): [boolean, string] => [n > 3, `[(>) 3 ${n}]`] const h = pipe(f, composeK(g)) assert.deepStrictEqual(h(""), [false, "[length][(>) 3 0]"]) assert.deepStrictEqual(h("abc"), [false, "[length][(>) 3 3]"]) assert.deepStrictEqual(h("abcd"), [true, "[length][(>) 3 4]"]) ``` -------------------------------- ### Pagination Guide Source: https://docs.union.build/integrations/api/graphql Explains how to use cursor-based pagination with `p_limit`, `p_sort_order`, and `p_comparison` parameters to navigate through results. ```APIDOC ## Pagination Guide This API uses cursor-based pagination. The following parameters control which data is returned: ### Parameters - **`p_limit`** (Int) - Optional - Maximum number of items to return. Default: `100`, Maximum: `100`. - **`p_sort_order`** (String) - Optional - Acts as a cursor for pagination. Use the `sort_order` value from the last item (for next page) or first item (for previous page) of the current result set. - **`p_comparison`** (String) - Optional - Controls pagination direction. Use `"lt"` to fetch the next page (results in descending order) or `"gt"` to fetch the previous page (results in ascending order). ### Notes - Each result includes a `sort_order` field used for pagination. Treat this as an opaque string. - Do not use external filtering or sorting options; pagination and ordering are controlled solely through these parameters. ### Example: Fetch first page (latest transfers) ```graphql query GetInitialTransfers { v2_transfers(args: { p_limit: 20 }) { sender_canonical receiver_canonical base_amount sort_order } } ``` ### Example: Fetch next page ```graphql query GetNextPage { v2_transfers(args: { p_limit: 20, p_sort_order: "cursor-from-last-item", p_comparison: "lt" }) { sender_canonical receiver_canonical base_amount sort_order } } ``` ### Example: Fetch previous page ```graphql query GetPreviousPage { v2_transfers(args: { p_limit: 20, p_sort_order: "cursor-from-first-item", p_comparison: "gt" }) { sender_canonical receiver_canonical base_amount sort_order } } ``` ``` -------------------------------- ### Create New Union Account with uniond Source: https://docs.union.build/joining-testnet/getting-tokens This command creates a new account and mnemonic phrase for the Union Testnet using the `uniond` binary. Ensure you securely store the generated mnemonic and note down the account address. ```bash uniond keys add $KEY_NAME ``` -------------------------------- ### Build Union Ceremony Web App with Nix Source: https://docs.union.build/ceremony Builds the Union Ceremony web application locally. This command utilizes Nix to fetch and compile the necessary components. Ensure you have Nix installed and configured. ```bash GIT_LFS_SKIP_SMUDGE=true nix build github:unionlabs/union/release/ceremony#ceremony ``` -------------------------------- ### Implement IZkgmable Interface (Solidity) Source: https://docs.union.build/ucs/03 Example implementation of the `IZkgmable` interface for contracts that need to receive cross-chain messages via the ZKGM protocol. It includes an `onZkgm` function to handle incoming messages, verify the sender, and emit an event. ```Solidity contract MyContract is IZkgmable { event MessageReceived( uint256 path, uint32 sourceChannelId, uint32 destinationChannelId, address sender, bytes message ); function onZkgm( uint256 path, uint32 sourceChannelId, uint32 destinationChannelId, bytes calldata sender, bytes calldata message ) external { // Verify caller is zkgm contract require(msg.sender == address(zkgm), "Only zkgm"); // Verify that the sourceChannelId and sender are authorized... // Process the cross-chain message emit MessageReceived( path, sourceChannelId, destinationChannelId, address(bytes20(sender)), message ); } } ``` -------------------------------- ### EVM Escrow Operation for Existing Wrapped Tokens Source: https://docs.union.build/ucs/03 Illustrates how to use an existing wrapped token to lock tokens on the source chain via an escrow operation. This example assumes the wrapped token was previously created using the initialize operation and focuses on constructing the TokenOrderV2 for the escrow transaction. ```solidity // Send more of the same token using the already initialized wrapped token TokenOrderV2 memory order = TokenOrderV2({ sender: abi.encodePacked(msg.sender), receiver: abi.encodePacked(recipient), baseToken: baseToken, // Same base token as before baseAmount: 500e18, kind: ZkgmLib.TOKEN_ORDER_KIND_ESCROW, metadata: hex"", // Empty for escrow quoteToken: abi.encodePacked(predictedWrappedTokenAddress), // Same wrapped token from initialize quoteAmount: 500e18 }); ``` -------------------------------- ### Initialize Cosmos Chain Environment Source: https://docs.union.build/connect/new-chain/cosmwasm Initializes a new Cosmos chain environment using the 'starsd' binary. This involves creating a home directory, initializing the chain with a specific ID and moniker, and adding a new key pair. The output includes an example address. ```bash mkdir ./starsd-home ./starsd init --chain-id elgafar-1 --home ./starsd-home $MONIKER ./starsd keys add $KEY_NAME --home ./starsd-home # this will give you your address: stars1qcvavxpxw3t8d9j7mwaeq9wgytkf5vwputv5x4 ``` -------------------------------- ### Configure State Pruning Options Source: https://docs.union.build/infrastructure/node-operators/node-configuration Sets the state pruning strategy for the node. Options include 'default', 'nothing' (archiving), 'everything', and 'custom' for manual specification. ```toml # default: the last 362880 states are kept, pruning at 10 block intervals # nothing: all historic states will be saved, nothing will be deleted (i.e. archiving node) # everything: 2 latest states will be kept; pruning at 10 block intervals. # custom: allow pruning options to be manually specified through 'pruning-keep-recent', and 'pruning-interval' pruning = "default" ``` -------------------------------- ### Channel Configuration JSON Example Source: https://docs.union.build/protocol/channels/overview This JSON object represents the configuration details for a channel, including its version, connection IDs, address, encoding, and transaction type. It is typically generated by the ICA module. ```json { "version": "ics27-1", "controller_connection_id": "connection-0", "host_connection_id": "connection-28", "address": "union1k8c7ks99ltx3gu4rejhm9jxj0cu4ukpg3s2dcqfwawr7d5k3xh0qzl9eag", "encoding": "proto3", "tx_type": "sdk_multi_msg" } ``` -------------------------------- ### Get Union Validator Address with uniond Source: https://docs.union.build/joining-testnet/getting-tokens This command retrieves the Union Testnet validator address associated with a given key name using the `uniond` binary. This is distinct from the user account address. ```bash uniond keys show $KEY_NAME --bech=val --address ``` -------------------------------- ### Pull Uniond Docker Image Source: https://docs.union.build/joining-testnet/obtaining-uniond Fetches the uniond Docker image from the GitHub Container Registry. Requires Docker to be installed and configured. The UNION_VERSION variable specifies the image tag. ```bash docker pull ghcr.io/unionlabs/uniond-release:$UNIOND_VERSION ``` -------------------------------- ### Adjust Consensus Timeouts for Block Production Source: https://docs.union.build/infrastructure/node-operators/node-configuration Modifies consensus timeouts to achieve target block times. Includes settings for proposal, prevote, precommit, and commit phases. ```toml # How long we wait for a proposal block before pre-voting nil timeout_propose = "3s" # How much timeout_propose increases with each round timeout_propose_delta = "500ms" # How long we wait after receiving +2/3 prevotes for “anything” (ie. not a single block or nil) timeout_prevote = "1s" # How much the timeout_prevote increases with each round timeout_prevote_delta = "500ms" # How long we wait after receiving +2/3 precommits for “anything” (ie. not a single block or nil) timeout_precommit = "1s" # How much the timeout_precommit increases with each round timeout_precommit_delta = "500ms" # How long we wait after committing a block, before starting on the new # height (this gives us a chance to receive some more precommits, even # though we already have +2/3). timeout_commit = "5s" ``` -------------------------------- ### EVM Basic Token Initialization with Custom Metadata Source: https://docs.union.build/ucs/03 Demonstrates how to initialize a new wrapped token with custom metadata on a destination chain using EVM. It involves encoding implementation and initializer data, creating TokenMetadata, predicting the wrapped token address, and constructing a TokenOrderV2 for the initialization operation. ```solidity // Default ZkgmERC20 address, don't change this unless you know what you are doing. bytes memory implementation = abi.encodePacked(0xAf739F34ddF951cBC24fdbBa4f76213688E13627); // Default ZkgmERC20.initialize (could be your implementation.initialize) // If you don't need any customization, you'll just update the token name, symbol and decimals. bytes memory initializer = abi.encodeCall( ZkgmERC20.initialize, ( // Default authority address, don't change this unless you know what you are doing. 0x40cdff51ae7487e0b4a4d6e5f86eb15fb7c1d9f4, // Default zkgm address, don't change this unless you know what you are doing. 0x5fbe74a283f7954f10aa04c2edf55578811aeb03, // Token name "My Token", // Token symbol "MTK", // Decimals 18 ) ); // Create metadata for the new wrapped token TokenMetadata memory metadata = TokenMetadata({ implementation: abi.encodePacked(0xAf739F34ddF951cBC24fdbBa4f76213688E13627), initializer: initializer }); // Predict the wrapped token address using the metadata // Use cast to call the counterparty zkgm instance: // cast call "predictWrappedTokenV2(uint256,uint32,bytes,tuple(bytes,bytes))" \ // 0 "(,)" \ // --rpc-url // Create the token order TokenOrderV2 memory order = TokenOrderV2({ sender: abi.encodePacked(msg.sender), receiver: abi.encodePacked(recipient), baseToken: baseToken, baseAmount: 1000e18, kind: ZkgmLib.TOKEN_ORDER_KIND_INITIALIZE, metadata: ZkgmLib.encodeTokenMetadata(metadata), // This is the predicted address we got quoteToken: abi.encodePacked(predictedWrappedTokenAddress), quoteAmount: 1000e18 }); // Create instruction Instruction memory instruction = Instruction({ version: ZkgmLib.INSTR_VERSION_2, opcode: ZkgmLib.OP_TOKEN_ORDER, operand: ZkgmLib.encodeTokenOrderV2(order) }); ``` -------------------------------- ### Get Union Account Address with uniond Source: https://docs.union.build/joining-testnet/getting-tokens This command retrieves the Union Testnet account address associated with a given key name using the `uniond` binary. This address is needed to receive testnet tokens. ```bash uniond keys show $KEY_NAME --address ``` -------------------------------- ### Create Solver Order with Multi-Step Execution (Solidity) Source: https://docs.union.build/ucs/03 Illustrates creating a solver order that involves multi-step execution. This allows for complex trading strategies by defining intermediate tokens, minimum outputs at each step, and custom data for each swap. The order uses TOKEN_ORDER_KIND_SOLVE. ```Solidity struct MultiStepParams { uint8 steps; address[] intermediateTokens; uint256[] minOutputs; bytes[] customData; } // Create a solver order with multi-step instructions SolverMetadata memory solverMeta = SolverMetadata({ solverAddress: abi.encodePacked(address(multiStepSolver)), metadata: abi.encode(MultiStepParams({ steps: 3, intermediateTokens: [USDC, WETH, TARGET_TOKEN], minOutputs: [1000e6, 0.5e18, 100e18], customData: [swapParams1, swapParams2, swapParams3] })) }); TokenOrderV2 memory order = TokenOrderV2({ sender: abi.encodePacked(msg.sender), receiver: abi.encodePacked(recipient), baseToken: abi.encodePacked(USDC), baseAmount: 1000e6, quoteToken: abi.encodePacked(TARGET_TOKEN), // Final token solver should provide quoteAmount: 100e18, // Minimum TARGET_TOKEN output expected kind: TOKEN_ORDER_KIND_SOLVE, metadata: abi.encode(solverMeta) }); ``` -------------------------------- ### Create Solver Order with Custom Parameters (Solidity) Source: https://docs.union.build/ucs/03 Demonstrates how to encode solver metadata with custom parameters for a solver order. This includes specifying solver address, slippage, deadline, preferred DEX, and minimum liquidity. The order is created with TOKEN_ORDER_KIND_SOLVE. ```Solidity // First, encode the solver metadata SolverMetadata memory solverMeta = SolverMetadata({ solverAddress: abi.encodePacked(address(mySolverContract)), metadata: abi.encode(CustomSolverParams({ maxSlippage: 300, // 3% deadline: block.timestamp + 3600, preferredDEX: "uniswap", minLiquidity: 100000e6 })) }); // Create the order with TOKEN_ORDER_KIND_SOLVE TokenOrderV2 memory order = TokenOrderV2({ sender: abi.encodePacked(msg.sender), receiver: abi.encodePacked(recipient), baseToken: abi.encodePacked(USDC), baseAmount: 10000e6, quoteToken: abi.encodePacked(address(uToken)), // U token that solver will mint quoteAmount: 9900e6, // Minimum U tokens expected kind: TOKEN_ORDER_KIND_SOLVE, // 0x03 metadata: abi.encode(solverMeta) }); ``` -------------------------------- ### Create Validator JSON for Unionvisor Docker Source: https://docs.union.build/infrastructure/node-operators/getting-started Creates a validator.json file within the .unionvisor directory, intended for use with Unionvisor Docker containers. This ensures the file is accessible by the Docker container. ```bash touch ~/.unionvisor/validator.json ``` -------------------------------- ### Build MPC Client for x86_64-linux with Nix Source: https://docs.union.build/ceremony Builds the MPC client for x86_64-linux systems using Nix. This command fetches the MPC client package and its dependencies. The output is a Docker image that can be loaded. ```bash GIT_LFS_SKIP_SMUDGE=true nix build github:unionlabs/union/bbfaa2f39d0183c2fd6c1d2505fad6c64ddb39e1#packages.x86_64-linux.mpc-client -L ``` -------------------------------- ### Declare Effect Program Source: https://docs.union.build/integrations/typescript/guided-tutorial/cosmos-union-sepolia Initializes an Effect program, which is the foundation for building the send funds example. It utilizes the Effect library for managing asynchronous operations and side effects. ```typescript import { Effect, Logger } from "effect" const program = Effect.gen(function*() {}) ``` -------------------------------- ### Build MPC Coordinator for x86_64-linux with Nix Source: https://docs.union.build/ceremony Builds the MPC coordinator service for x86_64-linux systems using Nix. This command fetches the MPC coordinator package and its dependencies. The output is a Docker image. ```bash GIT_LFS_SKIP_SMUDGE=true nix build github:unionlabs/union/bbfaa2f39d0183c2fd6c1d2505fad6c64ddb39e1#packages.x86_64-linux.mpc-coordinator -L ``` -------------------------------- ### Initialize Uniond Chain Configuration Source: https://docs.union.build/joining-testnet/obtaining-uniond Initializes the chain configuration and state folder using the uniond Docker image. It mounts the local '.union' directory into the container and uses the provided MONIKER for the node. Requires Docker and the previously created '.union' directory. ```bash docker run \ --user $(id -u):$(id -g) \ --volume ~/.union:/.union \ --volume /tmp:/tmp \ -it ghcr.io/unionlabs/uniond-release:$UNIOND_VERSION init $MONIKER \ --home /.union ``` -------------------------------- ### Recover Existing Union Account with uniond Source: https://docs.union.build/joining-testnet/getting-tokens This command recovers an existing Union Testnet account using a provided mnemonic phrase with the `uniond` binary. After recovery, note down the account address. ```bash uniond keys add $KEY_NAME --recover ``` -------------------------------- ### Execute zkgm Request and Get Response Source: https://docs.union.build/integrations/typescript/guided-tutorial/evm-holesky-sepolia Executes the prepared `ZkgmClientRequest` using `ZkgmClient.execute` and waits for the transaction receipt to complete. It logs the submission transaction hash and the final completion details. ```typescript import { ChannelId } from "@unionlabs/sdk/schema/channel" import * as ZkgmClient from "@unionlabs/sdk/ZkgmClient" import * as ZkgmClientRequest from "@unionlabs/sdk/ZkgmClientRequest" import * as ZkgmClientResponse from "@unionlabs/sdk/ZkgmClientResponse" import * as ZkgmIncomingMessage from "@unionlabs/sdk/ZkgmIncomingMessage" import { Effect, Logger } from "effect" const program = Effect.gen(function*() { // ... snip ... const zkgmClient = yield* ZkgmClient.ZkgmClient // NOTE: 1. switch chain is assumed // NOTE: 2. write in progress const response: ZkgmClientResponse.ZkgmClientResponse = yield* zkgmClient.execute(request) // NOTE: 3. write complete (with tx hash) yield* Effect.log("Submission Hash", response.txHash) const completion = yield* response.waitFor( ZkgmIncomingMessage.LifecycleEvent.$is("EvmTransactionReceiptComplete"), ) // NOTE: 4. tx complete yield* Effect.log("Completion", completion) }) ``` -------------------------------- ### Initialize Foundry Project for Asset Transfer Source: https://docs.union.build/connect/app/asset-transfer/solidity Initializes a new Foundry project to house the Solidity contract for asset transfer. This command creates a standard Foundry project structure. ```bash forge init ucs03-asset-transfer ``` -------------------------------- ### Monitor uniond Node Logs with journalctl Source: https://docs.union.build/infrastructure/node-operators/getting-started This command allows you to view the real-time logs of the uniond node using journalctl. The `-f` flag follows the log output, and `--user` specifies that you are viewing user-level logs. This is essential for monitoring the health and activity of your validator node. ```bash sudo journalctl -f --user uniond ``` -------------------------------- ### Create Uniond Directory Source: https://docs.union.build/joining-testnet/obtaining-uniond Creates a directory named '.union' in the user's home directory to store chain configuration and state. This is a prerequisite for initializing the chain. ```bash mkdir ~/.union ``` -------------------------------- ### Start Union Node in Detached Mode Source: https://docs.union.build/joining-testnet/unionvisor Command to start the Union node using Docker Compose in detached mode. This allows the node to run in the background. ```bash docker compose --file path/to/compose.yaml up --detach ``` -------------------------------- ### Execute Trade and Transfer Tokens (Solidity) Source: https://docs.union.build/ucs/03 This Solidity code snippet demonstrates finding the best trade route, executing a trade, ensuring minimum output, transferring quote tokens, and handling profit. It also retrieves beneficiary information based on configured paths and channels. ```solidity uint256 outputAmount = findBestRouteAndTrade( order.baseToken, order.baseAmount, quoteToken, order.quoteAmount, params ); // Ensure minimum output is met require(outputAmount >= order.quoteAmount, "Insufficient output"); // Transfer the quote tokens to the receiver IERC20(quoteToken).transfer(receiver, order.quoteAmount); // Keep any excess as profit uint256 profit = outputAmount - order.quoteAmount; if (profit > 0) { IERC20(quoteToken).transfer(relayer, profit); } // Return the market maker address that should receive the base tokens // This is typically configured per path/channel/token combination bytes memory beneficiary = beneficiaries[path][packet.destinationChannelId][order.baseToken]; require(beneficiary.length > 0, "No beneficiary configured"); return beneficiary; } } ``` -------------------------------- ### GET /tokenOrigin Source: https://docs.union.build/reference/unionlabs/sdk/ucs03ts Retrieves the origin of a token. ```APIDOC ## GET /tokenOrigin ### Description Retrieves the origin of a token. ### Method GET ### Endpoint /tokenOrigin ### Parameters #### Query Parameters - **tokenAddress** (address) - Required - The address of the token. ### Response #### Success Response (200) - **origin** (uint256) - The origin of the token. #### Response Example ```json { "origin": "12345" } ``` ``` -------------------------------- ### GET /stakes Source: https://docs.union.build/reference/unionlabs/sdk/ucs03ts Retrieves the stake information for a given index. ```APIDOC ## GET /stakes ### Description Retrieves the stake information for a given index. ### Method GET ### Endpoint /stakes ### Parameters #### Query Parameters - **index** (uint256) - Required - The index of the stake to retrieve. ### Response #### Success Response (200) - **state** (uint8) - The state of the stake (refer to ZkgmStakeState enum). - **channelId** (uint32) - The channel ID associated with the stake. - **validator** (bytes) - The validator associated with the stake. - **amount** (uint256) - The amount staked. - **unstakingCompletion** (uint256) - The timestamp when unstaking is completed. #### Response Example ```json { "state": 1, "channelId": 123, "validator": "0xabcd1234", "amount": "1000000000000000000", "unstakingCompletion": "1678886400" } ``` ``` -------------------------------- ### ZkgmClient - Constructors Source: https://docs.union.build/reference/unionlabs/sdk/zkgmclientts Provides methods for creating instances of ZkgmClient. ```APIDOC ## ZkgmClient Constructors ### make #### Description Creates a ZkgmClient instance with a provided function that handles requests, signals, and fibers. #### Signature ```typescript export declare const make: ( f: ( request: ClientRequest.ZkgmClientRequest, signal: AbortSignal, fiber: RuntimeFiber ) => Effect.Effect ) => ZkgmClient ``` ### makeWith #### Description Creates a ZkgmClient instance with preprocessing and postprocessing capabilities. #### Signature ```typescript export declare const makeWith: ( postprocess: ( request: Effect.Effect ) => Effect.Effect, preprocess: ZkgmClient.Preprocess ) => ZkgmClient.With ``` ``` -------------------------------- ### Execute Contract Transfer Source: https://docs.union.build/connect/app/asset-transfer/cosmwasm Executes a message on an instantiated contract. This example demonstrates sending UNO tokens. ```APIDOC ## POST /wasm/execute ### Description Executes a message on an instantiated contract. This example demonstrates sending UNO tokens. ### Method POST ### Endpoint /wasm/execute ### Parameters #### Path Parameters - **$CONTRACT_ADDRESS** (string) - Required - The address of the contract to execute. - **"$(jq -c '.' payload.json)"** (string) - Required - The JSON-encoded message to send to the contract. #### Query Parameters - **--from $KEY_NAME** (string) - Required - The key name to use for signing the transaction. - **--gas auto** (string) - Optional - Automatically set gas limit. - **--gas-adjustment 1.4** (number) - Optional - Gas adjustment factor. - **--chain-id union-testnet-9** (string) - Required - The chain ID of the network. - **--node $RPC_URL** (string) - Required - The RPC endpoint URL. - **--amount 2000000muno** (string) - Required - The amount of tokens to send with the transaction. ### Request Body #### payload.json ```json { "transfer": { "channel_id": 7, "receiver": "", "base_token": "muno", "base_amount": 1000000, "quote_token": "0xf2865969cf99a28bb77e25494fe12d5180fe0efd", "quote_amount": "1000000", "contract_address": "union19hspxmypfxsdsnxttma8rxvp7dtcmzhl9my0ee64avg358vlpawsdvucqa" } } ``` ### Request Example ```bash uniond \ tx wasm execute $CONTRACT_ADDRESS "$(jq -c '.' payload.json)" \ --from $KEY_NAME \ --gas auto \ --gas-adjustment 1.4 \ --chain-id union-testnet-9 \ --node $RPC_URL \ --amount 2000000muno ``` ### Response #### Success Response (200) - **TX_HASH** (string) - The hash of the transaction. #### Response Example ```json { "tx_hash": "..." } ``` ``` -------------------------------- ### Execute ZKGM Client Call with Cosmos SDK Source: https://docs.union.build/integrations/typescript/examples/cosmos/call This snippet demonstrates how to set up and execute a ZKGM client request using the @unionlabs/sdk-cosmos library. It involves configuring signers, chain registries, and the ZKGM client itself, then executing a 'Call' instruction and logging the transaction hash. Dependencies include @cosmjs/proto-signing, @cosmjs/stargate, and various modules from @unionlabs/sdk. ```typescript import { DirectSecp256k1HdWallet } from "@cosmjs/proto-signing" import { GasPrice } from "@cosmjs/stargate" import { Call, Ucs05, ZkgmClientRequest, ZkgmClientResponse } from "@unionlabs/sdk" import { Cosmos, CosmosZkgmClient } from "@unionlabs/sdk-cosmos" import { ChainRegistry } from "@unionlabs/sdk/ChainRegistry" import { UniversalChainId } from "@unionlabs/sdk/schema/chain" import { ChannelId } from "@unionlabs/sdk/schema/channel" import { Effect, Logger } from "effect" const signer = await DirectSecp256k1HdWallet.fromMnemonic( process.env.MEMO ?? "memo memo memo", { prefix: "bbn" }, ) const program = Effect.gen(function*() { const source = yield* ChainRegistry.byUniversalId( UniversalChainId.make("babylon.bbn-1"), ) const destination = yield* ChainRegistry.byUniversalId( UniversalChainId.make("ethereum.1"), ) const call = Call.make({ sender: Ucs05.CosmosDisplay.make({ address: "bbn122ny3mep2l7nhtafpwav2y9e5jrslhekrn8frh", }), eureka: false, contractAddress: Ucs05.EvmDisplay.make({ address: "0x921e5b5091f431f84f14423ec487783a853bc4b0", }), contractCalldata: "0xDEADBEEF", }) const request = ZkgmClientRequest.make({ source, destination, channelId: ChannelId.make(3), ucs03Address: "bbn1336jj8ertl8h7rdvnz4dh5rqahd09cy0x43guhsxx6xyrztx292q77945h", instruction: call, }) const client = yield* CosmosZkgmClient.make.pipe( Effect.provide(Cosmos.SigningClient.Live( "bbn122ny3mep2l7nhtafpwav2y9e5jrslhekrn8frh", "https://rpc.bbn-1.babylon.chain.kitchen", signer, { gasPrice: GasPrice.fromString("0.0007ubbn") }, )), Effect.provide(Cosmos.Client.Live("https://rpc.bbn-1.babylon.chain.kitchen")), ) const response: ZkgmClientResponse.ZkgmClientResponse = yield* client.execute(request) yield* Effect.log("TX Hash:", response.txHash) }).pipe( Effect.provide(ChainRegistry.Default), Effect.provide(Logger.replace(Logger.defaultLogger, Logger.prettyLoggerDefault)), ) Effect.runPromise(program) .then(console.log) .catch(console.error) ``` -------------------------------- ### Get IBC Address (Solidity) Source: https://docs.union.build/reference/unionlabs/sdk/ucs03ts Retrieves the IBC address associated with the contract. This is a view function. ```Solidity function ibcAddress() public view returns (address) { // ... implementation details ... } ``` -------------------------------- ### Get Chain By ID Source: https://docs.union.build/reference/unionlabs/sdk/chainregistryts Retrieves chain information by its unique identifier. This endpoint is part of the Chain Registry service. ```APIDOC ## GET /websites/union_build/chainregistry/getChainById ### Description Retrieves chain information by its unique identifier. ### Method GET ### Endpoint /websites/union_build/chainregistry/getChainById ### Parameters #### Query Parameters - **id** (UniversalChainId) - Required - The unique identifier of the chain. ### Response #### Success Response (200) - **Chain** (object) - The chain object containing detailed information. - **ChainRegistryError** (object) - An error object if the chain is not found or an issue occurs. #### Response Example { "chain": { "chainId": "1", "name": "Cosmos Hub", "rpcUrl": "https://rpc.cosmos.network:443" } } ``` -------------------------------- ### Common GraphQL Queries Source: https://docs.union.build/integrations/api/graphql Examples of common and useful GraphQL queries for retrieving transfer data and statistics. ```APIDOC ## Common GraphQL Queries ### Description This section provides examples of frequently used GraphQL queries, including fetching recent transfers, transfers by address, and aggregate statistics. Caching is recommended using the `@cached(ttl: ${time_in_seconds})` directive. ### Queries #### Latest 10 Transfers Retrieves the 10 most recent transfers. ```graphql query GetLatest10Transfers @cached(ttl: 1) { v2_transfers(args: { p_limit: 10 }) { sender_canonical receiver_canonical base_amount base_token_meta { denom representations { name symbol decimals } } } } ``` #### Latest 10 Transfers for a Specific Address Retrieves the 10 most recent transfers involving a specific sender or receiver address. ```graphql query GetLatest10UserTransfers @cached(ttl: 1) { v2_transfers(args: { p_limit: 10, p_addresses_canonical: [ "0x3c5daaa3c96ab8fe4cfc2fb6d76193fe959a9f82" ] }) { sender_canonical receiver_canonical base_amount base_token_meta { denom representations { name symbol decimals } } source_universal_chain_id destination_universal_chain_id } } ``` #### Aggregate Transfer and Packet Statistics Retrieves aggregate counts for transfers and packets. ```graphql query { v2_stats_count { name value } } ``` ### Concepts - **source**: The chain or rollup where the packet is sent from. - **destination**: The chain or roll-up that receives the packet. - **sender**: The contract or EOA that made the transfer. - **receiver**: The contract or EOA that received the transfer. - **universal_chain_id**: The UCS-04 chain reference. ### Caching Use the `@cached(ttl: ${time_in_seconds})` directive to improve performance. The cache key is computed by hashing the GraphQL query, operation name, and variables. ``` -------------------------------- ### Initialize Cosmos Chain and Create Key (Starsd) Source: https://docs.union.build/connect/new-chain Initializes a new Cosmos chain home directory and creates a new keypair for a validator or user. It uses the 'starsd' binary and specifies a chain ID and home directory. ```bash mkdir ./starsd-home ./starsd init --chain-id elgafar-1 --home ./starsd-home cor-systems ./starsd keys add cor-systems --home ./starsd-home # this will give you your address: stars1qcvavxpxw3t8d9j7mwaeq9wgytkf5vwputv5x4 ``` -------------------------------- ### Aptos Module Source: https://docs.union.build/reference/unionlabs/sdk/indexts This module handles Aptos chain functionality. ```APIDOC ## Aptos Module ### Description This module handles Aptos chain functionality. ### Method N/A (Module Export) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A ### Source `src/index.ts:57` ``` -------------------------------- ### Solver Use Cases Source: https://docs.union.build/ucs/03 Outlines various use cases for the solver interface, including multi-hop swaps, liquidity aggregation, arbitrage, and custom logic implementation. ```APIDOC ## Solver Use Cases ### Description Highlights the diverse applications and benefits of using the solver interface for advanced trading strategies and cross-chain operations. ### Method N/A (Use Case Listing) ### Endpoint N/A (Use Case Listing) ### Parameters N/A (Use Case Listing) ### Request Example N/A (Use Case Listing) ### Response N/A (Use Case Listing) ### Use Cases * **Multi-hop Swaps**: Solvers can execute complex swap routes across multiple DEXs. * **Liquidity Aggregation**: Combine liquidity from multiple sources for better rates. * **Arbitrage**: Execute arbitrage opportunities while fulfilling user orders. * **Custom Logic**: Implement protocol-specific market making strategies. * **Cross-chain Coordination**: Coordinate actions across multiple chains. ``` -------------------------------- ### Get Metadata Image of Address (Solidity) Source: https://docs.union.build/reference/unionlabs/sdk/ucs03ts Retrieves the metadata image (bytes32) associated with a given address. This is a view function. ```Solidity function metadataImageOf(address _addr) public view returns (bytes32) { // ... implementation details ... } ``` -------------------------------- ### Get authority Address (Solidity) Source: https://docs.union.build/reference/unionlabs/sdk/ucs03ts Retrieves the address of the contract's authority. This is a view function and does not alter the blockchain state. ```solidity function authority() public view returns (address) ``` -------------------------------- ### Create and Navigate CosmWasm Project Directory Source: https://docs.union.build/connect/app/asset-transfer/cosmwasm Initializes a new Rust library project for a CosmWasm contract using Cargo and changes the current directory into the newly created project folder. This sets up the basic project structure. ```bash cargo new --lib example-ucs03-cosmwasm cd example-ucs03-cosmwasm ``` -------------------------------- ### Get STAKE_IMPL Address (Solidity) Source: https://docs.union.build/reference/unionlabs/sdk/ucs03ts Retrieves the address of the STAKE implementation contract. This is a view function and does not alter the blockchain state. ```solidity function STAKE_IMPL() public view returns (address) ``` -------------------------------- ### Get SEND_IMPL Address (Solidity) Source: https://docs.union.build/reference/unionlabs/sdk/ucs03ts Retrieves the address of the SEND implementation contract. This is a view function and does not alter the blockchain state. ```solidity function SEND_IMPL() public view returns (address) ``` -------------------------------- ### Get FAO_IMPL Address (Solidity) Source: https://docs.union.build/reference/unionlabs/sdk/ucs03ts Retrieves the address of the FAO implementation contract. This is a view function and does not alter the blockchain state. ```solidity function FAO_IMPL() public view returns (address) ```