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.
You can skip straight to our kitchen sink example directly:
👉 Cosmos Example
#NPM
01npm install --save @magic-ext/cosmos
#Yarn
01yarn add @magic-ext/cosmos
#Initializing Extension
#ES Modules/TypeScript
01import { Magic } from 'magic-sdk';
02import { CosmosExtension } from '@magic-ext/cosmos';
03
04const magic = new Magic('YOUR_API_KEY', {
05 extensions: [
06 new CosmosExtension({
07 rpcUrl: 'cosmos rpc url',
08 }),
09 ],
10});
#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
01import { Magic } from 'magic-sdk';
02import { CosmosExtension } from '@magic-ext/cosmos';
03import { coins } from '@cosmjs/launchpad';
04
05const magic = new Magic('YOUR_API_KEY', {
06 extensions: [
07 new CosmosExtension({
08 rpcUrl: 'cosmos rpc url',
09 }),
10 ],
11});
12
13const metadata = await magic.user.getMetadata();
14
15const message = [
16 {
17 type: 'cosmos-sdk/MsgSend',
18 value: {
19 amount: [
20 {
21 amount: '200',
22 denom: 'token',
23 },
24 ],
25 from_address: metadata.publicAddress,
26 to_address: 'to address',
27 },
28 },
29];
30const fee = {
31 amount: coins(0, 'token'),
32 gas: '200000',
33};
34
35const sendTransactionResult = await magic.cosmos.signAndBroadcast(message, fee);
36
37//or
38
39const signTransactionResult = await magic.cosmos.sign(message, fee);
#Send Tokens
Using magic.cosmos.sendTokens
function to native tokens on Cosmos blockchain.
#ES Modules/TypeScript
01import { Magic } from 'magic-sdk';
02import { CosmosExtension } from '@magic-ext/cosmos';
03
04const magic = new Magic('YOUR_API_KEY', {
05 extensions: [
06 new CosmosExtension({
07 rpcUrl: 'cosmos rpc url',
08 }),
09 ],
10});
11
12const result = await magic.cosmos.sendTokens('recipientAddress', 'transferAmount', 'denom', 'memo');
#Change Address
Using magic.cosmos.changeAddress
function to change the address prefix.
#ES Modules/TypeScript
01import { Magic } from 'magic-sdk';
02import { CosmosExtension } from '@magic-ext/cosmos';
03
04const magic = new Magic('YOUR_API_KEY', {
05 extensions: [
06 new CosmosExtension({
07 rpcUrl: 'cosmos rpc url',
08 }),
09 ],
10});
11
12const result = await magic.cosmos.changeAddress('address prefix');