Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Learn how to connect Secret Network contracts to a frontend.
Secret.js a JavaScript SDK for writing applications that interact with the Secret Network blockchain. Key features include:
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.
You can find the full version of the docs here.
Refer to the reference SecretJS Templates to review code implementations of SecretJS such as:
Connecting to Secret Network
Creating account using SecretJS
Query Secret Network
Submitting transactions
Using contracts
Wallets
SNIP-20 tokens
Consuming websocket contract events
See here for a fullstack dApp tutorial that uses SecretJS.
SecretJS usage examples.
Learn how to send messages with SecretJS.
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
Used to simulate a complex transactions, which contains a list of messages, without broadcasting it to the chain. Can be used to get a gas estimation or to see the output without actually committing a transaction on-chain.
The input should be exactly how you'd use it in secretjs.tx.broadcast()
, except that you don't have to pass in gasLimit
, gasPriceInFeeDenom
& feeDenom
.
Notes:
On mainnet, it's recommended to not simulate every transaction as this can burden your node provider. Instead, use this while testing to determine the gas limit for each of your app's transactions, then in production use hard-coded values.
Gas estimation is known to be a bit off, so you might need to adjust it a bit before broadcasting.
MsgInstantiateContract
, MsgExecuteContract
, MsgMigrateContract
, MsgUpdateAdmin
& MsgClearAdmin
simulations are not supported for security reasons.
Used to sign transactions independently from the broadcast process. This is useful when you want to keep your seed safe and sign transactions offline.
secretjs.tx.broadcastSignedTx()
Used to send offline signed transactions.
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
secretjs.tx.authz.exec.simulate()
Simulates execution without sending a transactions. Input is exactly like the parent function. For more info see secretjs.tx.simulate()
.
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
secretjs.tx.authz.grant.simulate()
Simulates execution without sending a transactions. Input is exactly like the parent function. For more info see secretjs.tx.simulate()
.
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
secretjs.tx.authz.revoke.simulate()
Simulates execution without sending a transactions. Input is exactly like the parent function. For more info see secretjs.tx.simulate()
.
MsgMultiSend represents an arbitrary multi-in, multi-out send message.
Input: MsgMultiSendParams
Simulates execution without sending a transactions. Input is exactly like the parent function. For more info see secretjs.tx.simulate()
.
MsgSend represents a message to send coins from one account to another.
Input: MsgSendParams
secretjs.tx.bank.send.simulate()
Simulates execution without sending a transactions. Input is exactly like the parent function. For more info see secretjs.tx.simulate()
.
secretjs.tx.compute.storeCode()
Upload a compiled contract to Secret Network
Input: MsgStoreCodeParams
secretjs.tx.compute.storeCode.simulate()
Simulates execution without sending a transactions. Input is exactly like the parent function. For more info see secretjs.tx.simulate()
.
secretjs.tx.compute.instantiateContract()
Instantiate a contract from code id
Input: [MsgInstantiateContractParams](https://secretjs.scrt.network/interfaces/MsgInstanti
ateContractParams)
secretjs.tx.compute.instantiateContract.simulate()
Simulates execution without sending a transactions. Input is exactly like the parent function. For more info see secretjs.tx.simulate()
.
WARNING: secretjs.tx.compute
simulations are not supported for security reasons.
secretjs.tx.compute.executeContract()
Execute a function on a contract
Input: MsgExecuteContractParams
secretjs.tx.compute.executeContract.simulate()
Simulates execution without sending a transactions. Input is exactly like the parent function. For more info see secretjs.tx.simulate()
.
WARNING: secretjs.tx.compute
simulations are not supported for security reasons.
secretjs.tx.compute.migrateContract()
Migrate a contract's code while keeping the same address. Invokes the migrate()
function on the new code.
Input: MsgMigrateContractParams
secretjs.tx.compute.migrateContract.simulate()
Simulates execution without sending a transactions. Input is exactly like the parent function. For more info see secretjs.tx.simulate()
.
WARNING: secretjs.tx.compute
simulations are not supported for security reasons.
secretjs.tx.compute.updateAdmin()
Update a contract's admin.
Input: MsgUpdateAdminParams
secretjs.tx.compute.updateAdmin.simulate()
Simulates execution without sending a transactions. Input is exactly like the parent function. For more info see secretjs.tx.simulate()
.
WARNING: secretjs.tx.compute
simulations are not supported for security reasons.
secretjs.tx.compute.clearAdmin()
clear a contract's admin.
Input: MsgClearAdminParams
secretjs.tx.compute.clearAdmin.simulate()
Simulates execution without sending a transactions. Input is exactly like the parent function. For more info see secretjs.tx.simulate()
.
WARNING: secretjs.tx.compute
simulations are not supported for security reasons.
secretjs.tx.crisis.verifyInvariant()
MsgVerifyInvariant represents a message to verify a particular invariance.
Input: MsgVerifyInvariantParams
secretjs.tx.crisis.verifyInvariant.simulate()
Simulates execution without sending a transactions. Input is exactly like the parent function. For more info see secretjs.tx.simulate()
.
secretjs.tx.distribution.fundCommunityPool()
MsgFundCommunityPool allows an account to directly fund the community pool.
Input: MsgFundCommunityPoolParams
secretjs.tx.distribution.fundCommunityPool.simulate()
Simulates execution without sending a transactions. Input is exactly like the parent function. For more info see secretjs.tx.simulate()
.
secretjs.tx.distribution.setWithdrawAddress()
MsgSetWithdrawAddress sets the withdraw address for a delegator (or validator self-delegation).
Input: MsgSetWithdrawAddressParams
secretjs.tx.distribution.setWithdrawAddress.simulate()
Simulates execution without sending a transactions. Input is exactly like the parent function. For more info see secretjs.tx.simulate()
.
secretjs.tx.distribution.withdrawDelegatorReward()
MsgWithdrawDelegatorReward represents delegation withdrawal to a delegator from a single validator.
Input: MsgWithdrawDelegatorRewardParams
secretjs.tx.distribution.withdrawDelegatorReward.simulate()
Simulates execution without sending a transactions. Input is exactly like the parent function. For more info see secretjs.tx.simulate()
.
secretjs.tx.distribution.withdrawValidatorCommission()
MsgWithdrawValidatorCommission withdraws the full commission to the validator address.
Input: MsgWithdrawValidatorCommissionParams
Or a better one:
secretjs.tx.distribution.withdrawValidatorCommission.simulate()
Simulates execution without sending a transactions. Input is exactly like the parent function. For more info see secretjs.tx.simulate()
.
secretjs.tx.evidence.submitEvidence()
MsgSubmitEvidence represents a message that supports submitting arbitrary evidence of misbehavior such as equivocation or counterfactual signing.
Input: MsgSubmitEvidenceParams
secretjs.tx.evidence.submitEvidence.simulate()
Simulates execution without sending a transactions. Input is exactly like the parent function. For more info see secretjs.tx.simulate()
.
secretjs.tx.feegrant.grantAllowance()
MsgGrantAllowance adds permission for Grantee to spend up to Allowance of fees from the account of Granter.
Input: MsgGrantAllowanceParams
secretjs.tx.feegrant.grantAllowance.simulate()
Simulates execution without sending a transactions. Input is exactly like the parent function. For more info see secretjs.tx.simulate()
.
secretjs.tx.feegrant.revokeAllowance()
MsgRevokeAllowance removes any existing Allowance from Granter to Grantee.
Input: MsgRevokeAllowanceParams
secretjs.tx.feegrant.revokeAllowance.simulate()
Simulates execution without sending a transactions. Input is exactly like the parent function. For more info see secretjs.tx.simulate()
.
MsgDeposit defines a message to submit a deposit to an existing proposal.
Input: MsgDepositParams
secretjs.tx.gov.deposit.simulate()
Simulates execution without sending a transactions. Input is exactly like the parent function. For more info see secretjs.tx.simulate()
.
secretjs.tx.gov.submitProposal()
MsgSubmitProposal defines an sdk.Msg type that supports submitting arbitrary proposal Content.
Input: MsgSubmitProposalParams
secretjs.tx.gov.submitProposal.simulate()
Simulates execution without sending a transactions. Input is exactly like the parent function. For more info see secretjs.tx.simulate()
.
MsgVote defines a message to cast a vote.
Input: MsgVoteParams
secretjs.tx.gov.vote.simulate()
Simulates execution without sending a transactions. Input is exactly like the parent function. For more info see secretjs.tx.simulate()
.
secretjs.tx.gov.voteWeighted()
MsgVoteWeighted defines a message to cast a vote, with an option to split the vote.
Input: MsgVoteWeightedParams
secretjs.tx.gov.voteWeighted.simulate()
Simulates execution without sending a transactions. Input is exactly like the parent function. For more info see secretjs.tx.simulate()
.
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
secretjs.tx.ibc.transfer.simulate()
Simulates execution without sending a transactions. Input is exactly like the parent function. For more info see secretjs.tx.simulate()
.
MsgUnjail defines a message to release a validator from jail.
Input: MsgUnjailParams
secretjs.tx.slashing.unjail.simulate()
Simulates execution without sending a transactions. Input is exactly like the parent function. For more info see secretjs.tx.simulate()
.
secretjs.tx.staking.beginRedelegate()
MsgBeginRedelegate defines an SDK message for performing a redelegation of coins from a delegator and source validator to a destination validator.
Input: MsgBeginRedelegateParams
secretjs.tx.staking.beginRedelegate.simulate()
Simulates execution without sending a transactions. Input is exactly like the parent function. For more info see secretjs.tx.simulate()
.
secretjs.tx.staking.createValidator()
MsgCreateValidator defines an SDK message for creating a new validator.
Input: MsgCreateValidatorParams
secretjs.tx.staking.createValidator.simulate()
Simulates execution without sending a transactions. Input is exactly like the parent function. For more info see secretjs.tx.simulate()
.
secretjs.tx.staking.delegate()
MsgDelegate defines an SDK message for performing a delegation of coins from a delegator to a validator.
Input: MsgDelegateParams
secretjs.tx.staking.delegate.simulate()
Simulates execution without sending a transactions. Input is exactly like the parent function. For more info see secretjs.tx.simulate()
.
secretjs.tx.staking.editValidator()
MsgEditValidator defines an SDK message for editing an existing validator.
Input: MsgEditValidatorParams
secretjs.tx.staking.editValidator.simulate()
Simulates execution without sending a transactions. Input is exactly like the parent function. For more info see secretjs.tx.simulate()
.
secretjs.tx.staking.undelegate()
MsgUndelegate defines an SDK message for performing an undelegation from a delegate and a validator
Input: MsgUndelegateParams
secretjs.tx.staking.undelegate.simulate()
Simulates execution without sending a transactions. Input is exactly like the parent function. For more info see secretjs.tx.simulate()
.
Learn how to install and use SecretJS.
In this tutorial you will learn how to use Secret.js to connect a web3 wallet, upload a contract, instantiate a contract, execute a contract, and query a contract, amongst other use cases! For the complete Secret.js docs, see here.
All of the following examples use the pulsar-3
testnet with LCD endpoint https://api.pulsar3.scrttestnet.com
.
Public LCD endpoints can be found here for both mainnet and testnet.
Create a package.json file:
Then install secretJS:
Learn how to integrate various web3 wallets with SecretJS.
Notes:
MetaMask supports mobile!
MetaMask supports Ledger.
Secretjs MetaMaskWallet
will automatically prompt the user to sign a personal_sign
message, which is used to recover the users public key and derive the user's Secret Network address.
You might want to pass encryptionSeed
to SecretNetworkClient.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 a sha256(user_password)
but might impair UX.
The recommended way of integrating Keplr is by using window.keplr.getOfflineSignerOnlyAmino()
:
Notes:
No mobile support yet.
Keplr supports Ledger.
By using encryptionUtils
you let Keplr handle user encryption keys for you, which allows you to easily decrypt transactions across sessions.
Links:
TLDR:
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 these transactions:
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
If the connected Keplr account uses Ledger, returns window.keplr.getOfflineSignerOnlyAmino()
.
Otherwise returns window.keplr.getOfflineSigner()
.
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:
Links:
The recommended way of integrating Leap is by using window.leap.getOfflineSignerOnlyAmino()
:
Links:
Links:
@cosmjs/ledger-amino
can be used to sign transactions with a Ledger wallet running the Cosmos app.
Notes:
Use the appropriate hw-transport
package for your environment (Node or Browser)
The Ledger Cosmos app only supports coin type 118
You might want to pass encryptionSeed
to SecretNetworkClient.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 a sha256(user_password)
but might impair UX.
Links:
Learn how to send queries with SecretJS.
Returns account details based on address.
Returns all existing accounts on the blockchain.
Queries all x/auth parameters.
Returns list of authorizations, granted to the grantee by the granter.
Balance queries the balance of a single coin for a single account.
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
Get WASM bytecode and metadata for a code id.
Query all contract codes on-chain.
Get upgrades history of a Secret Contract.
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.
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.
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.
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.
Learn more about Query Permits .
Input:
See for further docs on contract migration.
See Keplr's for list of unsupported transactions.
: The recommended way. Supports Ledger, has a nice UI.
: No Ledger support, ugly UI, can send IBC relayer txs and submit IBC gov proposals.
: If Ledger alias for getOfflineSignerOnlyAmino()
, otherwise alias for getOfflineSigner()
.
Every tx type under ibc_client
, ibc_connection
and ibc_channel
(meaning IBC relaying, for example with )
Note that for sending funds across IBC is supported.
Fina implements the Keplr API, so 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
.
StarShell implements the Keplr API, so 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.
See Keplr's for list of unsupported transactions.
An allowance in the context of the Fee Grant module is a specified amount of tokens that a granter permits a grantee to use for paying transaction fees. It should be noted that there can be only one existing fee grant allowed for a grantee and granter and self grants are not allowed.
In the allowance mechanism, there are two key players:
The Granter: The granter is the account that provides the allowance. This account will be debited whenever the grantee pays transaction fees using the allowance.
The Grantee: The grantee is the account that receives the allowance. This account can use the allowance to pay for transaction fees.
There are three allowance types that can be granted:
Basic Fee Allowance: This is a simple allowance model where a granter can specify a maximum limit up to which a grantee can use tokens to pay transaction fees. The allowance can also have an expiration date after which it can no longer be used.
Periodic Fee Allowance: This allowance model is more complex and versatile. It allows the granter to set a periodic reset of the allowance, creating a recurring "budget" for the grantee. This could be used to create a daily, weekly, or monthly allowance, for example.
Allowed Msg Allowance: Creates allowance only for specified message types.
In this guide, our emphasis will be on generating allowances utilizing the BasicAllowance type. For detailed information on each allowance type, please refer to the following.
Granting an allowance involves the granter sending a special type of transaction that includes information about the grantee and the details of the allowance. Once the transaction is included in a block, the allowance is active and can be used by the grantee.
Revoking an allowance is also a simple process. The granter sends a revoke transaction that includes the address of the grantee. Once this transaction is processed, the grantee can no longer use the allowance to pay fees.
It's important to note that allowances may have an expiry date set by the granter. Once an allowance has expired, it can no longer be used to pay for transaction fees. Grantees must be aware of their allowance expiry dates and ensure that they use their allowances before they expire.
Similarly, if an allowance is exhausted (i.e., the fees for a transaction exceed the remaining allowance), the transaction will not be processed.
The Secret Network Fee Grant module is an interesting and powerful feature that allows accounts to grant allowances to other accounts, enabling them to pay fees for transactions from the allowance. This feature opens up numerous possibilities, and one popular use case involves subsidizing the onboarding process for new users who may not possess the native network token required to execute initial transactions.
This guide provides basic solutions for achieving two key goals: first, granting users an allowance on the Secret Network, and second, enabling the end user to use this allowance to execute transactions.
As one of the primary use case of the Fee Grant module is to help with onboarding new users, this section of the guide will show how to allow users to execute transactions using the allowance granted to them.
Now that an allowance has been assigned to an account address, you should be able to verify the details of that grant. The returned information will include the granter's address, the allowance amount, and any other conditions set by the granter, such as the expiration date of the allowance.
The following command using secretcli will give the details of a grant allowance:
Results:
This can also be achieved via the following API endpoint where api_endpoint is an API endpoint connected to one of the Archway networks (Testnet or Mainnet). granter is the address that granted the allowance and grantee is the address that received the allowance:
Results:
The following example will allow a user to unwrap sSCRT into SCRT using a feegrant on mainnet.
Before moving forward, ensure that you have completed the following prerequisites:
Set the fee granter and contract addresses.
Define the transaction details which includes the message to the contract (MsgExecuteContract)
and sign and broadcast the transaction.
Building a smart contract dapp that enables users to request a fee grant is a challenging task since all transactions necessitate the payment of transaction fees. However, there are several methods that can be utilized. Here are a few examples:
The granter can manually execute each fee grant allowance transaction using the secretcli
Construct a deployment script containing addresses that you wish to assign a fee grant to. This script will utilize the secretcli to perform the fee grant transaction for each specified address.
Implement a simple frontend application that verifies and validates a user's account. After confirming that they are the account owner, the application would execute a Javascript transaction with secret.js to carry out the fee grant transaction.
The secretcli is a key tool for accessing the fundamental functionalities of the Archway Blockchain. To install secretcli, refer to Install. Here is an illustration of a typical transaction for creating a grant allowance:
Let's break down a few of the components:
granter_address
: This value represents the address of the account providing tokens to the grantee for transaction execution.
grantee_address
: This denotes the account receiving tokens, enabling it to perform transactions using these grants.
allowed-messages
: Through the AllowedMsgAllowance type, you can limit the message type a grantee can use the grant for. If not specified, all messages are allowed.
expiration
: The deadline by which the allowance must be used or it will expire.
spend-limit
: The maximum allowance provided to the grantee. This amount is adjusted as tokens are utilized.
This section demonstrates how to create a grant allowance using secretjs. By following the steps outlined in this section, you'll be able to structure a grant allowance message, and execute the necessary transaction which will grant allowances to designated accounts.
The allowance message comprises three essential components: the granter
, grantee
, and the actual allowance
. As previously mentioned, the granter
is the address responsible for granting the allowance, while the grantee
is the recipient who can utilize the granted allowance. The allowance
component is slightly more intricate, with its structure dependent on the specific type of allowance employed.
To illustrate, let's examine the structure of a grantMsg using the following example:
Now, all that remains is to execute the transaction:
You can find a working example of this in the Fee Grant Faucet here.
The Fee Grant faucet is backend appilication that allows you to give out fee grants to users.
This tutorial explores how to manage fee grants using secretjs
. The Faucet serves as a backend service, granting, revoking, and querying fee allowances for blockchain addresses through a simple HTTP interface.
Git
Node.js
npm (Node Package Manager)
Clone the repository to your local machine and navigate to the project directory:
Install the necessary Node.js dependencies:
Create a .env file in the root of the project directory. Use the .env.sample provided in the repository as a reference and fill in the necessary details. Ensure these variables are correctly set in your .env
file for the script to function.
Before diving into the code, it's essential to set up the environment:
CHAIN_ID
: Identifier of the blockchain network.
LCD_NODE
: URL of the Light Client Daemon (LCD) for interacting with the blockchain.
FAUCET_MNEMOMIC
: Mnemonic for the wallet used in transactions.
Don't forget to fill up your Faucet with SCRT.
Start the application:
The script uses Node Express, a popular Node.js framework, to create a web server:
Endpoint Creation: An endpoint /claim/:address
is set up. It's designed to handle fee grants for a specified blockchain address passed as a parameter.
The script includes robust functionality for managing fee grants:
Address Validation: Uses validateAddress
to ensure the provided blockchain address is valid.
Querying Balance and Fee Grants: Before granting a fee, the script can check the existing balance and any active fee grants for the address.
The core functionality of the script lies in managing fee grants:
Function giveFeeGrant
: Depending on the situation, this function either revokes an old fee grant and issues a new one or issues a new grant directly.
Message Construction:
MsgRevokeAllowance
: Used to revoke an existing fee grant.
MsgGrantAllowance
: Used to grant a new fee allowance to an address.
Handling transactions is a critical part of the script:
Broadcasting Transactions: Utilizes secretjs.tx.broadcast
to send the transaction to the blockchain.
Transaction Parameters: Includes memo, fee, and gas limit details.
JSON Output: The script outputs a JSON object with the feegrant
details, including grantee, granter, spend limit, and expiration.
The script incorporates error handling mechanisms:
Invalid Addresses: Returns an error if the provided address is invalid.
Transaction Failures: Catches and logs transaction-related errors.
Here are some key code snippets and example responses:
Endpoint /claim/:address
:
Example JSON Response from the faucet:
Follow these steps to install and run the .