Esc

wallet-sdk

@megaeth-labs/wallet-sdkAI Generated

The Pure JS SDK for MOSS. Every function is on the mega object and talks to the wallet through an iframe the SDK adds to the page.

pnpm add @megaeth-labs/wallet-sdk
ts
import { mega } from '@megaeth-labs/wallet-sdk';

Connecting#

initialise#

Sets up the wallet for a network and returns the user's connection status. Call it once before anything else. See Initialise and Sponsoring Gas.

tsTypes
initialise: (config: Config) => Promise<ConnectionStatus | undefined>;

interface Config {
    network: 'mainnet' | 'testnet';
    logging?: 'debug' | 'info' | 'warn' | 'error';
    devMode?: boolean;
    devUIUrl?: string;
    debug?: boolean;
    sponsorUrl?: string;
    sponsorMode?: 'everything' | 'app-only' | 'explicit';
    sponsorToken?: 'native' | 'usdm';
    handshakeTimeoutMs?: number;
    silentDefault?: boolean; // Defaults to true
}

type ConnectionStatus = {
    status: 'connected' | 'disconnected' | 'cancelled';
    address?: `0x${string}`;
    network: 'mainnet' | 'testnet';
};
tsExample
import { mega, MegaInitError } from '@megaeth-labs/wallet-sdk';

try {
    const status = await mega.initialise({ network: 'testnet' });
    console.log(status?.status);
} catch (error) {
    if (error instanceof MegaInitError) console.error(error.code);
}

status#

Returns whether a wallet is connected, its address and the network. See Status.

tsTypes
status: () => Promise<ConnectionStatus>;
const { status, address, network } = await mega.status();
Runs on testnet with your wallet

events.onStatusChange#

Calls back whenever the connection status changes, such as when the user connects or disconnects in the wallet. See Status Changes.

tsTypes
events: {
    onStatusChange: (callback: (status: ConnectionStatus) => void) => void;
};
tsExample
mega.events.onStatusChange(({ status, address }) => {
    console.log(status, address);
});

connect#

Asks the user to sign in or create a wallet, and returns the connected address. See Connect.

tsTypes
connect: (request?: ConnectRequest) => Promise<ConnectionStatus>;

interface ConnectRequest {
    address?: `0x${string}`;
}
const { status, address } = await mega.connect();

if (status === 'connected') {
    console.log('Connected:', address);
}
Runs on testnet with your wallet

disconnect#

Disconnects the wallet from your app. See Disconnect.

tsTypes
disconnect: () => Promise<ConnectionStatus>;
const { status } = await mega.disconnect();
Runs on testnet with your wallet

Authenticating#

authenticate#

Signs the user in to your server with Sign-In with Ethereum and returns a JWT for your server to verify. See Authenticate and Authentication.

tsTypes
authenticate: () => Promise<AuthenticateResponse>;

interface AuthenticateResponse {
    status: 'success' | 'cancelled' | 'error';
    error?: string;
    jwt?: string;
}
const auth = await mega.authenticate();

if (auth.status === 'success' && auth.jwt) {
    await fetch('/api/login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ token: auth.jwt }),
    });
}
Runs on testnet with your wallet

Signing#

signMessage#

Asks the user to sign a plain text message. See Sign Message.

tsTypes
signMessage: (message: string) => Promise<SignMessageResponse>;

interface SignMessageResponse {
    status: 'success' | 'cancelled' | 'error';
    error?: string;
    signature?: `0x${string}`;
}
const result = await mega.signMessage('Hello, World!');

if (result.status === 'success') {
    console.log('Signature:', result.signature);
}
Runs on testnet with your wallet

signData#

Asks the user to sign EIP-712 typed data. See Sign Data.

tsTypes
signData: (request: SignDataRequest) => Promise<SignDataResponse>;

interface SignDataRequest {
    data: any;
}

interface SignDataResponse {
    status: 'success' | 'cancelled' | 'error';
    error?: string;
    signature?: string;
}
const result = await mega.signData({
    data: {
        domain: { name: 'MyApp', version: '1', chainId: 4326 },
        types: {
            Person: [
                { name: 'name', type: 'string' },
                { name: 'wallet', type: 'address' },
            ],
        },
        primaryType: 'Person',
        message: { name: 'Alice', wallet: '0xFD8D73c93385271d06138FA0Ff6E9c639C3Bd8b0' },
    },
});
Runs on testnet with your wallet

Opening the Wallet#

open#

Opens the MOSS wallet. See Open Wallet and Account Management.

tsTypes
open: () => Promise<void>;
await mega.open();
Runs on testnet with your wallet

Calling Contracts#

callContract#

Sends a transaction that calls a contract, or several calls batched into one transaction when given an array. See Call Contract, Permissions and Gas.

