Solana

Solana

#Installation

To get started, install the following dependencies for your project:

NPM
Yarn
01npm install @magic-ext/solana @solana/web3.js magic-sdk

#Initialization

The Magic class is the entry-point to the Magic SDK. It must be instantiated with a Magic publishable key.

#ES Modules/TypeScript

Typescript
01import { Magic } from 'magic-sdk';
02import { SolanaExtension } from '@magic-ext/solana';
03
04const magic = new Magic('YOUR_API_KEY', {
05  extensions: [
06    new SolanaExtension({
07      rpcUrl: 'SOLANA_RPC_NODE_URL',
08    }),
09  ],
10});

#CDN

Javascript
01<script src="https://auth.magic.link/sdk"></script>
02<script type="text/javascript" src="https://auth.magic.link/sdk/extension/solana"></script>
03
04<script>
05  const magic = new window.Magic("YOUR_API_KEY", {
06      extensions: [
07        new SolanaExtension({
08          rpcUrl: 'SOLANA_RPC_NODE_URL'
09        })
10      ]
11  });
12</script>

#Common Methods

Note that the Magic Solana extension follows the method names and conventions by Solana's Javascript SDK.

#Sign and Send Transaction

#ES Modules/TypeScript

To sign a standard Solana blockchain transaction, call the magic.solana.signTransaction method. Note that you must sign with the Magic SDK method but send the transaction using the @solana/web3.js method connection.sendRawTransaction.

Typescript
01import * as web3 from "@solana/web3.js";
02
03// Ensure you have Magic initialized with the Solana extension
04// Ensure that user is already authenticated
05
06const connection = new web3.Connection(clusterApiUrl("devnet"))
07
08const metadata = await magic.user.getMetadata();
09const userPublicKey = new web3.PublicKey(metadata.publicAddress);
10const recipientPubkey = new web3.Keypair.generate().publicKey;
11
12const blockhash = await connection?.getLatestBlockhash();
13if (!blockhash) return;
14
15const transaction = new web3.Transaction({        
16  ...blockhash,        
17  feePayer: userPublicKey,     
18}).add(
19  web3.SystemProgram.transfer({
20    fromPubkey: userPublicKey,
21    toPubkey: recipientPubkey,
22    lamports: web3.LAMPORTS_PER_SOL * 0.01,
23  })
24);
25
26const signedTransaction = await magic?.solana.signTransaction(        
27  transaction,        
28  {        
29    requireAllSignatures: false,        
30    verifySignatures: true,      
31  }     
32);
33
34const signature = await connection?.sendRawTransaction(        
35  Buffer.from(signedTransaction?.rawTransaction as string, "base64")      
36);
37
38console.log(signature);

#Sign Message

#ES Modules/TypeScript

Typescript
01// Ensure you have Magic initialized with the Solana extension
02// Ensure that user is already authenticated
03
04const signedMessage = await magic?.solana.signMessage("Hello World")
05
06console.log(signedMessage)

#Resources