import { GasPrice, SigningStargateClient, StargateClient, coins } from'@cosmjs/stargate';import { DirectSecp256k1Wallet } from'@cosmjs/proto-signing';import { toBech32 } from'@cosmjs/encoding';import { rawSecp256k1PubkeyToRawAddress } from'@cosmjs/amino'// Mnemonic for the account you want to useconstkey=process.env.PRIVATE_KEY!;constaddress=ADD_XION_ADDRESS_HEREconstrpcEndpoint='https://rpc.xion-testnet-1.burnt.com:443';//Tx infoconstamount=coins('1','uxion');constgasPrice=GasPrice.fromString("0uxion");consttxOptions= { gasPrice };// The main function to create and use the SigningStargateClientasyncfunctionmain() {// Creating a wallet instance from a given mnemonicconstwallet=awaitDirectSecp256k1Wallet.fromKey(Buffer.from(key,'hex'),"xion");// Fetching account from the walletconst [account] =awaitwallet.getAccounts();constsender=toBech32("xion",rawSecp256k1PubkeyToRawAddress(account.pubkey))// Creating an instance of SigningStargateClientconstclient=awaitSigningStargateClient.connectWithSigner(rpcEndpoint, wallet, txOptions);// Defining recipient and coins to be transferredconstrecipient= address;// Broadcasting the transactionconstresult=awaitclient.sendTokens(sender, recipient, amount,"auto","sending a msg!");console.log(result);}main().catch(console.error);
To fetch the private key from xiond execute the following in your terminal
The private key will be returned in plaintext, do NOT use --unarmored-hex --unsafe to export keys in production environments.
If you need to generate a quickly the following run the following in a terminal:
opensslrand-hex32
Queries
Query for the balance of a contract
import { QueryClient } from'@cosmjs/stargate';import { QueryAllBalancesResponse } from'@cosmjs/stargate/build/codec/cosmos/bank/v1beta1/query';// Change this to your node endpointconstrpcEndpoint='<rpc-endpoint>';// Address to queryconstaddressToQuery='<address-to-query>';asyncfunctionmain() {constclient=QueryClient.withExtensions({rpcEndpoint});constbalances:QueryAllBalancesResponse=awaitclient.bank.allBalances(addressToQuery);console.log('Balances:', balances);client.disconnect();}main().catch(console.error);