A call is silent unless it sets silent: false, or the config sets silentDefault: false. A silent call is sent with the app's session key without a prompt when the key's permissions cover it, whether the app granted them or the user set them up in the wallet, and the user is asked to approve it otherwise. One call with silent: false asks for the whole batch.

tsTypes
callContract: (request: CallContractRequest | CallContractRequest[]) => Promise<TransactionResult>;

interface CallContractRequest {
    address: `0x${string}`;
    abi?: any;
    functionName?: string;
    args?: any[];
    data?: `0x${string}`;
    silent?: boolean; // Defaults to config.silentDefault
    silentUIApproveFallback?: boolean;
    value?: bigint | string;
    sponsor?: boolean;
    maxGasAllowance?: bigint;
}

interface TransactionResult {
    status: 'approved' | 'cancelled' | 'error';
    receipt?: TransactionReceipt;
    receipts?: TransactionReceipt[];
    error?: string;
    silentHasUsedFallback?: boolean;
}

interface TransactionReceipt {
    hash: `0x${string}`;
    blockHash: string;
    blockNumber: number;
    chainId: number;
    gasUsed: number;
    logs: { address: `0x${string}`; data: `0x${string}`; topics: string[] }[];
    status: string;
    transactionHash: `0x${string}`;
}
const result = await mega.callContract({
    address: '0x3e942744C21Eec1D88FBD463Fd0CcE42891Aec5C',
    abi: storageAbi,
    functionName: 'store',
    args: [42],
});

if (result.status === 'approved') {
    console.log('Transaction hash:', result.receipt?.hash);
}
Runs on testnet with your wallet

getFromContract#

Reads from a contract without a transaction or any gas. See Get from Contract.

tsTypes
getFromContract: <T>(request: GetFromContractRequest) => Promise<T>;

interface GetFromContractRequest {
    address: `0x${string}`;
    abi: any;
    functionName: string;
    args: any[];
}
const value = await mega.getFromContract<bigint>({
    address: '0x3e942744C21Eec1D88FBD463Fd0CcE42891Aec5C',
    abi: storageAbi,
    functionName: 'retrieve',
    args: [],
});
Runs on testnet with your wallet

grantPermissions#

Asks the user to let your app make set calls and spend up to set limits without approving each transaction. See Grant Permissions and Permissions.

tsTypes
grantPermissions: (request: GrantPermissionsRequest) => Promise<GrantPermissionsResponse>;

interface GrantPermissionsRequest {
    permissions: Permission;
    externalAddress?: `0x${string}`;
    sponsor?: boolean;
    append?: boolean;
}

interface Permission {
    id?: string;
    expiry: number; // Unix timestamp, in seconds
    permissions: {
        calls: { signature: string; to: string }[];
        spend: {
            limit: bigint;
            period: 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year';
            token?: `0x${string}`;
        }[];
    };
}

type GrantPermissionsResponse = {
    status: 'approved' | 'cancelled';
};
import { parseEther } from 'viem';

const result = await mega.grantPermissions({
    permissions: {
        expiry: Math.floor(Date.now() / 1000) + 60 * 60 * 3, // 3 hours
        permissions: {
            calls: [{ to: '0x3e942744C21Eec1D88FBD463Fd0CcE42891Aec5C', signature: 'store(uint256)' }],
            spend: [{ limit: parseEther('0.01'), period: 'day' }],
        },
    },
});
Runs on testnet with your wallet

getPermissions#

Returns the permissions the user has granted your app that haven't expired, or null when there are none. See Get Permissions and Permissions.

tsTypes
getPermissions: (address?: string) => Promise<GetPermissionsResponse | undefined>;

interface GetPermissionsResponse {
    permissions?: {
        expiry: number;
        permissions: {
            calls: { signature: string; to: `0x${string}` }[];
            spend: {
                limit: bigint;
                period: 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year';
                token?: `0x${string}`;
            }[];
        };
    } | null;
}
const result = await mega.getPermissions();

if (result?.permissions) {
    console.log('Expires', new Date(result.permissions.expiry * 1000));
}
Runs on testnet with your wallet

revokePermissions#

Removes the permissions the user has granted your app. See Revoke Permissions and Permissions.

tsTypes
revokePermissions: () => Promise<void>;
await mega.revokePermissions();
Runs on testnet with your wallet

Sending Funds#

transfer#

Sends native tokens, an ERC-20, an ERC-721 or an ERC-1155 to an address. See Transfer.

tsTypes
transfer: (request: TransferRequest) => Promise<TransactionResult>;

interface TransferRequest {
    amount: string; // In the token's smallest unit
    to: `0x${string}`;
    type: 'native' | 'erc20' | 'erc721' | 'erc1155';
    contractAddress?: string;
    tokenId?: number;
    sponsor?: boolean;
}
import { parseUnits } from 'viem';

