### Installing Secret.js with npm Source: https://github.com/scrtlabs/secret.js/blob/master/README.md This command installs the Secret.js SDK using the npm package manager. It is the standard method for integrating the library into Node.js projects. ```bash npm install secretjs ``` -------------------------------- ### Installing Secret.js with Yarn Source: https://github.com/scrtlabs/secret.js/blob/master/README.md This command installs the Secret.js SDK using the Yarn package manager. It serves as an alternative to npm for managing project dependencies. ```bash yarn add secretjs ``` -------------------------------- ### Installing Secret.js in the Browser Source: https://github.com/scrtlabs/secret.js/blob/master/README.md This HTML snippet includes the Secret.js SDK directly in a web browser by loading the `browser.js` file from unpkg. After loading, it accesses the `SecretNetworkClient` class from the global `window.secretjs` object, making it available for use in client-side scripts. ```html ``` -------------------------------- ### Initializing Secret.js Client and Wallet Address - TypeScript Source: https://github.com/scrtlabs/secret.js/blob/master/README.md This code initializes a `SecretNetworkClient` with a `Wallet` instance, demonstrating how to derive and use the wallet's address. It shows that `secretjs.address` property of a signer client is equivalent to the `walletAddress` used during client instantiation. This setup is crucial for sending transactions. ```TypeScript import { Wallet, SecretNetworkClient } from "secretjs"; const wallet = new Wallet( "grant rice replace explain federal release fix clever romance raise often wild taxi quarter soccer fiber love must tape steak together observe swap guitar", ); const myAddress = wallet.address; const url = "TODO get from https://github.com/scrtlabs/api-registry"; // To create a signer secret.js client, also pass in a wallet const secretjs = new SecretNetworkClient({ url, chainId: "secret-4", wallet: wallet, walletAddress: myAddress, }); const alsoMyAddress = secretjs.address; ``` -------------------------------- ### Broadcasting Transactions with Secret.js Source: https://github.com/scrtlabs/secret.js/blob/master/README.md This example demonstrates how to initialize a `SecretNetworkClient` with a `Wallet` and broadcast a transaction. It constructs a `MsgSend` to transfer tokens and then broadcasts it, specifying transaction parameters like gas limit, gas price, and fee denomination. ```ts import { Wallet, SecretNetworkClient, MsgSend, MsgMultiSend, stringToCoins } from "secretjs"; const wallet = new Wallet( "grant rice replace explain federal release fix clever romance raise often wild taxi quarter soccer fiber love must tape steak together observe swap guitar", ); const myAddress = wallet.address; const url = "TODO get from https://github.com/scrtlabs/api-registry"; // To create a signer secret.js client, also pass in a wallet const secretjs = new SecretNetworkClient({ url, chainId: "secret-4", wallet: wallet, walletAddress: myAddress, }); const bob = "secret1dgqnta7fwjj6x9kusyz7n8vpl73l7wsm0gaamk"; const msg = new MsgSend({ from_address: myAddress, to_address: bob, amount: stringToCoins("1uscrt"), }); const tx = await secretjs.tx.broadcast([msg], { gasLimit: 20_000, gasPriceInFeeDenom: 0.1, feeDenom: "uscrt", }); ``` -------------------------------- ### Submitting a Governance Proposal with Secret.js (TypeScript) Source: https://github.com/scrtlabs/secret.js/blob/master/README.md This example demonstrates how to submit a new governance proposal. It requires the proposer's address, an initial deposit, and details about the proposal content such as title, summary, and metadata. ```TypeScript const tx = await secretjs.tx.gov.submitProposal( { proposer: myAddress, initial_deposit: stringToCoins("1000000uscrt"), messages: [], metadata: "some_metadata", summary: "summary", title: "some proposal", expedited: false, }, { broadcastCheckIntervalMs: 100, gasLimit: 5_000_000, }, ); const proposalId = Number( tx.arrayLog.find( (log) => log.type === "submit_proposal" && log.key === "proposal_id", ).value, ); ``` -------------------------------- ### Querying All Accounts with secretjs.query.auth.accounts Source: https://github.com/scrtlabs/secret.js/blob/master/README.md This snippet demonstrates how to use `secretjs.query.auth.accounts` to retrieve a list of all existing accounts on the blockchain. This can be useful for administrative tools or for auditing purposes to get an overview of all registered accounts. ```TypeScript /// Get all accounts const result = await secretjs.query.auth.accounts({}); ``` -------------------------------- ### Querying Secret Network Data with Secret.js Source: https://github.com/scrtlabs/secret.js/blob/master/README.md This example demonstrates how to create a read-only `SecretNetworkClient` to query blockchain data. It shows fetching an account's bank balance and querying a Secret Contract for its token information, highlighting the use of `code_hash` for optimized contract queries. ```ts import { SecretNetworkClient } from "secretjs"; const url = "TODO get from https://github.com/scrtlabs/api-registry"; // To create a readonly secret.js client, just pass in a LCD endpoint const secretjs = new SecretNetworkClient({ url, chainId: "secret-4", }); const { balance: { amount }, } = await secretjs.query.bank.balance( { address: "secret1ap26qrlp8mcq2pg6r47w43l0y8zkqm8a450s03", denom: "uscrt", } /*, // optional: query at a specific height (using an archive node) [["x-cosmos-block-height", "2000000"]] */, ); console.log(`I have ${Number(amount) / 1e6} SCRT!`); const sSCRT = "secret1k0jntykt7e4g3y88ltc60czgjuqdy4c9e8fzek"; // Get codeHash using `secretcli q compute contract-hash secret1k0jntykt7e4g3y88ltc60czgjuqdy4c9e8fzek` const sScrtCodeHash = "af74387e276be8874f07bec3a87023ee49b0e7ebe08178c49d0a49c3c98ed60e"; const { token_info } = await secretjs.query.compute.queryContract({ contract_address: sSCRT, code_hash: sScrtCodeHash, // optional but way faster query: { token_info: {} }, }); console.log(`sSCRT has ${token_info.decimals} decimals!`); ``` -------------------------------- ### Granting Fee Allowance and Submitting Proposal with Secret.js (TypeScript) Source: https://github.com/scrtlabs/secret.js/blob/master/README.md This comprehensive example demonstrates granting a fee allowance to a new wallet and then using that allowance to submit a governance proposal. The `granter` provides a `spend_limit` for fees to the `grantee`, allowing the grantee to send transactions without holding native tokens for gas. ```TypeScript const newWallet = new Wallet(); const txGranter = await secretjsGranter.tx.feegrant.grantAllowance({ granter: secretjsGranter.address, grantee: newWallet.address, allowance: { spend_limit: stringToCoins("1000000uscrt"), }, }); const secretjsGrantee = new SecretNetworkClient({ url: "http://localhost:1317", chainId: "secretdev-1", wallet: newWallet, walletAddress: newWallet.address, }); // Send a tx from newWallet with secretjs.address as the fee payer const txGrantee = await secretjsGrantee.tx.gov.submitProposal( { proposer: secretjsGrantee.address, initial_deposit: stringToCoins("1uscrt"), messages: [], metadata: "some_metadata", summary: "Send a tx without any balance", title: "Thanks ${secretjsGranter.address}!", expedited: false, }, { feeGranter: secretjsGranter.address, }, ); ``` -------------------------------- ### Signing and Broadcasting Offline Transactions - Secret.js TypeScript Source: https://github.com/scrtlabs/secret.js/blob/master/README.md This example demonstrates the process of signing a transaction offline using `secretjs.tx.signTx()` and then broadcasting the pre-signed transaction with `secretjs.tx.broadcastSignedTx()`. This method is useful for scenarios requiring offline signing or when separating the signing and broadcasting steps for enhanced security. ```TypeScript const bob = "secret1dgqnta7fwjj6x9kusyz7n8vpl73l7wsm0gaamk"; const msg = new MsgSend({ from_address: myAddress, to_address: bob, amount: stringToCoins("1000000uscrt"), }); let signedTX = await secretjs.tx.signTx([msg], { gasLimit: 20_000, gasPriceInFeeDenom: 0.1, feeDenom: "uscrt", }); let tx = await secretjs.tx.broadcastSignedTx(signedTX); ``` -------------------------------- ### Broadcasting Multiple Contract Execution Transactions - Secret.js TypeScript Source: https://github.com/scrtlabs/secret.js/blob/master/README.md This example demonstrates broadcasting a complex transaction containing multiple `MsgExecuteContract` messages using `secretjs.tx.broadcast()`. It first prepares messages to add a minter and then mint an NFT, executing them sequentially within a single transaction. The `gasLimit` option is provided for transaction fees. ```TypeScript const addMinterMsg = new MsgExecuteContract({ sender: MY_ADDRESS, contract_address: MY_NFT_CONTRACT, code_hash: MY_NFT_CONTRACT_CODE_HASH, // optional but way faster msg: { add_minters: { minters: [MY_ADDRESS] } }, sent_funds: [], // optional }); const mintMsg = new MsgExecuteContract({ sender: MY_ADDRESS, contract_address: MY_NFT_CONTRACT, code_hash: MY_NFT_CONTRACT_CODE_HASH, // optional but way faster msg: { mint_nft: { token_id: "1", owner: MY_ADDRESS, public_metadata: { extension: { image: "https://scrt.network/secretnetwork-logo-secondary-black.png", name: "secretnetwork-logo-secondary-black", }, }, private_metadata: { extension: { image: "https://scrt.network/secretnetwork-logo-primary-white.png", name: "secretnetwork-logo-primary-white", }, }, }, }, sent_funds: [], // optional }); const tx = await secretjs.tx.broadcast([addMinterMsg, mintMsg], { gasLimit: 200_000, }); ``` -------------------------------- ### Performing IBC Transfer and Resolving Responses with Secret.js (TypeScript) Source: https://github.com/scrtlabs/secret.js/blob/master/README.md This comprehensive example demonstrates initializing `SecretNetworkClient`, performing an IBC token transfer from Secret Network to Osmosis, and then resolving the IBC response (acknowledgement or timeout). It shows how to configure `ibcTxsOptions` for response resolution and handle different outcomes of the IBC packet. ```TypeScript import { Wallet, SecretNetworkClient } from "secretjs"; const wallet = new Wallet( "grant rice replace explain federal release fix clever romance raise often wild taxi quarter soccer fiber love must tape steak together observe swap guitar", ); const osmoAddress = new Wallet( "grant rice replace explain federal release fix clever romance raise often wild taxi quarter soccer fiber love must tape steak together observe swap guitar", { bech32Prefix: "osmos", coinType: 118, }, ).address; const secretjs = new SecretNetworkClient({ url: "http://localhost:1317", chainId: "secretdev-1", wallet, walletAddress: wallet.address, }); const tx = await secretjs.tx.ibc.transfer( { sender: wallet.address, receiver: osmoAddress, source_channel: "channel-1", source_port: "transfer", token: stringToCoin("1uscrt"), timeout_timestamp: String(Math.floor(Date.now() / 1000) + 10 * 60), // 10 minutes }, { gasLimit: 100_000, ibcTxsOptions: { resolveResponses: true, // enable IBC responses resolution (defualt) resolveResponsesTimeoutMs: 12 * 60 * 1000, // stop checking after 12 minutes (default is 2 minutes) resolveResponsesCheckIntervalMs: 15_000, // check every 15 seconds (default) }, }, ); if (tx.code !== 0) { console.error("failed sending 1uscrt from Secret to Osmosis:", tx.rawLog); } else { try { const ibcResp = await tx.ibcResponses[0]; if (ibcResp.type === "ack") { console.log("successfuly sent 1uscrt from Secret to Osmosis!"); } else { console.error( "failed sending 1uscrt from Secret to Osmosis: IBC packet timed-out before committed on Osmosis", ); } } catch (_error) { console.error( `timed-out while trying to resolve IBC response for txhash ${tx.transactionHash}`, ); } } ``` -------------------------------- ### Unjailing a Validator with Secret.js (TypeScript) Source: https://github.com/scrtlabs/secret.js/blob/master/README.md This example demonstrates how to unjail a validator that has been jailed due to misbehavior. It requires the `validator_addr` of the jailed validator. ```TypeScript const tx = await secretjs.tx.slashing.unjail( { validator_addr: mValidatorsAddress, }, { gasLimit: 50_000, }, ); ``` -------------------------------- ### Broadcasting Multiple Distribution Messages with Secret.js (TypeScript) Source: https://github.com/scrtlabs/secret.js/blob/master/README.md This example shows a more advanced way to broadcast multiple distribution messages in a single transaction, including `MsgWithdrawDelegatorReward` and `MsgWithdrawValidatorCommission`. It uses `secretjs.tx.broadcast` to send an array of messages. ```TypeScript const tx = await secretjs.tx.broadcast( [ new MsgWithdrawDelegatorReward({ delegator_address: mySelfDelegatorAddress, validator_address: myValidatorAddress, }), new MsgWithdrawValidatorCommission({ validator_address: myValidatorAddress, }), ], { gasLimit: 30_000, }, ); ``` -------------------------------- ### Casting a Weighted Governance Vote with Secret.js (TypeScript) Source: https://github.com/scrtlabs/secret.js/blob/master/README.md This example demonstrates how to cast a weighted vote on a governance proposal, allowing a voter to split their voting power across multiple options. The weights provided for each option must sum up to 1.0. ```TypeScript // vote yes with 70% of my power const tx = await secretjs.tx.gov.voteWeighted( { voter: myAddress, proposal_id: someProposalId, options: [ // weights must sum to 1.0 { weight: "0.7", option: VoteOption.VOTE_OPTION_YES }, { weight: "0.3", option: VoteOption.VOTE_OPTION_ABSTAIN }, ], metadata: "", }, { gasLimit: 50_000, }, ); ``` -------------------------------- ### Creating a Signer SecretNetworkClient for Transactions and Queries Source: https://github.com/scrtlabs/secret.js/blob/master/README.md This snippet demonstrates how to create a `SecretNetworkClient` capable of broadcasting transactions, sending queries, and accessing chain information. It requires a `Wallet` instance, the wallet's address, and the `chainId` to enable full signing capabilities, providing access to `secretjs.tx` and `secretjs.address` in addition to `secretjs.query`. ```TypeScript import { Wallet, SecretNetworkClient, MsgSend, MsgMultiSend } from "secretjs"; const wallet = new Wallet( "grant rice replace explain federal release fix clever romance raise often wild taxi quarter soccer fiber love must tape steak together observe swap guitar", ); const myAddress = wallet.address; const url = "TODO get from https://github.com/scrtlabs/api-registry"; // To create a signer secret.js client you must also pass in `wallet`, `walletAddress` and `chainId` const secretjs = new SecretNetworkClient({ url, chainId: "secret-4", wallet: wallet, walletAddress: myAddress, }); ``` -------------------------------- ### Importing Account into Secret.js Wallet from Mnemonic Source: https://github.com/scrtlabs/secret.js/blob/master/README.md This snippet demonstrates how to initialize a `Wallet` instance in Secret.js by providing a mnemonic phrase. This allows an application to import an existing account and retrieve its associated address for further operations. ```TypeScript import { Wallet } from "secretjs"; const wallet = new Wallet( "grant rice replace explain federal release fix clever romance raise often wild taxi quarter soccer fiber love must tape steak together observe swap guitar", ); const myAddress = wallet.address; ``` -------------------------------- ### Integrating MetaMask with Secret.js Source: https://github.com/scrtlabs/secret.js/blob/master/README.md This snippet illustrates how to connect MetaMask as a signer for Secret.js. It requests the user's Ethereum accounts via `window.ethereum`, creates a `MetaMaskWallet` instance, and then uses this wallet to initialize the `SecretNetworkClient` for signing transactions. ```ts import { SecretNetworkClient, MetaMaskWallet } from "secretjs"; //@ts-ignore const [ethAddress] = await window.ethereum.request({ method: "eth_requestAccounts", }); const wallet = await MetaMaskWallet.create(window.ethereum, ethAddress); const secretjs = new SecretNetworkClient({ url: "TODO get from https://github.com/scrtlabs/api-registry", chainId: "secret-4", wallet: wallet, walletAddress: wallet.address, }); ``` -------------------------------- ### Instantiating a Contract from Code ID with SecretJS (TypeScript) Source: https://github.com/scrtlabs/secret.js/blob/master/README.md This snippet shows how to instantiate a smart contract on the Secret Network using `secretjs.tx.compute.instantiateContract`. It requires the `sender` address, `code_id`, a `label` for the contract, and an `init_msg` object containing the contract's initialization parameters. Optional fields include `admin`, `code_hash` (for faster execution), and `init_funds`. The snippet also demonstrates how to extract the `contractAddress` from the transaction logs. ```TypeScript const tx = await secretjs.tx.compute.instantiateContract( { sender: myAddress, admin: myAddress, // optional admin address that can perform code migrations code_id: codeId, code_hash: codeHash, // optional but way faster init_msg: { name: "Secret SCRT", admin: myAddress, symbol: "SSCRT", decimals: 6, initial_balances: [{ address: myAddress, amount: "1" }], prng_seed: "eW8=", config: { public_total_supply: true, enable_deposit: true, enable_redeem: true, enable_mint: false, enable_burn: false, }, supported_denoms: ["uscrt"], }, label: "sSCRT", init_funds: [], // optional }, { gasLimit: 100_000, }, ); const contractAddress = tx.arrayLog.find( (log) => log.type === "message" && log.key === "contract_address", ).value; ``` -------------------------------- ### Creating Periodic Vesting Account with SecretJS (TypeScript) Source: https://github.com/scrtlabs/secret.js/blob/master/README.md This snippet demonstrates how to create a new periodic vesting account using `secretjs.tx.vesting.createPeriodicVestingAccount`. It requires a `from_address` to fund the account, a `to_address` which must be a new address, a `start_time`, and an array of `vesting_periods` defining the length and amount of tokens to vest over time. The output is a transaction object. ```TypeScript let tx = await secretjs.tx.vesting.createPeriodicVestingAccount({ from_address: accounts[0].address, to_address: newWallet.address, // to_address must be a new address start_time: "1234567", vesting_periods: [ { length: "100", amount: [stringToCoin("100uscrt")], }, ], }); ``` -------------------------------- ### Integrating Keplr Wallet with Secret.js Source: https://github.com/scrtlabs/secret.js/blob/master/README.md This code demonstrates the recommended integration of Keplr Wallet with Secret.js. It ensures Keplr's availability, enables the specified chain, retrieves the offline signer and account address, and then initializes `SecretNetworkClient` with Keplr's signer and optional encryption utilities for persistent transaction decryption. ```ts import { SecretNetworkClient } from "secretjs"; const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); while ( !window.keplr || !window.getEnigmaUtils || !window.getOfflineSigner ) { await sleep(50); } const CHAIN_ID = "secret-4"; await window.keplr.enable(CHAIN_ID); const keplrOfflineSigner = window.keplr.getOfflineSigner(CHAIN_ID); const [{ address: myAddress }] = await keplrOfflineSigner.getAccounts(); const url = "TODO get from https://github.com/scrtlabs/api-registry"; const secretjs = new SecretNetworkClient({ url, chainId: CHAIN_ID, wallet: keplrOfflineSigner, ``` -------------------------------- ### Generating a New Random Account with Secret.js Wallet Source: https://github.com/scrtlabs/secret.js/blob/master/README.md This snippet shows how to generate a new, random account using the `Wallet` class in Secret.js. It creates a new wallet instance, automatically generating a mnemonic phrase and an associated address, which can then be used for new user onboarding or temporary accounts. ```TypeScript import { Wallet } from "secretjs"; const wallet = new Wallet(); const myAddress = wallet.address; const myMnemonicPhrase = wallet.mnemonic; ``` -------------------------------- ### Querying Governance Proposals with secretjs.query.gov.proposals (TypeScript) Source: https://github.com/scrtlabs/secret.js/blob/master/README.md This snippet demonstrates how to query all governance proposals on the chain using `secretjs.query.gov.proposals`. It allows filtering by `proposal_status`, `voter`, and `depositor`, but here it's used to fetch all proposals by setting `PROPOSAL_STATUS_UNSPECIFIED` and empty strings for voter/depositor. ```TypeScript // Get all proposals const { proposals } = await secretjs.query.gov.proposals({ proposal_status: ProposalStatus.PROPOSAL_STATUS_UNSPECIFIED, voter: "", depositor: "", }); ``` -------------------------------- ### Integrating Leap Cosmos Wallet with Secret.js Source: https://github.com/scrtlabs/secret.js/blob/master/README.md This code demonstrates how to integrate the Leap Cosmos Wallet with Secret.js. It waits for the Leap wallet to be available, enables it for a specific chain ID, retrieves the offline signer and user address, and then initializes a `SecretNetworkClient` with the Leap signer and optional encryption utilities for persistent decryption. ```TypeScript import { SecretNetworkClient } from "secretjs"; const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); while ( !window.leap || !window.leap.getEnigmaUtils || !window.leap.getOfflineSigner ) { await sleep(50); } const CHAIN_ID = "secret-4"; await window.leap.enable(CHAIN_ID); const leapOfflineSigner = window.leap.getOfflineSigner(CHAIN_ID); const [{ address: myAddress }] = await leapOfflineSigner.getAccounts(); const url = "TODO get from https://github.com/scrtlabs/api-registry"; const secretjs = new SecretNetworkClient({ url, chainId: CHAIN_ID, wallet: leapOfflineSigner, walletAddress: myAddress, encryptionUtils: window.leap.getEnigmaUtils(CHAIN_ID), }); // Note: Using `window.leap.getEnigmaUtils()` is optional, it will allow // Leap to use the same encryption seed across sessions for the account. // The benefit of this is that `secretjs.query.getTx()` will be able to decrypt // the response across sessions. ``` -------------------------------- ### Funding the Community Pool with SecretJS (TypeScript) Source: https://github.com/scrtlabs/secret.js/blob/master/README.md This snippet demonstrates how to directly fund the community pool using `secretjs.tx.distribution.fundCommunityPool`. It requires the `depositor` address and the `amount` of coins to deposit. An optional `gasLimit` can be provided. ```TypeScript const tx = await secretjs.tx.distribution.fundCommunityPool( { depositor: myAddress, amount: stringToCoins("1uscrt"), }, { gasLimit: 20_000, }, ); ``` -------------------------------- ### Querying Single Governance Deposit with secretjs.query.gov.deposit (TypeScript) Source: https://github.com/scrtlabs/secret.js/blob/master/README.md This snippet illustrates how to query information about a single deposit made to a governance proposal using `secretjs.query.gov.deposit`. It requires the `depositor` address and `proposalId` to retrieve the deposit details, specifically extracting the `amount`. ```TypeScript const { deposit: { amount }, } = await secretjs.query.gov.deposit({ depositor: myAddress, proposalId: propId, }); ``` -------------------------------- ### Creating a Readonly SecretNetworkClient for Queries Source: https://github.com/scrtlabs/secret.js/blob/master/README.md This snippet illustrates how to instantiate a `SecretNetworkClient` that can only perform queries and retrieve chain information. By providing only the `chainId` and `url` (LCD endpoint), it creates a 'querier' client, suitable for applications that only need to read data from the Secret Network. ```TypeScript import { SecretNetworkClient } from "secretjs"; const url = "TODO get from https://github.com/scrtlabs/api-registry"; // To create a readonly secret.js client, just pass in a LCD endpoint const secretjs = new SecretNetworkClient({ chainId: "secret-4", url, }); ``` -------------------------------- ### Sending Coins with SecretJS (TypeScript) Source: https://github.com/scrtlabs/secret.js/blob/master/README.md This snippet demonstrates how to send coins from one account to another using `secretjs.tx.bank.send`. It requires `from_address`, `to_address`, and the `amount` of coins to send. An optional `gasLimit` can be provided to control transaction fees. ```TypeScript const tx = await secretjs.tx.bank.send( { from_address: myAddress, to_address: alice, amount: stringToCoins("1uscrt"), }, { gasLimit: 20_000, }, ); ``` -------------------------------- ### Querying Auth Module Parameters with secretjs.query.auth.params Source: https://github.com/scrtlabs/secret.js/blob/master/README.md This snippet illustrates how to fetch the x/auth module's parameters using `secretjs.query.auth.params`. It retrieves configuration details such as `maxMemoCharacters`, `sigVerifyCostEd25519`, `sigVerifyCostSecp256k1`, `txSigLimit`, and `txSizeCostPerByte`, which are important for understanding transaction constraints. ```TypeScript const { params: { maxMemoCharacters, sigVerifyCostEd25519, sigVerifyCostSecp256k1, txSigLimit, txSizeCostPerByte, }, } = await secretjs.query.auth.params({}); ``` -------------------------------- ### Simulating and Broadcasting Transactions for Gas Estimation - Secret.js TypeScript Source: https://github.com/scrtlabs/secret.js/blob/master/README.md This snippet illustrates how to simulate a transaction using `secretjs.tx.simulate()` to estimate gas usage before broadcasting. It prepares two `MsgSend` messages and then uses the simulation result to calculate an adjusted `gasLimit` for the actual broadcast, accounting for potential estimation errors. ```TypeScript const sendToAlice = new MsgSend({ from_address: bob, to_address: alice, amount: stringToCoins("1uscrt"), }); const sendToEve = new MsgSend({ from_address: bob, to_address: eve, amount: stringToCoins("1uscrt"), }); const sim = await secretjs.tx.simulate([sendToAlice, sendToEve]); const tx = await secretjs.tx.broadcast([sendToAlice, sendToEve], { // Adjust gasLimit up by 10% to account for gas estimation error gasLimit: Math.ceil(sim.gas_info.gas_used * 1.1), }); ``` -------------------------------- ### Opening App in Fina Wallet In-App Browser (Deep Linking) Source: https://github.com/scrtlabs/secret.js/blob/master/README.md This snippet demonstrates how to use deep linking to open a web application within the Fina Wallet's in-app browser. It constructs a URL with network and current page information and opens it in a new window, allowing seamless transition from a regular mobile browser to Fina's integrated browser. ```TypeScript const urlSearchParams = new URLSearchParams(); urlSearchParams.append("network", "secret-4"); urlSearchParams.append("url", window.location.href); window.open(`fina://wllet/dapps?${urlSearchParams.toString()}`, "_blank"); ``` -------------------------------- ### Depositing to a Governance Proposal with Secret.js (TypeScript) Source: https://github.com/scrtlabs/secret.js/blob/master/README.md This snippet illustrates how to submit a deposit to an existing governance proposal. It requires the depositor's address, the proposal ID, and the amount of tokens to deposit. ```TypeScript const tx = await secretjs.tx.gov.deposit( { depositor: myAddress, proposal_id: someProposalId, amount: stringToCoins("1uscrt"), }, { gasLimit: 20_000, }, ); ``` -------------------------------- ### Performing Multi-Send Transaction with SecretJS (TypeScript) Source: https://github.com/scrtlabs/secret.js/blob/master/README.md This snippet illustrates how to use `secretjs.tx.bank.multiSend` to execute an arbitrary multi-input, multi-output token transfer. It takes an object with `inputs` (sender addresses and their coins) and `outputs` (recipient addresses and their coins). An optional `gasLimit` can be specified for the transaction. ```TypeScript const tx = await secretjs.tx.bank.multiSend( { inputs: [ { address: myAddress, coins: stringToCoins("2uscrt"), }, ], outputs: [ { address: alice, coins: stringToCoins("1uscrt"), }, { address: bob, coins: stringToCoins("1uscrt"), }, ], }, { gasLimit: 20_000, }, ); ``` -------------------------------- ### Creating a Permanent Locked Vesting Account - Secret.js TypeScript Source: https://github.com/scrtlabs/secret.js/blob/master/README.md This snippet shows how to create a new permanently locked vesting account using `secretjs.tx.vesting.createPermanentLockedAccount()`. It funds the new account with a specified amount of tokens from a source address. The `to_address` parameter must refer to a newly generated address. ```TypeScript let tx = await secretjs.tx.vesting.createPermanentLockedAccount({ from_address: accounts[0].address, to_address: newWallet.address, // to_address must be a new address amount: coinsFromString("1uscrt"), }); ``` -------------------------------- ### Querying Account Details with secretjs.query.auth.account Source: https://github.com/scrtlabs/secret.js/blob/master/README.md This snippet shows how to use `secretjs.query.auth.account` to retrieve detailed information for a specific account address. It returns the account's address, account number, and sequence, which are essential for constructing and signing transactions. ```TypeScript const { address, accountNumber, sequence } = await secretjs.query.auth.account({ address: myAddress, }); ``` -------------------------------- ### Integrating Ledger Wallet with Secret.js using @cosmjs/ledger-amino Source: https://github.com/scrtlabs/secret.js/blob/master/README.md This snippet shows how to connect a Ledger hardware wallet to Secret.js for signing transactions. It uses `@cosmjs/ledger-amino` to create a `LedgerSigner`, specifying the HD path and prefix. The signer is then used to initialize a `SecretNetworkClient`, enabling secure transaction signing via Ledger. ```TypeScript import { SecretNetworkClient } from 'secretjs'; import { makeCosmoshubPath } from "@cosmjs/amino"; import { LedgerSigner } from "@cosmjs/ledger-amino"; // NodeJS only import TransportNodeHid from "@ledgerhq/hw-transport-node-hid"; // Browser only //import TransportNodeHid from "@ledgerhq/hw-transport-webusb"; const interactiveTimeout = 120_000; const accountIndex = 0; const cosmosPath = makeCosmoshubPath(accountIndex); const ledgerTransport = await TransportNodeHid.create(interactiveTimeout, interactiveTimeout); const ledgerSigner = new LedgerSigner( ledgerTransport, { testModeAllowed: true, hdPaths: [cosmosPath], prefix: 'secret' } ); const [{ address }] = await signer.getAccounts(); const client = new SecretNetworkClient({ url: "TODO get from https://github.com/scrtlabs/api-registry", chainId: "secret-4", wallet: ledgerSigner, walletAddress: address, }); ``` -------------------------------- ### Querying Single Coin Balance with secretjs.query.bank.balance Source: https://github.com/scrtlabs/secret.js/blob/master/README.md This snippet demonstrates how to query the balance of a specific coin for a given account using `secretjs.query.bank.balance`. It requires the account address and the denomination of the coin (e.g., 'uscrt') to retrieve the current balance. ```TypeScript const { balance } = await secretjs.query.bank.balance({ address: myAddress, denom: "uscrt", }); ``` -------------------------------- ### Querying Secret Contract Data with secretjs.query.compute.queryContract (TypeScript) Source: https://github.com/scrtlabs/secret.js/blob/master/README.md This snippet demonstrates how to query a Secret Contract using `secretjs.query.compute.queryContract`. It defines a `Result` type for the expected token information and then executes a query to retrieve token details like decimals, name, symbol, and total supply. The `code_hash` is optional but significantly improves query speed. ```TypeScript type Result = { token_info: { decimals: number; name: string; symbol: string; total_supply: string; }; }; const result = (await secretjs.query.compute.queryContract({ contract_address: sScrtAddress, code_hash: sScrtCodeHash, // optional but way faster query: { token_info: {} }, })) as Result; ``` -------------------------------- ### Beginning a Staking Redelegation with Secret.js (TypeScript) Source: https://github.com/scrtlabs/secret.js/blob/master/README.md This snippet illustrates how to redelegate staked coins from a source validator to a destination validator. It requires the delegator's address, the source validator's address, the destination validator's address, and the amount to redelegate. ```TypeScript const tx = await secretjs.tx.staking.beginRedelegate( { delegator_address: myAddress, validator_src_address: someValidator, validator_dst_address: someOtherValidator, amount: stringToCoin("1uscrt"), }, { gasLimit: 50_000, }, ); ``` -------------------------------- ### Querying All Staking Validators - Secret.js TypeScript Source: https://github.com/scrtlabs/secret.js/blob/master/README.md This snippet demonstrates how to query all validators on the Secret Network using `secretjs.query.staking.validators()`. It retrieves a list of validators, optionally filtered by status. The `status` parameter can be an empty string to fetch all validators. ```TypeScript const { validators } = await secretjs.query.staking.validators({ status: "" }); ``` -------------------------------- ### Creating a Validator with Secret.js Staking Module (TypeScript) Source: https://github.com/scrtlabs/secret.js/blob/master/README.md This snippet demonstrates how to create a new validator on the Secret Network using `secretjs.tx.staking.createValidator`. It requires `MsgCreateValidatorParams` to define validator properties like delegator address, commission rates, description, public key, minimum self-delegation, and initial delegation. The transaction is sent with a specified gas limit. ```TypeScript const tx = await secretjs.tx.staking.createValidator( { delegator_address: myAddress, commission: { max_change_rate: 0.01, // can change +-1% every 24h max_rate: 0.1, // 10% rate: 0.05, // 5% }, description: { moniker: "My validator's display name", identity: "ID on keybase.io, to have a logo on explorer and stuff", website: "example.com", security_contact: "hi@example.com", details: "**We** are good", }, pubkey: toBase64(new Uint8Array(32).fill(1)), // validator's pubkey, to sign on validated blocks min_self_delegation: "1", // uscrt initial_delegation: stringToCoin("1uscrt"), }, { gasLimit: 100_000, }, ); ``` -------------------------------- ### Executing a Function on a Contract with SecretJS (TypeScript) Source: https://github.com/scrtlabs/secret.js/blob/master/README.md This snippet demonstrates how to execute a function on an existing smart contract using `secretjs.tx.compute.executeContract`. It requires the `sender` address, `contract_address`, and a `msg` object containing the function call and its parameters (e.g., 'transfer' with 'recipient' and 'amount'). Optional fields include `code_hash` and `sent_funds`. A `gasLimit` is also specified. ```TypeScript const tx = await secretjs.tx.compute.executeContract( { sender: myAddress, contract_address: contractAddress, code_hash: codeHash, // optional but way faster msg: { transfer: { recipient: bob, amount: "1", }, }, sent_funds: [], // optional }, { gasLimit: 100_000, }, ); ``` -------------------------------- ### Setting Delegator Withdraw Address with SecretJS (TypeScript) Source: https://github.com/scrtlabs/secret.js/blob/master/README.md This snippet shows how to set the withdraw address for a delegator using `secretjs.tx.distribution.setWithdrawAddress`. It requires the `delegator_address` and the `withdraw_address` where rewards will be sent. An optional `gasLimit` can be provided. ```TypeScript const tx = await secretjs.tx.distribution.setWithdrawAddress( { delegator_address: mySelfDelegatorAddress, withdraw_address: myOtherAddress, }, { gasLimit: 20_000, }, ); ``` -------------------------------- ### Withdrawing Delegator Reward with SecretJS (TypeScript) Source: https://github.com/scrtlabs/secret.js/blob/master/README.md This snippet demonstrates how to withdraw rewards from a single validator for a delegator using `secretjs.tx.distribution.withdrawDelegatorReward`. It requires the `delegator_address` and the `validator_address` from which to withdraw rewards. An optional `gasLimit` can be provided. ```TypeScript const tx = await secretjs.tx.distribution.withdrawDelegatorReward( { delegator_address: myAddress, validator_address: someValidatorAddress, }, { gasLimit: 20_000, }, ); ``` -------------------------------- ### Migrating a Contract with SecretJS (TypeScript) Source: https://github.com/scrtlabs/secret.js/blob/master/README.md This snippet shows how to migrate a contract's code while retaining its existing address using `secretjs.tx.compute.migrateContract`. It requires the `sender` address, `contract_address`, the `newCodeId` for the updated contract, and a `msg` object for the migration function. Optional fields include `newCodeHash` and `sent_funds`. A `gasLimit` is also specified. ```TypeScript const tx = await secretjs.tx.compute.migrateContract( { sender: myAddress, contract_address: contractAddress, code_id: newCodeId, code_hash: newCodeHash, // optional but way faster msg: { migrate_state_to_new_format: {}, }, sent_funds: [], // optional }, { gasLimit: 100_000, }, ); ``` -------------------------------- ### Delegating Tokens with Secret.js Staking Module (TypeScript) Source: https://github.com/scrtlabs/secret.js/blob/master/README.md This snippet illustrates how to delegate coins from a delegator to a validator using `secretjs.tx.staking.delegate`. It takes `MsgDelegateParams` including the delegator's address, validator's address, and the amount of tokens to delegate. A gas limit is also specified for the transaction. ```TypeScript const tx = await secretjs.tx.staking.delegate( { delegator_address: myAddress, validator_address: someValidatorAddress, amount: stringToCoin("1uscrt"), }, { gasLimit: 50_000, }, ); ``` -------------------------------- ### Retrieving WASM Code and Metadata with secretjs.query.compute.code (TypeScript) Source: https://github.com/scrtlabs/secret.js/blob/master/README.md This snippet shows how to retrieve the WASM bytecode and associated metadata for a given contract code ID using `secretjs.query.compute.code`. It returns an object containing `codeInfo`, which holds details about the code. ```TypeScript const { codeInfo } = await secretjs.query.compute.code(codeId); ``` -------------------------------- ### Depositing Validator Rewards Pool with Secret.js (TypeScript) Source: https://github.com/scrtlabs/secret.js/blob/master/README.md This snippet illustrates how to provide additional rewards to delegators from a specific validator by depositing into the validator's rewards pool. It requires the depositor's address, validator's address, and the amount to deposit. ```TypeScript const tx = await secretjs.tx.distribution.depositValidatorRewardsPool( { depositor: depositorAddress, validator_address: validatorAddress, amount: [stringToCoin("10000uscrt")], }, { broadcastCheckIntervalMs: 100, gasLimit: gasLimit, }, ); ``` -------------------------------- ### Uploading Compiled Contract Code to Secret Network with SecretJS (TypeScript) Source: https://github.com/scrtlabs/secret.js/blob/master/README.md This snippet demonstrates how to upload a compiled WebAssembly contract to the Secret Network using `secretjs.tx.compute.storeCode`. It requires the `sender` address and the `wasm_byte_code` as a Uint8Array. Optional fields like `source` and `builder` can be included. The `gasLimit` is set to a higher value due to the nature of code storage. The snippet also shows how to extract the `codeId` from the transaction logs. ```TypeScript const tx = await secretjs.tx.compute.storeCode( { sender: myAddress, wasm_byte_code: fs.readFileSync( `${__dirname}/snip20-ibc.wasm.gz`, ) as Uint8Array, source: "", builder: "", }, { gasLimit: 1_000_000, }, ); const codeId = Number( tx.arrayLog.find((log) => log.type === "message" && log.key === "code_id") .value, ); ``` -------------------------------- ### Setting Send Enabled Status with SecretJS (TypeScript) Source: https://github.com/scrtlabs/secret.js/blob/master/README.md This snippet shows how to use `secretjs.tx.bank.setSendEnabled` to configure which denominations are enabled for sending. This function is typically used with the x/gov module and requires an `authority` address, an array of `send_enabled` objects specifying the denom and its enabled status, and an optional `use_default_for` array. ```TypeScript const tx = await secretjs.tx.bank.setSendEnabled( { authority: authorityAddress, send_enabled: [ { denom: "banana", enabled: true, }, ], use_default_for: [], } ) ``` -------------------------------- ### Updating a Contract's Admin with SecretJS (TypeScript) Source: https://github.com/scrtlabs/secret.js/blob/master/README.md This snippet demonstrates how to update the administrator of a smart contract using `secretjs.tx.compute.updateAdmin`. It requires the `sender` (current admin address), the `contract_address`, and the `new_admin` address. A `gasLimit` is also specified for the transaction. ```TypeScript const tx = await secretjs.tx.compute.updateAdmin( { sender: currentAdminAddress, contract_address: contractAddress, new_admin: newAdminAddress, }, { gasLimit: 100_000, }, ); ``` -------------------------------- ### Pruning Expired Fee Allowances with Secret.js (TypeScript) Source: https://github.com/scrtlabs/secret.js/blob/master/README.md This code demonstrates how to prune expired fee allowances from the blockchain. The `pruner` address initiates the transaction to clean up any allowances that have passed their expiration. ```TypeScript let tx = await secretjs.tx.feegrant.pruneAllowances({ pruner: secretjs.address, }); ``` -------------------------------- ### Withdrawing Validator Commission using Secret.js (TypeScript) Source: https://github.com/scrtlabs/secret.js/blob/master/README.md This snippet demonstrates how to withdraw the full commission to a validator's address using `secretjs.tx.distribution.withdrawValidatorCommission`. It requires the `validator_address` and an optional `gasLimit` for the transaction. ```TypeScript const tx = await secretjs.tx.distribution.withdrawValidatorCommission( { validator_address: myValidatorAddress, }, { gasLimit: 20_000, }, ); ``` -------------------------------- ### Clearing a Contract's Admin with SecretJS (TypeScript) Source: https://github.com/scrtlabs/secret.js/blob/master/README.md This snippet shows how to clear the administrator of a smart contract using `secretjs.tx.compute.clearAdmin`. It requires the `sender` (current admin address) and the `contract_address`. A `gasLimit` is also specified for the transaction. ```TypeScript const tx = await secretjs.tx.compute.clearAdmin( { sender: currentAdminAddress, contract_address: contractAddress, }, { gasLimit: 100_000, }, ); ``` -------------------------------- ### Undelegating Tokens with Secret.js Staking Module (TypeScript) Source: https://github.com/scrtlabs/secret.js/blob/master/README.md This snippet shows how to undelegate tokens from a validator using `secretjs.tx.staking.undelegate`. It takes `MsgUndelegateParams` specifying the delegator's address, the validator's address, and the amount of tokens to undelegate. A gas limit is provided for the transaction. ```TypeScript const tx = await secretjs.tx.staking.undelegate( { delegator_address: myAddress, validator_address: someValidatorAddress, amount: stringToCoin("1uscrt"), }, { gasLimit: 50_000, }, ); ``` -------------------------------- ### Cancelling a Governance Proposal with Secret.js (TypeScript) Source: https://github.com/scrtlabs/secret.js/blob/master/README.md This snippet shows how to cancel an existing governance proposal. It requires the proposer's address and the ID of the proposal to be cancelled. ```TypeScript const txCancel = await secretjs.tx.gov.cancelProposal({ proposer: secretjs.address, proposal_id, }); ``` -------------------------------- ### Editing a Validator with Secret.js Staking Module (TypeScript) Source: https://github.com/scrtlabs/secret.js/blob/master/README.md This snippet demonstrates how to modify an existing validator's properties using `secretjs.tx.staking.editValidator`. It requires `MsgEditValidatorParams` to update the validator's description, minimum self-delegation, or commission rate. Note that editing any description field requires re-inputting all description items, and commission rate changes are rate-limited. ```TypeScript const tx = await secretjs.tx.staking.editValidator( { validator_address: myValidatorAddress, description: { // To edit even one item in "description you have to re-input everything moniker: "papaya", identity: "banana", website: "watermelon.com", security_contact: "sec@watermelon.com", details: "We are the banana papaya validator yay!", }, min_self_delegation: "2", commission_rate: 0.04, // 4%, commission cannot be changed more than once in 24h }, { gasLimit: 5_000_000, }, ); ```