How to Integrate with the Cosmos Blockchain with Magic

How to Integrate with the Cosmos Blockchain with Magic

#Installation

Magic interacts with the Cosmos blockchain via Magic's extension NPM package @magic-ext/cosmos. The Cosmos extension also lets you interact with the blockchain using methods from cosmjs.

note

You can skip straight to our kitchen sink example directly:

👉 Cosmos Example

#NPM

npm install --save @magic-ext/cosmos

#Yarn

yarn add @magic-ext/cosmos

#Initializing Extension

#ES Modules/TypeScript

import { Magic } from 'magic-sdk';
import { CosmosExtension } from '@magic-ext/cosmos';

const magic = new Magic('YOUR_API_KEY', {
  extensions: [
    new CosmosExtension({
      rpcUrl: 'cosmos rpc url',
    }),
  ],
});

#Send and Sign Transaction

To send or sign a standard Cosmos blockchain transaction, you can call the magic.cosmos.signAndBroadcast method or magic.cosmos.sign method.

#ES Modules/TypeScript

import { Magic } from 'magic-sdk';
import { CosmosExtension } from '@magic-ext/cosmos';
import { coins } from '@cosmjs/launchpad';

const magic = new Magic('YOUR_API_KEY', {
  extensions: [
    new CosmosExtension({
      rpcUrl: 'cosmos rpc url',
    }),
  ],
});

const metadata = await magic.user.getMetadata();

const message = [
  {
    type: 'cosmos-sdk/MsgSend',
    value: {
      amount: [
        {
          amount: '200',
          denom: 'token',
        },
      ],
      from_address: metadata.publicAddress,
      to_address: 'to address',
    },
  },
];
const fee = {
  amount: coins(0, 'token'),
  gas: '200000',
};

const sendTransactionResult = await magic.cosmos.signAndBroadcast(message, fee);

//or

const signTransactionResult = await magic.cosmos.sign(message, fee);

#Send Tokens

Using magic.cosmos.sendTokens function to native tokens on Cosmos blockchain.

#ES Modules/TypeScript

import { Magic } from 'magic-sdk';
import { CosmosExtension } from '@magic-ext/cosmos';

const magic = new Magic('YOUR_API_KEY', {
  extensions: [
    new CosmosExtension({
      rpcUrl: 'cosmos rpc url',
    }),
  ],
});

const result = await magic.cosmos.sendTokens('recipientAddress', 'transferAmount', 'denom', 'memo');

#Change Address

Using magic.cosmos.changeAddress function to change the address prefix.

#ES Modules/TypeScript

import { Magic } from 'magic-sdk';
import { CosmosExtension } from '@magic-ext/cosmos';

const magic = new Magic('YOUR_API_KEY', {
  extensions: [
    new CosmosExtension({
      rpcUrl: 'cosmos rpc url',
    }),
  ],
});

const result = await magic.cosmos.changeAddress('address prefix');

Did you find what you were looking for?

How to Integrate with the Cosmos Blockchain with Magic

Did you find what you were looking for?