The JavaScript SDK for Secret Network
Secret.js a JavaScript SDK for writing applications that interact with the Secret Network blockchain.
- Written in TypeScript and provided with type definitions.
- Provides simple abstractions over core data structures.
- Supports every possible message and transaction type.
- Exposes every possible query type.
- Handles input/output encryption/decryption for Secret Contracts.
- Works in Node.js, modern web browsers and React Native.
This library is still in beta, APIs may break. Beta testers are welcome!
See project board for list of existing/missing features.
npm install secretjs@beta
or
yarn add secretjs@beta
For a lot more usage examples refer to the tests.
import { SecretNetworkClient } from "secretjs";
// To create a readonly secret.js client, just pass in an RPC endpoint
const secretjs = await SecretNetworkClient.create({
rpcUrl: "https://rpc-secret.scrtlabs.com/secret-4/rpc/",
});
const {
balance: { amount },
} = await secretjs.query.bank.balance({
address: "secret1ap26qrlp8mcq2pg6r47w43l0y8zkqm8a450s03",
denom: "uscrt",
});
console.log(`I have ${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({
address: sSCRT,
codeHash: sScrtCodeHash, // optional but way faster
query: { token_info: {} },
});
console.log(`sSCRT has ${token_info.decimals} decimals!`);
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;
// To create a signer secret.js client, also pass in a wallet
const secretjs = await SecretNetworkClient.create({
rpcUrl: "https://rpc.pulsar.griptapejs.com/",
wallet: wallet,
walletAddress: myAddress,
chainId: "pulsar-2",
});
const bob = "secret1dgqnta7fwjj6x9kusyz7n8vpl73l7wsm0gaamk";
const msg = new MsgSend({
fromAddress: myAddress,
toAddress: bob,
amount: [{ denom: "uscrt", amount: "1" }],
});
const tx = await secretjs.tx.broadcast([msg], {
gasLimit: 20_000,
gasPriceInFeeDenom: 0.25,
feeDenom: "uscrt",
});
The recommended way to integrate Keplr is by using window.keplr.getOfflineSignerOnlyAmino()
:
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
while (
!window.keplr ||
!window.getEnigmaUtils ||
!window.getOfflineSignerOnlyAmino
) {
await sleep(100);
}
const CHAIN_ID = "secret-4";
const SECRET_RPC = "https://rpc-secret.scrtlabs.com/secret-4/rpc/";
await window.keplr.enable(CHAIN_ID);
const keplrOfflineSigner = window.getOfflineSignerOnlyAmino(CHAIN_ID);
const [{ address: myAddress }] = await keplrOfflineSigner.getAccounts();
const secretjs = await SecretNetworkClient.create({
rpcUrl: SECRET_RPC,
chainId: SECRET_CHAIN_ID,
wallet: keplrOfflineSigner,
walletAddress: myAddress,
encryptionUtils: window.getEnigmaUtils(SECRET_CHAIN_ID),
});
// Note: Using `window.getEnigmaUtils` is optional, it will allow
// Keplr 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.
Although this is the legacy way of signing transactions on cosmos-sdk, it's still the most recommended for connecting to Keplr due to Ledger support & better UI on Keplr.
- 🟩 Looks good on Keplr
- 🟩 Supports users signing with Ledger
- 🟥 Doesn't support signing transactions with these Msgs:
- authz/MsgExec
- authz/MsgGrant
- authz/MsgRevoke
- feegrant/MsgGrantAllowance
- feegrant/MsgRevokeAllowance
- All IBC relayer Msgs:
- gov/MsgSubmitProposal/ClientUpdateProposal
- gov/MsgSubmitProposal/UpgradeProposal
- ibc_channel/MsgAcknowledgement
- ibc_channel/MsgChannelCloseConfirm
- ibc_channel/MsgChannelCloseInit
- ibc_channel/MsgChannelOpenAck
- ibc_channel/MsgChannelOpenConfirm
- ibc_channel/MsgChannelOpenInit
- ibc_channel/MsgChannelOpenTry
- ibc_channel/MsgRecvPacket
- ibc_channel/MsgTimeout
- ibc_channel/MsgTimeoutOnClose
- ibc_client/MsgCreateClient
- ibc_client/MsgSubmitMisbehaviour
- ibc_client/MsgUpdateClient
- ibc_client/MsgUpgradeClient
- ibc_connection/MsgConnectionOpenAck
- ibc_connection/MsgConnectionOpenConfirm
- ibc_connection/MsgConnectionOpenInit
- ibc_connection/MsgConnectionOpenTry
Note that ibc_transfer/MsgTransfer for sending funds across IBC is supported.
The new way of signing transactions on cosmos-sdk, it's more efficient but still doesn't have Ledger support, so it's most recommended for usage in apps that don't require signing transactions with Ledger.
- 🟥 Looks bad on Keplr
- 🟥 Doesn't support users signing with Ledger
- 🟩 Supports signing transactions with all types of Msgs
Currently this is equivalent to keplr.getOfflineSigner()
but may change at the discretion of the Keplr team.
v0.9.x
throughv0.16.x
supportedsecret-2
&secret-3
v0.17.x
supportssecret-4
v1.2.x
supportssecret-4
, corresponds tov1.2.x
of secretd
TODO
An offline wallet implementation, used to sign transactions. Usually we'd just want to pass it to SecretNetworkClient
.
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;
import { Wallet } from "secretjs";
const wallet = new Wallet();
const myAddress = wallet.address;
const myMnemonicPhrase = wallet.mnemonic;
A querier client can only send queries and get chain information. Access to all query types can be done via secretjs.query
.
import { SecretNetworkClient } from "secretjs";
// To create a readonly secret.js client, just pass in an RPC endpoint
const secretjs = await SecretNetworkClient.create({
rpcUrl: "https://rpc-secret.scrtlabs.com/secret-4/rpc/",
});
A signer client can broadcast transactions, send queries and get chain information.
Here in addition to secretjs.query
, there are also secretjs.tx
& secretjs.address
.
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;
// To create a signer secret.js client, also pass in a wallet
const secretjs = await SecretNetworkClient.create({
rpcUrl: "https://rpc.pulsar.griptapejs.com/",
wallet: wallet,
walletAddress: myAddress,
chainId: "pulsar-2",
});
Returns a transaction with a txhash. hash
is a 64 character upper-case hex string.
Returns all transactions that match a query.
To tell which events you want, you need to provide a query. query is a string, which has a form: condition AND condition ...
(no OR at the moment). Condition has a form: key operation operand
. key is a string with a restricted set of possible symbols (\t
, \n
, \r
, \
, (
, )
, "
, '
, =
, >
, <
are not allowed). Operation can be =
, <
, <=
, >
, >=
, CONTAINS
AND EXISTS
. Operand can be a string (escaped with single quotes), number, date or time.
Examples:
tx.hash = 'XYZ'
# single transactiontx.height = 5
# all txs of the fifth blockcreate_validator.validator = 'ABC'
# tx where validator ABC was created
Tendermint provides a few predefined keys: tx.hash
and tx.height
. You can provide additional event keys that were emitted during the transaction. All events are indexed by a composite key of the form {eventType}.{evenAttrKey}
. Multiple event types with duplicate keys are allowed and are meant to categorize unique and distinct events.
To create a query for txs where AddrA transferred funds: transfer.sender = 'AddrA'
See txsQuery
under https://secretjs.scrt.network/modules#Querier.
Returns account details based on address.
const { address, accountNumber, sequence } = await secretjs.query.auth.account({
address: myAddress,
});
Returns all existing accounts on the blockchain.
/// Get all accounts
const result = await secretjs.query.auth.accounts({});
Queries all x/auth parameters.
const {
params: {
maxMemoCharacters,
sigVerifyCostEd25519,
sigVerifyCostSecp256k1,
txSigLimit,
txSizeCostPerByte,
},
} = await secretjs.query.auth.params();
Returns list of authorizations, granted to the grantee by the granter.
Balance queries the balance of a single coin for a single account.
const { balance } = await secretjs.query.bank.balance({
address: myAddress,
denom: "uscrt",
});
AllBalances queries the balance of all coins for a single account.
TotalSupply queries the total supply of all coins.
SupplyOf queries the supply of a single coin.
Params queries the parameters of x/bank module.
DenomsMetadata queries the client metadata of a given coin denomination.
DenomsMetadata queries the client metadata for all registered coin denominations.
Get codeHash of a Secret Contract.
Get codeHash from a code id.
Get metadata of a Secret Contract.
Get all contracts that were instantiated from a code id.
Query a Secret Contract.
type Result = {
token_info: {
decimals: number;
name: string;
symbol: string;
total_supply: string;
};
};
const result = (await secretjs.query.compute.queryContract({
address: sScrtAddress,
codeHash: sScrtCodeHash, // optional but way faster
query: { token_info: {} },
})) as Result;
Get WASM bytecode and metadata for a code id.
const { codeInfo } = await secretjs.query.compute.code(codeId);
Query all contract codes on-chain.
Params queries params of the distribution module.
ValidatorOutstandingRewards queries rewards of a validator address.
ValidatorCommission queries accumulated commission for a validator.
ValidatorSlashes queries slash events of a validator.
DelegationRewards queries the total rewards accrued by a delegation.
DelegationTotalRewards queries the total rewards accrued by a each validator.
DelegatorValidators queries the validators of a delegator.
DelegatorWithdrawAddress queries withdraw address of a delegator.
CommunityPool queries the community pool coins.
DelegatorWithdrawAddress queries withdraw address of a delegator.
Evidence queries evidence based on evidence hash.
AllEvidence queries all evidence.
Allowance returns fee granted to the grantee by the granter.
Allowances returns all the grants for address.
Proposal queries proposal details based on ProposalID.
Proposals queries all proposals based on given status.
// Get all proposals
const { proposals } = await secretjs.query.gov.proposals({
proposalStatus: ProposalStatus.PROPOSAL_STATUS_UNSPECIFIED,
voter: "",
depositor: "",
});
Vote queries voted information based on proposalID, voterAddr.
Votes queries votes of a given proposal.
Params queries all parameters of the gov module.
Deposit queries single deposit information based proposalID, depositAddr.
const {
deposit: { amount },
} = await secretjs.query.gov.deposit({
depositor: myAddress,
proposalId: propId,
});
Deposits queries all deposits of a single proposal.
TallyResult queries the tally of a proposal vote.
Channel queries an IBC Channel.
Channels queries all the IBC channels of a chain.
ConnectionChannels queries all the channels associated with a connection end.
ChannelClientState queries for the client state for the channel associated with the provided channel identifiers.
ChannelConsensusState queries for the consensus state for the channel associated with the provided channel identifiers.
PacketCommitment queries a stored packet commitment hash.
PacketCommitments returns all the packet commitments hashes associated with a channel.
PacketReceipt queries if a given packet sequence has been received on the queried chain
PacketAcknowledgement queries a stored packet acknowledgement hash.
PacketAcknowledgements returns all the packet acknowledgements associated with a channel.
UnreceivedPackets returns all the unreceived IBC packets associated with a channel and sequences.
UnreceivedAcks returns all the unreceived IBC acknowledgements associated with a channel and sequences.
NextSequenceReceive returns the next receive sequence for a given channel.
ClientState queries an IBC light client.
ClientStates queries all the IBC light clients of a chain.
ConsensusState queries a consensus state associated with a client state at a given height.
ConsensusStates queries all the consensus state associated with a given client.
Status queries the status of an IBC client.
ClientParams queries all parameters of the ibc client.
UpgradedClientState queries an Upgraded IBC light client.
UpgradedConsensusState queries an Upgraded IBC consensus state.
Connection queries an IBC connection end.
Connections queries all the IBC connections of a chain.
ClientConnections queries the connection paths associated with a client state.
ConnectionClientState queries the client state associated with the connection.
ConnectionConsensusState queries the consensus state associated with the connection.
DenomTrace queries a denomination trace information.
DenomTraces queries all denomination traces.
Params queries all parameters of the ibc-transfer module.
Params returns the total set of minting parameters.
Inflation returns the current minting inflation value.
AnnualProvisions current minting annual provisions value.
Params queries a specific parameter of a module, given its subspace and key.
Returns the key used for transactions.
Returns the key used for registration.
Returns the encrypted seed for a registered node by public key.
Params queries the parameters of slashing module.
SigningInfo queries the signing info of given cons address.
SigningInfos queries signing info of all validators.
Validators queries all validators that match the given status.
// Get all validators
const { validators } = await secretjs.query.staking.validators({ status: "" });
Validator queries validator info for given validator address.
ValidatorDelegations queries delegate info for given validator.
ValidatorUnbondingDelegations queries unbonding delegations of a validator.
Delegation queries delegate info for given validator delegator pair.
UnbondingDelegation queries unbonding info for given validator delegator pair.
DelegatorDelegations queries all delegations of a given delegator address.
DelegatorUnbondingDelegations queries all unbonding delegations of a given delegator address.
Redelegations queries redelegations of given address.
DelegatorValidators queries all validators info for given delegator address.
DelegatorValidator queries validator info for given delegator validator pair.
HistoricalInfo queries the historical info for given height.
Pool queries the pool info.
Parameters queries the staking parameters.
GetNodeInfo queries the current node info.
GetSyncing queries node syncing.
GetLatestBlock returns the latest block.
GetBlockByHeight queries block for given height.
GetLatestValidatorSet queries latest validator-set.
GetValidatorSetByHeight queries validator-set at a given height.
CurrentPlan queries the current upgrade plan.
AppliedPlan queries a previously applied upgrade plan by its name.
UpgradedConsensusState queries the consensus state that will serve as a trusted kernel for the next version of this chain. It will only be stored at the last height of this chain.
ModuleVersions queries the list of module versions from state.
On a signer secret.js, secretjs.address
is the same as walletAddress
:
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;
// To create a signer secret.js client, also pass in a wallet
const secretjs = await SecretNetworkClient.create({
rpcUrl: "https://rpc.pulsar.griptapejs.com/",
wallet: wallet,
walletAddress: myAddress,
chainId: "pulsar-2",
});
const alsoMyAddress = secretjs.address;
On a signer secret.js, secretjs.tx
is used to broadcast transactions. Every function under secretjs.tx
can receive an optional TxOptions.
Used to send a complex transactions, which contains a list of messages. The messages are executed in sequence, and the transaction succeeds if all messages succeed.
For a list of all messages see: https://secretjs.scrt.network/interfaces/Msg
const addMinterMsg = new MsgExecuteContract({
sender: MY_ADDRESS,
contract: MY_NFT_CONTRACT,
codeHash: MY_NFT_CONTRACT_CODE_HASH, // optional but way faster
msg: { add_minters: { minters: [MY_ADDRESS] } },
sentFunds: [], // optional
});
const mintMsg = new MsgExecuteContract({
sender: MY_ADDRESS,
contract: MY_NFT_CONTRACT,
codeHash: 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",
},
},
},
},
sentFunds: [], // optional
});
const tx = await secretjs.tx.broadcast([addMinterMsg, mintMsg], {
gasLimit: 200_000,
});
MsgExec attempts to execute the provided messages using authorizations granted to the grantee. Each message should have only one signer corresponding to the granter of the authorization.
Input: MsgExecParams
MsgGrant is a request type for Grant method. It declares authorization to the grantee on behalf of the granter with the provided expiration time.
Input: MsgGrantParams
MsgRevoke revokes any authorization with the provided sdk.Msg type on the granter's account with that has been granted to the grantee.
Input: MsgRevokeParams
MsgMultiSend represents an arbitrary multi-in, multi-out send message.
Input: MsgMultiSendParams
const tx = await secretjs.tx.bank.multiSend(
{
inputs: [
{
address: myAddress,
coins: [{ denom: "uscrt", amount: "2" }],
},
],
outputs: [
{
address: alice,
coins: [{ denom: "uscrt", amount: "1" }],
},
{
address: bob,
coins: [{ denom: "uscrt", amount: "1" }],
},
],
},
{
gasLimit: 20_000,
},
);
MsgSend represents a message to send coins from one account to another.
Input: MsgSendParams
const tx = await secretjs.tx.bank.send(
{
fromAddress: myAddress,
toAddress: alice,
amount: [{ denom: "uscrt", amount: "1" }],
},
{
gasLimit: 20_000,
},
);
Upload a compiled contract to Secret Network
Input: MsgStoreCodeParams
const tx = await secretjs.tx.compute.storeCode(
{
sender: myAddress,
wasmByteCode: 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,
);
Instantiate a contract from code id
Input: MsgInstantiateContractParams
const tx = await secretjs.tx.compute.instantiateContract(
{
sender: myAddress,
codeId: codeId,
codeHash: codeHash, // optional but way faster
initMsg: {
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",
initFunds: [], // optional
},
{
gasLimit: 100_000,
},
);
const contractAddress = tx.arrayLog.find(
(log) => log.type === "message" && log.key === "contract_address",
).value;
Execute a function on a contract
Input: MsgExecuteContractParams
const tx = await secretjs.tx.compute.executeContract(
{
sender: myAddress,
contract: contractAddress,
codeHash: codeHash, // optional but way faster
msg: {
transfer: {
recipient: bob,
amount: "1",
},
},
sentFunds: [], // optional
},
{
gasLimit: 100_000,
},
);
MsgVerifyInvariant represents a message to verify a particular invariance.
Input: MsgVerifyInvariantParams
MsgFundCommunityPool allows an account to directly fund the community pool.
Input: MsgFundCommunityPoolParams
const tx = await secretjs.tx.distribution.fundCommunityPool(
{
depositor: myAddress,
amount: [{ amount: "1", denom: "uscrt" }],
},
{
gasLimit: 20_000,
},
);
MsgSetWithdrawAddress sets the withdraw address for a delegator (or validator self-delegation).
Input: MsgSetWithdrawAddressParams
const tx = await secretjs.tx.distribution.setWithdrawAddress(
{
delegatorAddress: mySelfDelegatorAddress,
withdrawAddress: myOtherAddress,
},
{
gasLimit: 20_000,
},
);
MsgWithdrawDelegatorReward represents delegation withdrawal to a delegator from a single validator.
Input: MsgWithdrawDelegatorRewardParams
const tx = await secretjs.tx.distribution.withdrawDelegatorReward(
{
delegatorAddress: myAddress,
validatorAddress: someValidatorAddress,
},
{
gasLimit: 20_000,
},
);
MsgWithdrawValidatorCommission withdraws the full commission to the validator address.
Input: MsgWithdrawValidatorCommissionParams
const tx = await secretjs.tx.distribution.withdrawValidatorCommission(
{
validatorAddress: myValidatorAddress,
},
{
gasLimit: 20_000,
},
);
Or a better one:
const tx = await secretjs.tx.broadcast(
[
new MsgWithdrawDelegatorReward({
delegatorAddress: mySelfDelegatorAddress,
validatorAddress: myValidatorAddress,
}),
new MsgWithdrawValidatorCommission({
validatorAddress: myValidatorAddress,
}),
],
{
gasLimit: 30_000,
},
);
MsgSubmitEvidence represents a message that supports submitting arbitrary evidence of misbehavior such as equivocation or counterfactual signing.
Input: MsgSubmitEvidenceParams
MsgGrantAllowance adds permission for Grantee to spend up to Allowance of fees from the account of Granter.
Input: MsgGrantAllowanceParams
MsgRevokeAllowance removes any existing Allowance from Granter to Grantee.
Input: MsgRevokeAllowanceParams
MsgDeposit defines a message to submit a deposit to an existing proposal.
Input: MsgDepositParams
const tx = await secretjs.tx.gov.deposit(
{
depositor: myAddress,
proposalId: someProposalId,
amount: [{ amount: "1", denom: "uscrt" }],
},
{
gasLimit: 20_000,
},
);
MsgSubmitProposal defines an sdk.Msg type that supports submitting arbitrary proposal Content.
Input: MsgSubmitProposalParams
const tx = await secretjs.tx.gov.submitProposal(
{
type: ProposalType.TextProposal,
proposer: myAddress,
initialDeposit: [{ amount: "10000000", denom: "uscrt" }],
content: {
title: "Hi",
description: "Let's vote on this",
},
},
{
gasLimit: 50_000,
},
);
const proposalId = Number(
tx.arrayLog.find(
(log) => log.type === "submit_proposal" && log.key === "proposal_id",
).value,
);
MsgVote defines a message to cast a vote.
Input: MsgVoteParams
const tx = await secretjs.tx.gov.vote(
{
voter: myAddress,
proposalId: someProposalId,
option: VoteOption.VOTE_OPTION_YES,
},
{
gasLimit: 50_000,
},
);
MsgVoteWeighted defines a message to cast a vote, with an option to split the vote.
Input: MsgVoteWeightedParams
// vote yes with 70% of my power
const tx = await secretjs.tx.gov.voteWeighted(
{
voter: myAddress,
proposalId: someProposalId,
options: [
// weights must sum to 1.0
{ weight: 0.7, option: VoteOption.VOTE_OPTION_YES },
{ weight: 0.3, option: VoteOption.VOTE_OPTION_ABSTAIN },
],
},
{
gasLimit: 50_000,
},
);
MsgTransfer defines a msg to transfer fungible tokens (i.e Coins) between ICS20 enabled chains. See ICS Spec here: https://github.com/cosmos/ics/tree/master/spec/ics-020-fungible-token-transfer#data-structures
Input: MsgTransferParams
MsgUnjail defines a message to release a validator from jail.
Input: MsgUnjailParams
const tx = await secretjs.tx.slashing.unjail(
{
validatorAddr: mValidatorsAddress,
},
{
gasLimit: 50_000,
},
);
MsgBeginRedelegate defines an SDK message for performing a redelegation of coins from a delegator and source validator to a destination validator.
Input: MsgBeginRedelegateParams
const tx = await secretjs.tx.staking.beginRedelegate(
{
delegatorAddress: myAddress,
validatorSrcAddress: someValidator,
validatorDstAddress: someOtherValidator,
amount: { amount: "1", denom: "uscrt" },
},
{
gasLimit: 50_000,
},
);
MsgCreateValidator defines an SDK message for creating a new validator.
Input: MsgCreateValidatorParams
const tx = await secretjs.tx.staking.createValidator(
{
selfDelegatorAddress: myAddress,
commission: {
maxChangeRate: 0.01, // can change +-1% every 24h
maxRate: 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",
securityContact: "[email protected]",
details: "We are good",
},
pubkey: toBase64(new Uint8Array(32).fill(1)), // validator's pubkey, to sign on validated blocks
minSelfDelegation: "1", // uscrt
initialDelegation: { amount: "1", denom: "uscrt" },
},
{
gasLimit: 100_000,
},
);
MsgDelegate defines an SDK message for performing a delegation of coins from a delegator to a validator.
Input: MsgDelegateParams
const tx = await secretjs.tx.staking.delegate(
{
delegatorAddress: myAddress,
validatorAddress: someValidatorAddress,
amount: { amount: "1", denom: "uscrt" },
},
{
gasLimit: 50_000,
},
);
MsgEditValidator defines an SDK message for editing an existing validator.
Input: MsgEditValidatorParams
const tx = await secretjs.tx.staking.editValidator(
{
validatorAddress: myValidatorAddress,
description: {
// To edit even one item in "description you have to re-input everything
moniker: "papaya",
identity: "banana",
website: "watermelon.com",
securityContact: "[email protected]",
details: "We are the banana papaya validator yay!",
},
minSelfDelegation: "2",
commissionRate: 0.04, // 4%, commission cannot be changed more than once in 24h
},
{
gasLimit: 5_000_000,
},
);
MsgUndelegate defines an SDK message for performing an undelegation from a delegate and a validator
Input: MsgUndelegateParams
const tx = await secretjs.tx.staking.undelegate(
{
delegatorAddress: myAddress,
validatorAddress: someValidatorAddress,
amount: { amount: "1", denom: "uscrt" },
},
{
gasLimit: 50_000,
},
);