The JavaScript SDK for Secret Network
Table of Contents
- Key Features
- Beta Version Notice
- Installation
- Usage Examples
- Sending Queries
- Broadcasting Transactions
- Integrations
- MetaMask
- Keplr Wallet
SignerOnlyAminovsSignervsSignerAuto
- Fina Wallet
- Deep linking
- Leap Cosmos Wallet
- StarShell Wallet
- Ledger Wallet
- API
- Wallet
- Importing account from mnemonic
- Generating a random account
- SecretNetworkClient
- Querier secret.js
- Signer secret.js
secretjs.querysecretjs.addresssecretjs.tx- Resolve IBC Responses
- Helper Functions
pubkeyToAddress()base64PubkeyToAddress()selfDelegatorAddressToValidatorAddress()validatorAddressToSelfDelegatorAddress()tendermintPubkeyToValconsAddress()base64TendermintPubkeyToValconsAddress()ibcDenom()stringToCoins()/coinsFromString()stringToCoins()/coinFromString()validateAddress()
- Wallet
Key Features
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.
Beta Version Notice
This library is still in beta, APIs may break. Beta testers are welcome!
See project board for list of existing/missing features.
Installation
Using npm:
Using yarn:
Directly in the browser:
<script>
const { SecretNetworkClient } = window.secretjs;
script>
Additional step for React Native:
Follow the instruction of react-native-get-random-values package
Usage Examples
Note: Public LCD endpoints can be found in https://github.com/scrtlabs/api-registry for both mainnet and testnet.
For a lot more usage examples refer to the tests.
Sending Queries
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!`);
Broadcasting Transactions
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",
});
Integrations
MetaMask
//@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,
});
Notes:
- MetaMask supports mobile!
- MetaMask supports Ledger.
- You might want to pass
encryptionSeedtoSecretNetworkClient.create()to use the same encryption key for the user across sessions. This value should be a true random 32 byte number that is stored securely in your app, such that only the user can decrypt it. This can also be asha256(user_password)but might impair UX. - See Keplr's
getOfflineSignerOnlyAmino()for list of unsupported transactions.
Keplr Wallet
The recommended way of integrating Keplr is by using window.keplr.getOfflineSigner():
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,
walletAddress: myAddress,
encryptionUtils: window.keplr.getEnigmaUtils(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.
Notes:
- No mobile support yet.
- Keplr supports Ledger.
- By using
encryptionUtilsyou let Keplr handle user encryption keys for you, which allows you to easily decrypt transactions across sessions.
Links:
Signer vs SignerAuto vs SignerOnlyAmino
TL;DR:
getOfflineSigner(): The recommended way. Efficient, supports all transaction types except Ledger.getOfflineSignerAuto(): Automatically selects the best signer based on the account type (Ledger or not).getOfflineSignerOnlyAmino(): The legacy way. Recommended only for Ledger users.
window.keplr.getOfflineSigner()
The recommended way of signing transactions on cosmos-sdk. Efficient and supports all transaction types except those requiring a Ledger.
- Efficient and supports all types of
Msgs - Doesn't support users signing with Ledger
- Looks bad on Keplr UI
window.keplr.getOfflineSignerAuto()
Automatically chooses the best signing method based on the user's Keplr account:
-
For Ledger users, uses
window.keplr.getOfflineSignerOnlyAmino(). -
For non-Ledger users, uses
window.keplr.getOfflineSigner(). -
Smart and adaptable
-
Provides flexibility for both Ledger and non-Ledger accounts
window.keplr.getOfflineSignerOnlyAmino()
The legacy and non-recommended way of signing transactions on cosmos-sdk. Suitable only for Ledger users due to its limited transaction support and better UI.
- Looks good on Keplr
- Supports users signing with Ledger
- Doesn't support signing these transactions:
- Every tx type under
ibc_client,ibc_connection, andibc_channel(e.g., IBC relaying) - gov/MsgSubmitProposal/ClientUpdateProposal
- gov/MsgSubmitProposal/UpgradeProposal
- Every tx type under
Note that ibc_transfer/MsgTransfer for sending funds across IBC is supported.
Fina Wallet
Fina implements the Keplr API, so the above Keplr docs applies. If you support Keplr, your app will also work on the Fina Wallet mobile app. This works because the Fina Wallet mobile app has webview to which it injects its objects under window.keplr.
Deep linking
Fina supports deep linking into its in-app browser.
Example1: fina://wllet/dapps?network=secret-4&url=https%3A%2F%2Fdash.scrt.network
Example2:
If a user accessed your app using a regular mobile browser, you can open your app in the Fina in-app browser using this code:
urlSearchParams.append("network", "secret-4");
urlSearchParams.append("url", window.location.href);
window.open(`fina://wllet/dapps?${urlSearchParams.toString()}`, "_blank");
Links:
Leap Cosmos Wallet
The recommended way of integrating Leap is by using window.leap.getOfflineSigner():
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.
Links:
StarShell Wallet
StarShell implements the Keplr API, so the above Keplr docs applies. If you support Keplr, your app will also work on StarShell wallet. This works because StarShell wallet asks the user to turn off Keplr and then overrides window.keplr with its objects.
Links:
Ledger Wallet
@cosmjs/ledger-amino can be used to sign transactions with a Ledger wallet running the Cosmos app.
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,
});
Notes:
- Use the appropriate
hw-transportpackage for your environment (Node or Browser) - The Ledger Cosmos app only supports coin type 118
- You might want to pass
encryptionSeedtoSecretNetworkClient.create()to use the same encryption key for the user across sessions. This value should be a true random 32 byte number that is stored securly in your app, such that only the user can decrypt it. This can also be asha256(user_password)but might impair UX. - See Keplr's
getOfflineSignerOnlyAmino()for list of unsupported transactions.
Links:
API
Wallet
An offline wallet implementation, used to sign transactions. Usually we'd just want to pass it to SecretNetworkClient.
Importing account from mnemonic
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;
Generating a random account
const wallet = new Wallet();
const myAddress = wallet.address;
const myMnemonicPhrase = wallet.mnemonic;
SecretNetworkClient
Querier secret.js
A querier client can only send queries and get chain information. Access to all query types can be done via secretjs.query.
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,
});
Signer secret.js
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.
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,
});
secretjs.query
secretjs.query.node.status()
Queries the node status
secretjs.query.getTx(hash)
Returns a transaction with a txhash. hash is a 64 character upper-case hex string.
secretjs.query.txsQuery(query)
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.
secretjs.query.auth.account()
Returns account details based on address.
address: myAddress,
});
secretjs.query.auth.accounts()
Returns all existing accounts on the blockchain.
const result = await secretjs.query.auth.accounts({});
secretjs.query.auth.params()
Queries all x/auth parameters.
params: {
maxMemoCharacters,
sigVerifyCostEd25519,
sigVerifyCostSecp256k1,
txSigLimit,
txSizeCostPerByte,
},
} = await secretjs.query.auth.params({});
secretjs.query.authz.grants()
Returns list of authorizations, granted to the grantee by the granter.
secretjs.query.bank.balance()
Balance queries the balance of a single coin for a single account.
address: myAddress,
denom: "uscrt",
});
secretjs.query.bank.allBalances()
AllBalances queries the balance of all coins for a single account.
secretjs.query.bank.totalSupply()
TotalSupply queries the total supply of all coins.
secretjs.query.bank.supplyOf()
SupplyOf queries the supply of a single coin.
secretjs.query.bank.params()
Params queries the parameters of x/bank module.
secretjs.query.bank.denomMetadata()
DenomsMetadata queries the client metadata of a given coin denomination.
secretjs.query.bank.denomsMetadata()
DenomsMetadata queries the client metadata for all registered coin denominations.
secretjs.query.bank.spendableBalanceByDenom()
Queries the spendable balance of a single denom for a single account.
secretjs.query.bank.denomMetadataByQueryString()
Executes the DenomMetadataByQueryString RPC method
secretjs.query.bank.denomOwners()
Queries for all account addresses that own a particular token denomination.
secretjs.query.bank.sendEnabled()
Queries for send enabled entries that have been specifically set.
secretjs.query.bank.denomOwnersByQuery()
Executes the DenomOwnersByQuery RPC method
secretjs.query.auth.moduleAccounts()
Queries all module accounts
secretjs.query.auth.bech32Prefix()
Query the chain bech32 prefix (if applicable)
secretjs.query.auth.addressBytesToString()
Transforms an address bytes to string
secretjs.query.auth.addressStringToBytes()
Transforms an address string to bytes
secretjs.query.auth.accountAddressByID()
Queries account address by account number
secretjs.query.auth.accountInfo()
Queries account info which is common to all account types.
secretjs.query.compute.codeHashByContractAddress()
Get codeHash of a Secret Contract.
secretjs.query.compute.codeHashByCodeId()
Get codeHash from a code id.
secretjs.query.compute.contractInfo()
Get metadata of a Secret Contract.
secretjs.query.compute.contractsByCode()
Get all contracts that were instantiated from a code id.
secretjs.query.compute.queryContract()
Query a Secret Contract.
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;
secretjs.query.compute.code()
Get WASM bytecode and metadata for a code id.
secretjs.query.compute.codes()
Query all contract codes on-chain.
secretjs.query.compute.contractHistory()
Get upgrades history of a Secret Contract.
secretjs.query.distribution.params()
Params queries params of the distribution module.
secretjs.query.distribution.validatorOutstandingRewards()
ValidatorOutstandingRewards queries rewards of a validator address.
secretjs.query.distribution.validatorCommission()
ValidatorCommission queries accumulated commission for a validator.
secretjs.query.distribution.validatorSlashes()
ValidatorSlashes queries slash events of a validator.
secretjs.query.distribution.delegationRewards()
DelegationRewards queries the total rewards accrued by a delegation.
secretjs.query.distribution.delegationTotalRewards()
DelegationTotalRewards queries the total rewards accrued by a each validator.
secretjs.query.distribution.delegatorValidators()
DelegatorValidators queries the validators of a delegator.
secretjs.query.distribution.delegatorWithdrawAddress()
DelegatorWithdrawAddress queries withdraw address of a delegator.
secretjs.query.distribution.communityPool()
CommunityPool queries the community pool coins.
secretjs.query.distribution.foundationTax()
DelegatorWithdrawAddress queries withdraw address of a delegator.
secretjs.query.distribution.validatorDistributionInfo()
Queries validator distribution information
secretjs.query.evidence.evidence()
Evidence queries evidence based on evidence hash.
secretjs.query.evidence.allEvidence()
AllEvidence queries all evidence.
secretjs.query.feegrant.allowance()
Allowance returns fee granted to the grantee by the granter.
secretjs.query.feegrant.allowances()
Allowances returns all the grants for address.
secretjs.query.gov.proposal()
Proposal queries proposal details based on ProposalID.
secretjs.query.gov.proposals()
Proposals queries all proposals based on given status.
const { proposals } = await secretjs.query.gov.proposals({
proposal_status: ProposalStatus.PROPOSAL_STATUS_UNSPECIFIED,
voter: "",
depositor: "",
});
secretjs.query.gov.vote()
Vote queries voted information based on proposalID, voterAddr.
secretjs.query.gov.votes()
Votes queries votes of a given proposal.
secretjs.query.gov.params()
Params queries all parameters of the gov module.
secretjs.query.gov.deposit()
Deposit queries single deposit information based proposalID, depositAddr.
deposit: { amount },
} = await secretjs.query.gov.deposit({
depositor: myAddress,
proposalId: propId,
});
secretjs.query.gov.deposits()
Deposits queries all deposits of a single proposal.
secretjs.query.gov.tallyResult()
TallyResult queries the tally of a proposal vote.
secretjs.query.ibc_channel.channel()
Channel queries an IBC Channel.
secretjs.query.ibc_channel.channels()
Channels queries all the IBC channels of a chain.
secretjs.query.ibc_channel.connectionChannels()
ConnectionChannels queries all the channels associated with a connection end.
secretjs.query.ibc_channel.channelClientState()
ChannelClientState queries for the client state for the channel associated with the provided channel identifiers.
secretjs.query.ibc_channel.channelConsensusState()
ChannelConsensusState queries for the consensus state for the channel associated with the provided channel identifiers.
secretjs.query.ibc_channel.packetCommitment()
PacketCommitment queries a stored packet commitment hash.
secretjs.query.ibc_channel.packetCommitments()
PacketCommitments returns all the packet commitments hashes associated with a channel.
secretjs.query.ibc_channel.packetReceipt()
PacketReceipt queries if a given packet sequence has been received on the queried chain
secretjs.query.ibc_channel.packetAcknowledgement()
PacketAcknowledgement queries a stored packet acknowledgement hash.
secretjs.query.ibc_channel.packetAcknowledgements()
PacketAcknowledgements returns all the packet acknowledgements associated with a channel.
secretjs.query.ibc_channel.unreceivedPackets()
UnreceivedPackets returns all the unreceived IBC packets associated with a channel and sequences.
secretjs.query.ibc_channel.unreceivedAcks()
UnreceivedAcks returns all the unreceived IBC acknowledgements associated with a channel and sequences.
secretjs.query.ibc_channel.nextSequenceReceive()
NextSequenceReceive returns the next receive sequence for a given channel.
secretjs.query.ibc_channel.channelParams()
Queries the current ibc channel parameters
secretjs.query.ibc_channel.nextSequenceSend()
Queries the next sequence send for a given channel
secretjs.query.ibc_channel.upgradeError()
Queries the upgrade error for a given channel
secretjs.query.ibc_channel.upgrade()
Queries the upgrade for a given channel
secretjs.query.ibc_client.clientState()
ClientState queries an IBC light client.
secretjs.query.ibc_client.clientStates()
ClientStates queries all the IBC light clients of a chain.
secretjs.query.ibc_client.consensusState()
ConsensusState queries a consensus state associated with a client state at a given height.
secretjs.query.ibc_client.consensusStates()
ConsensusStates queries all the consensus state associated with a given client.
secretjs.query.ibc_client.clientStatus()
Status queries the status of an IBC client.
secretjs.query.ibc_client.clientParams()
ClientParams queries all parameters of the ibc client.
secretjs.query.ibc_client.upgradedClientState()
UpgradedClientState queries an Upgraded IBC light client.
secretjs.query.ibc_client.upgradedConsensusState()
UpgradedConsensusState queries an Upgraded IBC consensus state.
secretjs.query.ibc_connection.connection()
Connection queries an IBC connection end.
secretjs.query.ibc_connection.connections()
Connections queries all the IBC connections of a chain.
secretjs.query.ibc_connection.clientConnections()
ClientConnections queries the connection paths associated with a client state.
secretjs.query.ibc_connection.connectionClientState()
ConnectionClientState queries the client state associated with the connection.
secretjs.query.ibc_connection.connectionConsensusState()
ConnectionConsensusState queries the consensus state associated with the connection.
secretjs.query.ibc_connection.connectionParams()
Returns the current ibc connection params
secretjs.query.ibc_transfer.denomTrace()
DenomTrace queries a denomination trace information.
secretjs.query.ibc_transfer.denomTraces()
DenomTraces queries all denomination traces.
secretjs.query.ibc_transfer.params()
Params queries all parameters of the ibc-transfer module.
secretjs.query.ibc_transfer.totalEscrowForDenom()
Returns the total amount of tokens in escrow for a denom
secretjs.query.mint.params()
Params returns the total set of minting parameters.
secretjs.query.mint.inflation()
Inflation returns the current minting inflation value.
secretjs.query.mint.annualProvisions()
AnnualProvisions current minting annual provisions value.
secretjs.query.params.params()
Params queries a specific parameter of a module, given its subspace and key.
secretjs.query.params.subspaces()
Query for all registered subspaces and all keys for a subspace
secretjs.query.registration.txKey()
Returns the key used for transactions.
secretjs.query.registration.registrationKey()
Returns the key used for registration.
secretjs.query.registration.encryptedSeed()
Returns the encrypted seed for a registered node by public key.