### Submit Neutron blockchain transactions using neutrond CLI Source: https://context7.com/neutron-org/neutron/llms.txt Demonstrates how to start a Neutron node and perform common blockchain operations such as registering interchain accounts, creating token denominations, minting tokens, providing liquidity, placing orders, executing swaps, and registering interchain queries. Requires the neutrond binary and a configured wallet. Outputs transaction hashes or error messages from the CLI. ```bash # Start the Neutron node neutrond start --home ~/.neutrond # Register an interchain account neutrond tx interchaintxs register \ --connection-id connection-0 \ --interchain-account-id my-ica \ --ordering ORDER_UNORDERED \ --from my-wallet \ --chain-id neutron-1 \ --gas auto \ --fees 5000untrn # Create a new token denom neutrond tx tokenfactory create-denom mytoken \ --from my-wallet \ --chain-id neutron-1 \ --fees 10000000untrn # Mint tokens neutrond tx tokenfactory mint 1000000factory/neutron1.../mytoken \ --from my-wallet \ --chain-id neutron-1 \ --fees 5000untrn # Deposit liquidity to DEX neutrond tx dex deposit untrn uatom \ --amounts-a 1000000 \ --amounts-b 500000 \ --tick-indexes-a-to-b 0 \ --fees 1 \ --from my-wallet \ --chain-id neutron-1 # Place limit order neutrond tx dex place-limit-order \ --token-in untrn \ --token-out uatom \ --tick-index 100 \ --amount-in 100000 \ --order-type GOOD_TIL_CANCELLED \ --from my-wallet \ --chain-id neutron-1 # Execute multi-hop swap neutrond tx dex multi-hop-swap \ --routes "untrn,uatom,uosmo" \ --amount-in 50000 \ --exit-limit-price 1.05 \ --pick-best-route \ --from my-wallet \ --chain-id neutron-1 # Register interchain query neutrond tx interchainqueries register-kv-query \ --connection-id connection-0 \ --keys "bank:balances/cosmos1..." \ --update-period 100 \ --from my-wallet \ --chain-id neutron-1 ``` -------------------------------- ### CosmWasm Custom Bindings with Rust Source: https://context7.com/neutron-org/neutron/llms.txt These Rust examples showcase how to leverage Neutron's custom CosmWasm bindings to perform advanced operations directly from smart contracts. Functionalities include submitting interchain transactions, creating and minting tokens via the Token Factory module, and registering interchain queries. ```rust use cosmwasm_std::{DepsMut, Env, MessageInfo, Response, StdResult, CosmosMsg}; use neutron_sdk::bindings::msg::NeutronMsg; use neutron_sdk::bindings::types::ProtobufAny; // Submit interchain transaction from contract pub fn submit_interchain_tx( deps: DepsMut, env: Env, info: MessageInfo, connection_id: String, msgs: Vec, ) -> StdResult> { let submit_msg = NeutronMsg::SubmitTx { connection_id, interchain_account_id: "contract_ica".to_string(), msgs, memo: "Contract initiated tx".to_string(), timeout: 100, fee: Fee { recv_fee: vec![], ack_fee: vec![Coin { denom: "untrn".to_string(), amount: "1000".to_string() }], timeout_fee: vec![], }, }; Ok(Response::new() .add_message(submit_msg) .add_attribute("action", "submit_interchain_tx")) } // Create and mint tokens from contract pub fn create_token_from_contract( deps: DepsMut, _env: Env, info: MessageInfo, ) -> StdResult> { // Create denom let create_denom_msg = NeutronMsg::CreateDenom { subdenom: "contract_token".to_string(), }; // Mint tokens let mint_msg = NeutronMsg::MintTokens { denom: format!("factory/{}/contract_token", info.sender), amount: "1000000".to_string(), mint_to_address: info.sender.to_string(), }; Ok(Response::new() .add_message(create_denom_msg) .add_message(mint_msg) .add_attribute("action", "create_and_mint")) } // Register interchain query pub fn register_icq( deps: DepsMut, _env: Env, _info: MessageInfo, connection_id: String, keys: Vec, ) -> StdResult> { let icq_msg = NeutronMsg::RegisterInterchainQuery { query_type: "kv".to_string(), keys, transactions_filter: "".to_string(), connection_id, update_period: 100, }; Ok(Response::new() .add_message(icq_msg) .add_attribute("action", "register_icq")) } ``` -------------------------------- ### Register and Process Interchain Queries in Go Source: https://context7.com/neutron-org/neutron/llms.txt This Go example shows how to register an interchain query using Neutron's interchainqueries module to fetch data like account balances from remote chains. It depends on Cosmos SDK types and Neutron's v8 x/interchainqueries keeper. The code registers a KV query and processes results, limited to querying specified keys with periodic updates. ```go package main import ( "context" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/neutron-org/neutron/v8/x/interchainqueries/keeper" "github.com/neutron-org/neutron/v8/x/interchainqueries/types" ) func RegisterBalanceQuery(ctx context.Context, k *keeper.Keeper) error { // Define KV keys to query from remote chain keys := []*types.KVKey{ { Path: "bank", Key: []byte("balances/cosmos1..."), }, } // Register the interchain query msg := &types.MsgRegisterInterchainQuery{ QueryType: "kv", Keys: keys, ConnectionId: "connection-0", UpdatePeriod: 100, // Update every 100 blocks } response, err := k.RegisterInterchainQuery(ctx, msg) if err != nil { return err } queryId := response.Id // Retrieve query result result, found := k.GetQueryResult(sdk.UnwrapSDKContext(ctx), queryId) if !found { return types.ErrQueryResultNotFound } // Process the returned data for _, kvResult := range result.KvResults { println("Key:", string(kvResult.Key)) println("Value:", string(kvResult.Value)) } return nil } ``` -------------------------------- ### Register and Submit Interchain Transactions in Go Source: https://context7.com/neutron-org/neutron/llms.txt This Go function demonstrates registering an Interchain Account (ICA) and submitting cross-chain transactions using Neutron's interchaintxs module. It requires the Cosmos SDK and Neutron's keeper types. The example handles registration and submission, returning a sequence ID for tracking, with dependencies on Neutron's v8 x/interchaintxs package. ```go package main import ( "context" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/neutron-org/neutron/v8/x/interchaintxs/keeper" "github.com/neutron-org/neutron/v8/x/interchaintxs/types" ) func RegisterAndSubmitInterchainTx(ctx context.Context, k *keeper.Keeper) error { // Register an interchain account registerMsg := &types.MsgRegisterInterchainAccount{ FromAddress: "neutron1...", ConnectionId: "connection-0", InterchainAccountId: "my-ica-account", RegisterFee: sdk.NewCoins(sdk.NewCoin("untrn", sdk.NewInt(1000000))), } // Execute registration _, err := k.RegisterInterchainAccount(ctx, registerMsg) if err != nil { return err } // Submit a transaction to remote chain submitMsg := &types.MsgSubmitTx{ FromAddress: "neutron1...", InterchainAccountId: "my-ica-account", ConnectionId: "connection-0", Msgs: []sdk.Msg{/* remote chain messages */}, Memo: "Cross-chain transfer", Timeout: 100, } response, err := k.SubmitTx(ctx, submitMsg) if err != nil { return err } // Response contains sequence number for tracking println("Submitted with sequence:", response.SequenceId) return nil } ``` -------------------------------- ### GET /osmosis/tokenfactory/v1beta1/denoms_from_creator/{creator} Source: https://context7.com/neutron-org/neutron/llms.txt This endpoint retrieves a list of token factory denoms created by a specific address. It integrates with the token factory module for token management. ```APIDOC ## GET /osmosis/tokenfactory/v1beta1/denoms_from_creator/{creator} ### Description Fetch all token factory denominations created by the specified creator address. This is used to list custom tokens issued via the factory. ### Method GET ### Endpoint /osmosis/tokenfactory/v1beta1/denoms_from_creator/{creator} ### Parameters #### Path Parameters - **creator** (string) - Required - The address of the token creator. #### Query Parameters N/A #### Request Body N/A ### Request Example curl -X GET "http://localhost:1317/osmosis/tokenfactory/v1beta1/denoms_from_creator/neutron1..." -H "accept: application/json" ### Response #### Success Response (200) - **denoms** (array of strings) - A list of denom identifiers created by the specified address. #### Response Example { "denoms": [ "factory/neutron1.../mytoken", "factory/neutron1.../anothertoken" ] } ``` -------------------------------- ### GET /RegisteredInterchainQueries Source: https://github.com/neutron-org/neutron/blob/main/wasmbinding/README.md This endpoint retrieves all registered interchain queries. ```APIDOC ## GET /RegisteredInterchainQueries ### Description Retrieves all set of registered interchain queries. ### Method GET ### Endpoint /RegisteredInterchainQueries ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Request Example { } ### Response #### Success Response (200) - **queries** (array) - An array of registered interchain queries. ``` -------------------------------- ### Neutron REST API Endpoints Source: https://context7.com/neutron-org/neutron/llms.txt This section details how to interact with the Neutron blockchain's state and submit transactions using its REST API. Examples include querying DEX pool information, retrieving interchain account addresses, listing token factory denoms, and fetching registered interchain query details. ```bash # Query DEX pool information curl -X GET "http://localhost:1317/neutron/dex/pool/untrn/uatom/1/0" \ -H "accept: application/json" # Response: # { # "pool": { # "id": "...", # "lower_tick0": { "reserves_maker_denom": "1000000", "reserves_taker_denom": "500000" }, # "upper_tick1": { "reserves_maker_denom": "800000", "reserves_taker_denom": "600000" } # } # } # Query interchain account address curl -X GET "http://localhost:1317/neutron/interchaintxs/interchain_account/connection-0/neutron1.../my-ica" \ -H "accept: application/json" # Response: # { # "interchain_account_address": "cosmos1...", # "channel_id": "channel-0" # } # Query token factory denoms by creator curl -X GET "http://localhost:1317/osmosis/tokenfactory/v1beta1/denoms_from_creator/neutron1..." \ -H "accept: application/json" # Response: # { # "denoms": [ # "factory/neutron1.../mytoken", # "factory/neutron1.../anothertoken" # ] # } # Query interchain query results curl -X GET "http://localhost:1317/neutron/interchainqueries/registered_queries" \ -H "accept: application/json" # Response: # { # ``` -------------------------------- ### GET /RegisteredInterchainQuery Source: https://github.com/neutron-org/neutron/blob/main/wasmbinding/README.md This endpoint retrieves a registered interchain query with the specified query_id. ```APIDOC ## GET /RegisteredInterchainQuery ### Description Retrieves a registered interchain query with specified query_id. ### Method GET ### Endpoint /RegisteredInterchainQuery ### Parameters #### Path Parameters - **query_id** (string) - Required - The ID of the interchain query. #### Query Parameters - None #### Request Body - None ### Request Example { "query_id": "example_query_id" } ### Response #### Success Response (200) - **query** (object) - The registered interchain query. ``` -------------------------------- ### GET /neutron/interchainqueries/registered_queries Source: https://context7.com/neutron-org/neutron/llms.txt This endpoint returns a list of registered interchain queries. It helps monitor active queries for interchain data retrieval. ```APIDOC ## GET /neutron/interchainqueries/registered_queries ### Description Retrieve information about all registered interchain queries, useful for tracking query statuses and configurations. ### Method GET ### Endpoint /neutron/interchainqueries/registered_queries ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example curl -X GET "http://localhost:1317/neutron/interchainqueries/registered_queries" -H "accept: application/json" ### Response #### Success Response (200) - **registered_queries** (array) - An array of registered query objects (details not fully specified in input). #### Response Example { } ``` -------------------------------- ### GET /InterchainQueryResult Source: https://github.com/neutron-org/neutron/blob/main/wasmbinding/README.md This endpoint retrieves the result of a registered interchain query. It requires the query_id as a parameter. ```APIDOC ## GET /InterchainQueryResult ### Description Retrieves the result of a registered interchain query by query_id. ### Method GET ### Endpoint /InterchainQueryResult ### Parameters #### Path Parameters - **query_id** (string) - Required - The ID of the interchain query. #### Query Parameters - None #### Request Body - None ### Request Example { "query_id": "example_query_id" } ### Response #### Success Response (200) - **result** (string) - The result of the interchain query. ``` -------------------------------- ### GET /InterchainAccountAddress Source: https://github.com/neutron-org/neutron/blob/main/wasmbinding/README.md This endpoint retrieves the interchain account address. It requires owner_id and connection_id as parameters. ```APIDOC ## GET /InterchainAccountAddress ### Description Retrieves the interchain account address by owner_id and connection_id. ### Method GET ### Endpoint /InterchainAccountAddress ### Parameters #### Path Parameters - **owner_id** (string) - Required - The ID of the owner. - **connection_id** (string) - Required - The ID of the connection. #### Query Parameters - None #### Request Body - None ### Request Example { "owner_id": "example_owner_id", "connection_id": "example_connection_id" } ### Response #### Success Response (200) - **address** (string) - The interchain account address. ``` -------------------------------- ### GET /neutron/dex/pool/{maker_denom}/{taker_denom}/{pool_id}/{tranche_key} Source: https://context7.com/neutron-org/neutron/llms.txt This endpoint retrieves information about a specific DEX pool, including reserves for lower and upper ticks. It is used to query pool details for trading operations. ```APIDOC ## GET /neutron/dex/pool/{maker_denom}/{taker_denom}/{pool_id}/{tranche_key} ### Description Retrieve detailed information about a Decentralized Exchange (DEX) pool, including reserve amounts for the specified maker and taker denoms, pool ID, and tranche key. ### Method GET ### Endpoint /neutron/dex/pool/{maker_denom}/{taker_denom}/{pool_id}/{tranche_key} ### Parameters #### Path Parameters - **maker_denom** (string) - Required - The denomination of the maker asset in the pool. - **taker_denom** (string) - Required - The denomination of the taker asset in the pool. - **pool_id** (integer) - Required - The unique identifier of the pool. - **tranche_key** (integer) - Required - The tranche key for the pool query. #### Query Parameters N/A #### Request Body N/A ### Request Example curl -X GET "http://localhost:1317/neutron/dex/pool/untrn/uatom/1/0" -H "accept: application/json" ### Response #### Success Response (200) - **pool** (object) - An object containing pool details. - **id** (string) - The pool identifier. - **lower_tick0** (object) - Reserves for the lower tick. - **reserves_maker_denom** (string) - Amount of maker denom reserves. - **reserves_taker_denom** (string) - Amount of taker denom reserves. - **upper_tick1** (object) - Reserves for the upper tick. - **reserves_maker_denom** (string) - Amount of maker denom reserves. - **reserves_taker_denom** (string) - Amount of taker denom reserves. #### Response Example { "pool": { "id": "...", "lower_tick0": { "reserves_maker_denom": "1000000", "reserves_taker_denom": "500000" }, "upper_tick1": { "reserves_maker_denom": "800000", "reserves_taker_denom": "600000" } } } ``` -------------------------------- ### GET /neutron/interchaintxs/interchain_account/{connection_id}/{owner}/{interchain_account_id} Source: https://context7.com/neutron-org/neutron/llms.txt This endpoint queries the Interchain Account (ICA) address associated with a given connection, owner, and ICA ID. It is essential for managing interchain transactions. ```APIDOC ## GET /neutron/interchaintxs/interchain_account/{connection_id}/{owner}/{interchain_account_id} ### Description Query the address of an interchain account linked to a specific connection, owner address, and interchain account ID, along with the associated channel ID. ### Method GET ### Endpoint /neutron/interchaintxs/interchain_account/{connection_id}/{owner}/{interchain_account_id} ### Parameters #### Path Parameters - **connection_id** (string) - Required - The ID of the IBC connection. - **owner** (string) - Required - The address of the owner of the interchain account. - **interchain_account_id** (string) - Required - The unique identifier for the interchain account. #### Query Parameters N/A #### Request Body N/A ### Request Example curl -X GET "http://localhost:1317/neutron/interchaintxs/interchain_account/connection-0/neutron1.../my-ica" -H "accept: application/json" ### Response #### Success Response (200) - **interchain_account_address** (string) - The address of the interchain account. - **channel_id** (string) - The IBC channel ID associated with the account. #### Response Example { "interchain_account_address": "cosmos1...", "channel_id": "channel-0" } ``` -------------------------------- ### Build and deploy CosmWasm smart contracts on Neutron via CLI Source: https://context7.com/neutron-org/neutron/llms.txt Shows the full workflow to clone a contract repository, compile a Rust-based CosmWasm contract to WebAssembly, optimize the binary with the official Docker optimizer, and deploy it to the Neutron chain. After storing the wasm, the snippet illustrates instantiation, execution, and state querying using neutrond commands. Requires Docker, Cargo, and a funded wallet. ```bash # Clone contract repository git clone https://github.com/neutron-org/neutron-contracts cd neutron-contracts/contracts/my-contract # Build the contract cargo build --release --target wasm32-unknown-unknown # Optimize the wasm binary docker run --rm -v "$(pwd)":/code \ --mount type=volume,source="$(basename "$(pwd)")_cache",target=/code/target \ --mount type=volume,source=registry_cache,target=/usr/local/cargo/registry \ cosmwasm/rust-optimizer:0.15.0 # Store the contract on-chain neutrond tx wasm store artifacts/my_contract.wasm \ --from my-wallet \ --chain-id neutron-1 \ --gas auto \ --gas-adjustment 1.3 \ --fees 50000untrn # Instantiate the contract INIT_MSG='{"owner":"neutron1...","config":{}}' neutrond tx wasm instantiate "$INIT_MSG" \ --from my-wallet \ --label "My Contract v1.0" \ --admin neutron1... \ --chain-id neutron-1 \ --fees 10000untrn # Execute contract method EXECUTE_MSG='{"submit_interchain_tx":{"connection_id":"connection-0","msgs":[]}}' neutrond tx wasm execute "$EXECUTE_MSG" \ --from my-wallet \ --chain-id neutron-1 \ --amount 1000000untrn \ --fees 5000untrn # Query contract state QUERY_MSG='{"get_state":{}}' neutrond query wasm contract-state smart "$QUERY_MSG" ``` -------------------------------- ### Initialize Swagger UI with JavaScript Source: https://github.com/neutron-org/neutron/blob/main/docs/static/index.html This JavaScript snippet initializes Swagger UI on window load, configuring it to load API specs from swagger.yaml. It includes presets like API presets and standalone layout, with plugins for downloading URLs. Dependencies include SwaggerUIBundle; inputs are configuration options, outputs render the UI in the DOM element with ID swagger-ui. Limitations may include browser compatibility for deep linking. ```javascript window.onload = function() { // Begin Swagger UI call region const ui = SwaggerUIBundle({ url: "./swagger.yaml", dom_id: '#swagger-ui', deepLinking: true, queryConfigEnabled: false, presets: [ SwaggerUIBundle.presets.apis, SwaggerUIStandalonePreset ], plugins: [ SwaggerUIBundle.plugins.DownloadUrl ], layout: "StandaloneLayout" }); // End Swagger UI call region window.ui = ui; }; ``` -------------------------------- ### Create, Mint, and Manage Custom Tokens with Neutron Token Factory Source: https://context7.com/neutron-org/neutron/llms.txt This Go function demonstrates how to create a new custom token denomination, set its metadata, mint initial tokens, and optionally change the administrator using the Neutron Token Factory module. It requires context, the keeper instance, and the creator's address. ```go package main import ( "context" sdk "github.com/cosmos/cosmos-sdk/types" banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" "github.com/neutron-org/neutron/v8/x/tokenfactory/keeper" "github.com/neutron-org/neutron/v8/x/tokenfactory/types" ) func CreateAndMintToken(ctx context.Context, k *keeper.Keeper, creator sdk.AccAddress) error { // Create a new denom subdenom := "mytoken" createMsg := types.NewMsgCreateDenom(creator.String(), subdenom) response, err := k.CreateDenom(ctx, createMsg) if err != nil { return err } newDenom := response.NewTokenDenom // Format: factory/{creator_address}/{subdenom} // Set metadata for the token metadata := banktypes.Metadata{ Description: "My Custom Token", DenomUnits: []*banktypes.DenomUnit{ {Denom: newDenom, Exponent: 0}, {Denom: "mytoken", Exponent: 6}, }, Base: newDenom, Display: "mytoken", Name: "My Token", Symbol: "MTK", } setMetadataMsg := types.NewMsgSetDenomMetadata(creator.String(), metadata) _, err = k.SetDenomMetadata(ctx, setMetadataMsg) if err != nil { return err } // Mint tokens mintAmount := sdk.NewCoin(newDenom, sdk.NewInt(1000000000)) mintMsg := types.NewMsgMint(creator.String(), mintAmount) _, err = k.Mint(ctx, mintMsg) if err != nil { return err } // Change admin (optional) newAdmin := "neutron1newadmin..." changeAdminMsg := types.NewMsgChangeAdmin(creator.String(), newDenom, newAdmin) _, err = k.ChangeAdmin(ctx, changeAdminMsg) return err } ``` -------------------------------- ### Perform DEX Operations: Deposit, Limit Orders, and Swaps Source: https://context7.com/neutron-org/neutron/llms.txt This Go function illustrates various Decentralized Exchange (DEX) operations on Neutron, including depositing liquidity into a pool, placing a limit order (Good 'Til Cancelled), executing a multi-hop swap with price protection, and withdrawing a filled limit order. It requires context, the DEX keeper, and the trader's address. ```go package main import ( "context" "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/neutron-org/neutron/v8/x/dex/keeper" "github.com/neutron-org/neutron/v8/x/dex/types" ) func DEXOperations(ctx context.Context, k keeper.Keeper, trader sdk.AccAddress) error { // Deposit liquidity into pool depositMsg := &types.MsgDeposit{ Creator: trader.String(), Receiver: trader.String(), TokenA: "untrn", TokenB: "uatom", AmountsA: []math.Int{math.NewInt(1000000)}, AmountsB: []math.Int{math.NewInt(500000)}, TickIndexesAToB: []int64{0}, Fees: []uint64{1}, // 0.01% fee tier Options: []*types.DepositOptions{ { DisableAutoswap: false, FailTxOnBel: true, }, }, } depositResp, err := k.Deposit(ctx, depositMsg) if err != nil { return err } println("Shares issued:", depositResp.SharesIssued) // Place a limit order limitOrderMsg := &types.MsgPlaceLimitOrder{ Creator: trader.String(), Receiver: trader.String(), TokenIn: "untrn", TokenOut: "uatom", TickIndexInToOut: 100, AmountIn: math.NewInt(100000), OrderType: types.LimitOrderType_GOOD_TIL_CANCELLED, MaxAmountOut: nil, // No limit } orderResp, err := k.PlaceLimitOrder(ctx, limitOrderMsg) if err != nil { return err } trancheKey := orderResp.TrancheKey // Execute multi-hop swap swapMsg := &types.MsgMultiHopSwap{ Creator: trader.String(), Receiver: trader.String(), Routes: []*types.MultiHopRoute{ { Hops: []string{"untrn", "uatom", "uosmo"}, }, }, AmountIn: math.NewInt(50000), ExitLimitPrice: math.LegacyMustNewDecFromStr("1.05"), PickBestRoute: true, } swapResp, err := k.MultiHopSwap(ctx, swapMsg) if err != nil { return err } println("Amount out:", swapResp.Dust[0].Amount) // Withdraw filled limit order withdrawMsg := &types.MsgWithdrawFilledLimitOrder{ Creator: trader.String(), TrancheKey: trancheKey, } _, err = k.WithdrawFilledLimitOrder(ctx, withdrawMsg) return err } ``` -------------------------------- ### Apply Box-Sizing CSS for Swagger UI Source: https://github.com/neutron-org/neutron/blob/main/docs/static/index.html This CSS snippet applies box-sizing rules to ensure consistent sizing across elements, including HTML, body, and all pseudo-elements. It uses border-box for inheritance and sets overflow handling for the page body with a light background color. No dependencies are required as it's standard CSS; inputs are via HTML classes, outputs affect rendering. ```css html { box-sizing: border-box; overflow: -moz-scrollbars-vertical; overflow-y: scroll; } *, *:before, *:after { box-sizing: inherit; } body { margin:0; background: #fafafa; } ``` -------------------------------- ### POST /RegisterInterchainQuery Source: https://github.com/neutron-org/neutron/blob/main/wasmbinding/README.md This endpoint registers an interchain query. ```APIDOC ## POST /RegisterInterchainQuery ### Description Registers an interchain query. ### Method POST ### Endpoint /RegisterInterchainQuery ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - **query_id** (string) - Required - The ID of the query. - **chain_id** (string) - Required - The chain ID to query. - **query** (string) - Required - The query to execute. ``` -------------------------------- ### Mint Message Definition (Protobuf) Source: https://github.com/neutron-org/neutron/blob/main/x/tokenfactory/README.md Defines the structure for minting tokens of a specific denomination. Only the creator of the denom can mint. This message requires sender's address and the amount to mint, ensuring safety checks against the denom's admin. ```protobuf message MsgMint { string sender = 1 [ (gogoproto.moretags) = "yaml:\"sender\"" ]; cosmos.base.v1beta1.Coin amount = 2 [ (gogoproto.moretags) = "yaml:\"amount\"", (gogoproto.nullable) = false ]; } ``` -------------------------------- ### POST /SubmitTx Source: https://github.com/neutron-org/neutron/blob/main/wasmbinding/README.md This endpoint submits a transaction for execution on a remote chain. ```APIDOC ## POST /SubmitTx ### Description Submits a transaction for execution on a remote chain. ### Method POST ### Endpoint /SubmitTx ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - **tx** (string) - Required - The transaction to submit. ``` -------------------------------- ### Schedule Smart Contract Executions with Go Source: https://context7.com/neutron-org/neutron/llms.txt This Go code demonstrates how to schedule and manage automated smart contract executions on the Neutron blockchain. It covers adding, querying, and removing schedules for periodic tasks, with executions typically occurring at the end of a block. ```go package main import ( "context" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/neutron-org/neutron/v8/x/cron/keeper" "github.com/neutron-org/neutron/v8/x/cron/types" ) func ScheduleContractExecution(ctx context.Context, k keeper.Keeper, authority string) error { // Define contract execution message contractMsg := types.MsgExecuteContract{ Contract: "neutron1contract...", Msg: `{"update_price": {}}`, } // Add schedule for periodic execution msg := &types.MsgAddSchedule{ Authority: authority, Name: "price_updater", Period: 100, // Execute every 100 blocks Msgs: []*types.MsgExecuteContract{&contractMsg}, ExecutionStage: types.ExecutionStage_EXECUTION_STAGE_END_BLOCKER, } _, err := k.AddSchedule(ctx, msg) if err != nil { return err } // Query existing schedules schedules := k.GetAllSchedules(sdk.UnwrapSDKContext(ctx)) for _, schedule := range schedules { println("Schedule:", schedule.Name) println("Period:", schedule.Period) println("Last executed at:", schedule.LastExecuteHeight) } // Remove schedule when no longer needed removeMsg := &types.MsgRemoveSchedule{ Authority: authority, Name: "price_updater", } _, err = k.RemoveSchedule(ctx, removeMsg) return err } ``` -------------------------------- ### ChangeAdmin Message Definition (Protobuf) Source: https://github.com/neutron-org/neutron/blob/main/x/tokenfactory/README.md Defines the structure for changing the administrator of a specific denomination. This operation is restricted to the current admin. It requires the sender's address, the denom, and the new admin's address. ```protobuf message MsgChangeAdmin { string sender = 1 [ (gogoproto.moretags) = "yaml:\"sender\"" ]; string denom = 2 [ (gogoproto.moretags) = "yaml:\"denom\"" ]; string newAdmin = 3 [ (gogoproto.moretags) = "yaml:\"new_admin\"" ]; } ``` -------------------------------- ### POST /RegisterInterchainAccount Source: https://github.com/neutron-org/neutron/blob/main/wasmbinding/README.md This endpoint registers an interchain account. ```APIDOC ## POST /RegisterInterchainAccount ### Description Registers an interchain account. ### Method POST ### Endpoint /RegisterInterchainAccount ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - **owner_id** (string) - Required - The ID of the owner. - **connection_id** (string) - Required - The ID of the connection. ``` -------------------------------- ### CreateDenom Message Definition (Protobuf) Source: https://github.com/neutron-org/neutron/blob/main/x/tokenfactory/README.md Defines the structure for creating a new denomination. It includes the sender's address and a subdenom. The subdenom has specific allowed characters. This message modifies state by updating DenomMetaData and AuthorityMetadata. ```protobuf message MsgCreateDenom { string sender = 1 [ (gogoproto.moretags) = "yaml:\"sender\"" ]; string subdenom = 2 [ (gogoproto.moretags) = "yaml:\"subdenom\"" ]; } ``` -------------------------------- ### Save Consensus State in BeginBlocker (Go) Source: https://github.com/neutron-org/neutron/blob/main/x/state-verifier/README.md This snippet demonstrates how the `BeginBlocker` in the State Verifier module saves the `ConsensusState` for the current block height. It includes the timestamp, Merkle root (derived from the previous block's AppHash), and the next validators hash. The `.Root` field is primarily used for verification. ```go consensusState := tendermint.ConsensusState{ Timestamp: ctx.BlockTime(), // current block time Root: ibccommitmenttypes.NewMerkleRoot(headerInfo.AppHash), // .AppHash for the previous block NextValidatorsHash: cometInfo.GetValidatorsHash(), // hash of the validator set for the next block } ``` -------------------------------- ### Manage IBC packet fees with Neutron fee refunder in Go Source: https://context7.com/neutron-org/neutron/llms.txt Provides a Go function that locks fees for a specific IBC packet, handles automatic refunds based on packet outcome, and queries stored fee information. Utilizes Neutron's feerefunder keeper and SDK types. Requires a Cosmos SDK context and an initialized keeper instance. ```go package main import ( "context" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/neutron-org/neutron/v8/x/feerefunder/keeper" "github.com/neutron-org/neutron/v8/x/feerefunder/types" ) func ManageFees(ctx context.Context, k *keeper.Keeper, payer sdk.AccAddress) error { // Set fee for IBC packet handling fee := types.Fee{ RecvFee: sdk.NewCoins(), // No fee for receive AckFee: sdk.NewCoins(sdk.NewCoin("untrn", sdk.NewInt(1000))), TimeoutFee: sdk.NewCoins(sdk.NewCoin("untrn", sdk.NewInt(2000))), } // Lock fees for upcoming IBC packet portID := "transfer" channelID := "channel-0" sequence := uint64(123) err := k.LockFees(sdk.UnwrapSDKContext(ctx), payer, types.NewPacketID(portID, channelID, sequence), fee) if err != nil { return err } // Fees are automatically refunded when: // 1. Packet is acknowledged -> RecvFee + TimeoutFee refunded, AckFee distributed // 2. Packet times out -> RecvFee + AckFee refunded, TimeoutFee distributed // 3. Packet neither acks nor times out within period -> all fees refunded // Query fee information packet, found := k.GetFeeInfo(sdk.UnwrapSDKContext(ctx), types.NewPacketID(portID, channelID, sequence)) if found { println("Ack fee:", packetFee.Fee.AckFee.String()) println("Timeout fee:", packetFee.Fee.TimeoutFee.String()) } return nil } ``` -------------------------------- ### Construct CosmWasm MsgExecuteContract in Go for IBC Wasm Hook Source: https://github.com/neutron-org/neutron/blob/main/x/ibc-hooks/README.md Defines the Go struct for MsgExecuteContract and demonstrates how to populate it with data extracted from an IBC packet's memo. Handles sender transformation, contract address extraction, message payload, and fund conversion for proper execution within the wasm hook. ```go type MsgExecuteContract struct { // Sender is the actor that signed the messages Sender string // Contract is the address of the smart contract Contract string // Msg json encoded message to be passed to the contract Msg RawContractMessage // Funds coins that are transferred to the contract on execution Funds sdk.Coins } // Construction of the MsgExecuteContract using packet data msg := MsgExecuteContract{ // Sender is derived from channel ID and original sender to avoid spoofing Sender: "ntrn-hash-of-channel-and-sender", // Contract address is taken directly from the memo field Contract: packet.data.memo["wasm"]["ContractAddress"], // Msg payload is the raw JSON message from the memo Msg: packet.data.memo["wasm"]["Msg"], // Funds are the transferred coins, with denom converted to local representation Funds: sdk.NewCoin{Denom: ibc.ConvertSenderDenomToLocalDenom(packet.data.Denom), Amount: packet.data.Amount}, } ``` -------------------------------- ### Burn Message Definition (Protobuf) Source: https://github.com/neutron-org/neutron/blob/main/x/tokenfactory/README.md Defines the structure for burning tokens of a specific denomination. Only the creator of the denom can burn. This message requires the sender's address and the amount to burn, with safety checks on the denom's admin. ```protobuf message MsgBurn { string sender = 1 [ (gogoproto.moretags) = "yaml:\"sender\"" ]; cosmos.base.v1beta1.Coin amount = 2 [ (gogoproto.moretags) = "yaml:\"amount\"", (gogoproto.nullable) = false ]; } ``` -------------------------------- ### POST /UpdateInterchainQuery Source: https://github.com/neutron-org/neutron/blob/main/wasmbinding/README.md This endpoint updates an interchain query. ```APIDOC ## POST /UpdateInterchainQuery ### Description Updates an interchain query. ### Method POST ### Endpoint /UpdateInterchainQuery ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - **query_id** (string) - Required - The ID of the query. - **query** (string) - Required - The query to execute. ``` -------------------------------- ### OAuth2 Redirect Handler (JavaScript) Source: https://github.com/neutron-org/neutron/blob/main/docs/static/oauth2-redirect.html Processes OAuth2 redirect responses, extracts authorization codes or tokens, validates the state parameter, and sends the result back to the opener window. It supports 'accessCode' and 'authorizationCode' flows. Dependencies include `window.opener.swaggerUIRedirectOauth2` for accessing Swagger UI's OAuth2 state and callback functions. ```javascript 'use strict'; function run () { var oauth2 = window.opener.swaggerUIRedirectOauth2; var sentState = oauth2.state; var redirectUrl = oauth2.redirectUrl; var isValid, qp, arr; if (/code|token|error/.test(window.location.hash)) { qp = window.location.hash.substring(1); } else { qp = location.search.substring(1); } arr = qp.split("&"); arr.forEach(function (v,i,_arr) { _arr[i] = '"' + v.replace('=', '":"') + '"'; }); qp = qp ? JSON.parse('{' + arr.join() + '}', function (key, value) { return key === "" ? value : decodeURIComponent(value); } ) : {}; isValid = qp.state === sentState; if (( oauth2.auth.schema.get("flow") === "accessCode" || oauth2.auth.schema.get("flow") === "authorizationCode" || oauth2.auth.schema.get("flow") === "authorization_code" ) && !oauth2.auth.code) { if (!isValid) { oauth2.errCb({ authId: oauth2.auth.name, source: "auth", level: "warning", message: "Authorization may be unsafe, passed state was changed in server Passed state wasn't returned from auth server" }); } if (qp.code) { delete oauth2.state; oauth2.auth.code = qp.code; oauth2.callback({auth: oauth2.auth, redirectUrl: redirectUrl}); } else { let oauthErrorMsg; if (qp.error) { oauthErrorMsg = "["+qp.error+"]: " + (qp.error_description ? qp.error_description + ". " : "no accessCode received from the server. ") + (qp.error_uri ? "More info: "+qp.error_uri : ""); } oauth2.errCb({ authId: oauth2.auth.name, source: "auth", level: "error", message: oauthErrorMsg || "[Authorization failed]: no accessCode received from the server" }); } } else { oauth2.callback({auth: oauth2.auth, token: qp, isValid: isValid, redirectUrl: redirectUrl}); } window.close(); } window.addEventListener('DOMContentLoaded', function () { run(); }); ``` -------------------------------- ### ICS20 Packet JSON Format for Wasm Hook Source: https://github.com/neutron-org/neutron/blob/main/x/ibc-hooks/README.md Shows the expected JSON structure of an ICS-20 packet that includes a wasm hook memo. The memo must contain a "wasm" object with "contract" and "msg" fields, and the packet may specify a receiver that matches the contract address. ```json { "data": { "denom": "denom on counterparty chain (e.g. uatom)", "amount1000", "sender": "addr on counterparty chain", "receiver": "contract addr or blank", "memo": { "wasm": { "contract": "ntrnContractAddr", "msg": { "raw_message_fields": "raw_message_data" } } } } } ``` -------------------------------- ### POST /RemoveInterchainQuery Source: https://github.com/neutron-org/neutron/blob/main/wasmbinding/README.md This endpoint removes an interchain query. ```APIDOC ## POST /RemoveInterchainQuery ### Description Removes an interchain query. ### Method POST ### Endpoint /RemoveInterchainQuery ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - **query_id** (string) - Required - The ID of the query to remove. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.