How to Integrate with the Avalanche Blockchain with Magic
How to Integrate with the Avalanche Blockchain with Magic
#Installation
Magic interacts with the Avalanche blockchain via Magic's extension NPM package @magic-ext/avalanche
. The Avalanche extension also lets you interact with the blockchain using methods from Avalanche's Javascript SDK.
You can skip straight to our github example directly:
👉 Avalanche Example
#NPM
npm install --save @magic-ext/avalanche
#Yarn
yarn add @magic-ext/avalanche
#Initializing Extension
Note: This is for X-Chain implementation. For generic EVM compatible C-Chain support refer to this documentation on configuring custom nodes.
#ES Modules/TypeScript
import { Magic } from 'magic-sdk';
import { AvalancheExtension } from '@magic-ext/avalanche';
const magic = new Magic('YOUR API KEY', {
extensions: {
xchain: new AvalancheExtension({
rpcUrl: 'Avalanche node url',
chainId: 'Avalanche chain id',
networkId: 4, // Avalanche networkId
}),
},
});
#Send Transaction
#Getting Test AVAX
Before you can send transaction on the Avalanche blockchain, you'll need to acquire some test AVAX (Avalanche's native cryptocurrency for test network).
- Go to our Avalanche Example.
- Login with your email address
- Copy your Avalanche public address
- Go to the Avalanche Faucet
- Paste your copied Avalanche public address in the text input
- You can receive 10000000 nAVAX
- Now you can use your test AVAX in our example app
#Call Extension Method
Note that the Magic Avalanche extension follows the method names and conventions by Avalanche's Javascript SDK. To send a standard Avalanche blockchain transaction, you can call the magic.xchain.signTransaction()
method.
#ES Modules/TypeScript
import { Magic } from 'magic-sdk';
import { AvalancheExtension } from '@magic-ext/avalanche';
import { Avalanche, BinTools, Buffer, BN } from 'avalanche';
const magic = new Magic('YOUR API KEY', {
extensions: {
xchain: new AvalancheExtension({
rpcUrl: 'Avalanche node url',
chainId: 'Avalanche chain id',
networkId: 4, // Avalanche networkId
}),
},
});
const metadata = await magic.user.getMetadata();
let myNetworkID = 4; //default is 3, we want to override that for our local network
let myBlockchainID = 'X'; // The XChain blockchainID on this network
let ava = new Avalanche('testapi.avax.network', 443, 'https', myNetworkID, myBlockchainID);
let xchain = ava.XChain();
let assetId = 'nznftJBicce1PfWQeNEVBmDyweZZ6zcM3p78z9Hy9Hhdhfaxm';
let fromAddresses = [metadata.publicAddress];
let toAddresses = ['X-everest1zr334udmau3xruusmwnyng3hug38errx83h6xq'];
let sendAmount = 1000000;
const signedTx = await magic.xchain.signTransaction(sendAmount, assetId, toAddresses, fromAddresses, toAddresses);
console.log('signedTX', signedTx);
let txid = await xchain.issueTx(signedTx);
console.log('send transaction', txid);