const result = await mega.transfer({
    type: 'erc20',
    to: '0xFD8D73c93385271d06138FA0Ff6E9c639C3Bd8b0',
    contractAddress: '0x2715b6d04b6a0AB227631019899282a585Be410F',
    amount: parseUnits('1', 18).toString(),
});
Runs on testnet with your wallet

checkout#

Asks the user to pay your app an amount in US dollars. It takes its own config, so it works without initialise. See Checkout and Ramps.

tsTypes
checkout: (request: CheckoutRequest) => Promise<CheckoutResult>;

interface CheckoutRequest {
    config?: Config;
    amountUSD: string;
    destination?: `0x${string}`;
    tokenAddress?: `0x${string}`;
    reference?: string;
    lineItems?: { amountUSD: string; label: string }[];
}

interface CheckoutResult {
    status: 'approved' | 'cancelled' | 'error';
    error?: string;
    address?: `0x${string}`;
    hash?: `0x${string}`;
    tokenAmount?: string;
    usdAmount?: string;
    destination?: `0x${string}`;
}
const result = await mega.checkout({
    config: { network: 'mainnet' },
    amountUSD: '9.99',
    destination: '0xFD8D73c93385271d06138FA0Ff6E9c639C3Bd8b0',
    reference: 'A-2481',
});

if (result.status === 'approved') {
    console.log('Paid in transaction', result.hash);
}
Runs on testnet with your wallet

send#

Opens the wallet's send screen, optionally with a token and destination filled in. See Send.

tsTypes
send: (request: SendRequest) => Promise<TransactionResult>;

interface SendRequest {
    token?: `0x${string}` | 'native';
    destination?: `0x${string}`;
}
const result = await mega.send({});
Runs on testnet with your wallet

Tokens#

deposit#

Opens the wallet's deposit screen, where the user can buy tokens or bridge them in. See Deposit, Ramps and Bridging.

tsTypes
deposit: () => Promise<void>;
await mega.deposit();
Runs on testnet with your wallet

swap#

Opens the wallet's swap screen, optionally with the tokens filled in. See Swap and Swaps.

tsTypes
swap: (request: SwapRequest) => Promise<TransactionResult>;

interface SwapRequest {
    fromToken?: `0x${string}` | 'native';
    toToken?: `0x${string}` | 'native';
}
const result = await mega.swap({
    fromToken: 'native',
    toToken: '0x2715b6d04b6a0AB227631019899282a585Be410F',
});
Runs on testnet with your wallet

balances#

Returns the connected account's token balances, for every token it holds or just the ones you list. See Balances.

tsTypes
balances: (request: BalancesRequest) => Promise<OwnedTokenResponse[]>;

interface BalancesRequest {
    tokens?: string[];
}

interface OwnedTokenResponse {
    name: string;
    symbol: string;
    decimals: number;
    address: string;
    image?: string;
    balance: string;
    displayBalance: string;
    usdPrice?: string;
    usdBalance?: string;
    marketCap?: string;
    volume?: string;
    holders?: number;
    percentChange?: number;
}
const balances = await mega.balances({ tokens: ['0x2715b6d04b6a0AB227631019899282a585Be410F'] });

for (const token of balances) {
    console.log(token.symbol, token.displayBalance);
}
Runs on testnet with your wallet

collectible#

Opens the wallet on one of the user's collectibles. See Collectible.

tsTypes
collectible: (request: CollectibleRequest) => Promise<void>;

interface CollectibleRequest {
    address: `0x${string}`;
    tokenId: string;
}
await mega.collectible({
    address: '0x9416E9a7E89ceF6ECF97A6D7Cc4b58E128d0d3bb',
    tokenId: '1',
});
Runs on testnet with your wallet

MegaNames#

fromMegaName#

Returns the address a MegaName points to, or undefined when it isn't registered. See From MegaName.

tsTypes
fromMegaName: (name: string) => Promise<`0x${string}` | undefined>;
const address = await mega.fromMegaName('alice.mega');
Runs on testnet with your wallet

toMegaName#

Returns the MegaName for an address, or undefined when it has none. See To MegaName.

tsTypes
toMegaName: (address: `0x${string}`) => Promise<string | undefined>;
const name = await mega.toMegaName('0xFD8D73c93385271d06138FA0Ff6E9c639C3Bd8b0');
Runs on testnet with your wallet

Errors#

MegaInitError#

Thrown by initialise when the wallet doesn't respond in time, often because your site isn't allowed to embed it, or the connection fails. See Initialise.

tsTypes
class MegaInitError extends Error {
    code: 'HANDSHAKE_TIMEOUT' | 'CONNECTION_FAILED';
}
tsExample
import { mega, MegaInitError } from '@megaeth-labs/wallet-sdk';

try {
    await mega.initialise({ network: 'mainnet', handshakeTimeoutMs: 10_000 });
} catch (error) {
    if (error instanceof MegaInitError && error.code === 'HANDSHAKE_TIMEOUT') {
        console.error('The wallet took too long to load');
    }
}