/example/cosmoshub.js

https://github.com/cosmostation/cosmosjs · JavaScript · 49 lines · 34 code · 8 blank · 7 comment · 0 complexity · b8fb37c2daff871e13c3e6a3eeddb79a MD5 · raw file

  1. import { Cosmos } from "../src/index.js";
  2. import message from "../src/messages/proto";
  3. // [WARNING] This mnemonic is just for the demo purpose. DO NOT USE THIS MNEMONIC for your own wallet.
  4. const mnemonic = "swear buyer security impulse public stereo peasant correct cross tornado bid discover anchor float venture deal patch property cool wreck eight dwarf december surface";
  5. const chainId = "cosmoshub-4";
  6. // This rest server URL may be disabled at any time. In order to maintain stable blockchain service, it is recommended to prepare your rest server.
  7. // (https://hub.cosmos.network/main/gaia-tutorials/join-mainnet.html#enable-the-rest-api)
  8. const cosmos = new Cosmos("https://api.cosmos.network", chainId);
  9. cosmos.setBech32MainPrefix("cosmos");
  10. cosmos.setPath("m/44'/118'/0'/0/0");
  11. const address = cosmos.getAddress(mnemonic);
  12. const privKey = cosmos.getECPairPriv(mnemonic);
  13. const pubKeyAny = cosmos.getPubKeyAny(privKey);
  14. cosmos.getAccounts(address).then(data => {
  15. // signDoc = (1)txBody + (2)authInfo
  16. // ---------------------------------- (1)txBody ----------------------------------
  17. const msgSend = new message.cosmos.bank.v1beta1.MsgSend({
  18. from_address: address,
  19. to_address: "cosmos18vhdczjut44gpsy804crfhnd5nq003nz0nf20v",
  20. amount: [{ denom: "uatom", amount: String(100000) }] // 6 decimal places (1000000 uatom = 1 ATOM)
  21. });
  22. const msgSendAny = new message.google.protobuf.Any({
  23. type_url: "/cosmos.bank.v1beta1.MsgSend",
  24. value: message.cosmos.bank.v1beta1.MsgSend.encode(msgSend).finish()
  25. });
  26. const txBody = new message.cosmos.tx.v1beta1.TxBody({ messages: [msgSendAny], memo: "" });
  27. // --------------------------------- (2)authInfo ---------------------------------
  28. const signerInfo = new message.cosmos.tx.v1beta1.SignerInfo({
  29. public_key: pubKeyAny,
  30. mode_info: { single: { mode: message.cosmos.tx.signing.v1beta1.SignMode.SIGN_MODE_DIRECT } },
  31. sequence: data.account.sequence
  32. });
  33. const feeValue = new message.cosmos.tx.v1beta1.Fee({
  34. amount: [{ denom: "uatom", amount: String(5000) }],
  35. gas_limit: 200000
  36. });
  37. const authInfo = new message.cosmos.tx.v1beta1.AuthInfo({ signer_infos: [signerInfo], fee: feeValue });
  38. // -------------------------------- sign --------------------------------
  39. const signedTxBytes = cosmos.sign(txBody, authInfo, data.account.account_number, privKey);
  40. cosmos.broadcast(signedTxBytes).then(response => console.log(response));
  41. });