# wallet-sdk

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.

```bash title="pnpm"
pnpm add @megaeth-labs/wallet-sdk
```

```bash title="npm"
npm install @megaeth-labs/wallet-sdk
```

```bash title="yarn"
yarn 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](https://moss.megaeth.com/developers/methods/connecting/initialise) and [Sponsoring Gas](https://moss.megaeth.com/developers/concepts/sponsoring-gas).

```ts title="Types"
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';
};
```

```ts title="Example"
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](https://moss.megaeth.com/developers/methods/connecting/status).

```ts title="Types"
status: () => Promise<ConnectionStatus>;
```

```ts title="Example"
const { status, address, network } = await mega.status();
```

### `events.onStatusChange`

Calls back whenever the connection status changes, such as when the user connects or disconnects in the wallet.
See [Status Changes](https://moss.megaeth.com/developers/methods/connecting/status#status-changes).

```ts title="Types"
events: {
    onStatusChange: (callback: (status: ConnectionStatus) => void) => void;
};
```

```ts title="Example"
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](https://moss.megaeth.com/developers/methods/connecting/connect).

```ts title="Types"
connect: (request?: ConnectRequest) => Promise<ConnectionStatus>;

interface ConnectRequest {
    address?: `0x${string}`;
}
```

```ts title="Example"
const { status, address } = await mega.connect();

if (status === 'connected') {
    console.log('Connected:', address);
}
```

### `disconnect`

Disconnects the wallet from your app.
See [Disconnect](https://moss.megaeth.com/developers/methods/connecting/disconnect).

```ts title="Types"
disconnect: () => Promise<ConnectionStatus>;
```

```ts title="Example"
const { status } = await mega.disconnect();
```

## 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](https://moss.megaeth.com/developers/methods/authenticate) and [Authentication](https://moss.megaeth.com/developers/concepts/authentication).

```ts title="Types"
authenticate: () => Promise<AuthenticateResponse>;

interface AuthenticateResponse {
    status: 'success' | 'cancelled' | 'error';
    error?: string;
    jwt?: string;
}
```

```ts title="Example"
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 }),
    });
}
```

## Signing

### `signMessage`

Asks the user to sign a plain text message.
See [Sign Message](https://moss.megaeth.com/developers/methods/signing/sign-message).

```ts title="Types"
signMessage: (message: string) => Promise<SignMessageResponse>;

interface SignMessageResponse {
    status: 'success' | 'cancelled' | 'error';
    error?: string;
    signature?: `0x${string}`;
}
```

```ts title="Example"
const result = await mega.signMessage('Hello, World!');

if (result.status === 'success') {
    console.log('Signature:', result.signature);
}
```

### `signData`

Asks the user to sign EIP-712 typed data.
See [Sign Data](https://moss.megaeth.com/developers/methods/signing/sign-data).

```ts title="Types"
signData: (request: SignDataRequest) => Promise<SignDataResponse>;

interface SignDataRequest {
    data: any;
}

interface SignDataResponse {
    status: 'success' | 'cancelled' | 'error';
    error?: string;
    signature?: string;
}
```

```ts title="Example"
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' },
    },
});
```

## Opening the Wallet

### `open`

Opens the MOSS wallet.
See [Open Wallet](https://moss.megaeth.com/developers/methods/open) and [Account Management](https://moss.megaeth.com/developers/concepts/account-management).

```ts title="Types"
open: () => Promise<void>;
```

```ts title="Example"
await mega.open();
```

## Calling Contracts

### `callContract`

Sends a transaction that calls a contract, or several calls batched into one transaction when given an array.
See [Call Contract](https://moss.megaeth.com/developers/methods/calling-contracts/call-contract), [Permissions](https://moss.megaeth.com/developers/concepts/permissions)
and [Gas](https://moss.megaeth.com/developers/concepts/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.

```ts title="Types"
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}`;
}
```

```ts title="Example"
const result = await mega.callContract({
    address: '0x3e942744C21Eec1D88FBD463Fd0CcE42891Aec5C',
    abi: storageAbi,
    functionName: 'store',
    args: [42],
});

if (result.status === 'approved') {
    console.log('Transaction hash:', result.receipt?.hash);
}
```

### `getFromContract`

Reads from a contract without a transaction or any gas.
See [Get from Contract](https://moss.megaeth.com/developers/methods/calling-contracts/get-from-contract).

```ts title="Types"
getFromContract: <T>(request: GetFromContractRequest) => Promise<T>;

interface GetFromContractRequest {
    address: `0x${string}`;
    abi: any;
    functionName: string;
    args: any[];
}
```

```ts title="Example"
const value = await mega.getFromContract<bigint>({
    address: '0x3e942744C21Eec1D88FBD463Fd0CcE42891Aec5C',
    abi: storageAbi,
    functionName: 'retrieve',
    args: [],
});
```

### `grantPermissions`

Asks the user to let your app make set calls and spend up to set limits without approving each transaction.
See [Grant Permissions](https://moss.megaeth.com/developers/methods/calling-contracts/grant-permissions) and
[Permissions](https://moss.megaeth.com/developers/concepts/permissions).

```ts title="Types"
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';
};
```

```ts title="Example"
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' }],
        },
    },
});
```

### `getPermissions`

Returns the permissions the user has granted your app that haven't expired, or `null` when there are none.
See [Get Permissions](https://moss.megaeth.com/developers/methods/calling-contracts/get-permissions) and
[Permissions](https://moss.megaeth.com/developers/concepts/permissions).

```ts title="Types"
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;
}
```

```ts title="Example"
const result = await mega.getPermissions();

if (result?.permissions) {
    console.log('Expires', new Date(result.permissions.expiry * 1000));
}
```

### `revokePermissions`

Removes the permissions the user has granted your app.
See [Revoke Permissions](https://moss.megaeth.com/developers/methods/calling-contracts/revoke-permissions) and
[Permissions](https://moss.megaeth.com/developers/concepts/permissions).

```ts title="Types"
revokePermissions: () => Promise<void>;
```

```ts title="Example"
await mega.revokePermissions();
```

## Sending Funds

### `transfer`

Sends native tokens, an ERC-20, an ERC-721 or an ERC-1155 to an address.
See [Transfer](https://moss.megaeth.com/developers/methods/sending-funds/transfer).

```ts title="Types"
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;
}
```

```ts title="Example"
import { parseUnits } from 'viem';

const result = await mega.transfer({
    type: 'erc20',
    to: '0xFD8D73c93385271d06138FA0Ff6E9c639C3Bd8b0',
    contractAddress: '0x2715b6d04b6a0AB227631019899282a585Be410F',
    amount: parseUnits('1', 18).toString(),
});
```

### `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](https://moss.megaeth.com/developers/methods/sending-funds/checkout) and [Ramps](https://moss.megaeth.com/developers/concepts/ramps).

```ts title="Types"
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}`;
}
```

```ts title="Example"
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);
}
```

### `send`

Opens the wallet's send screen, optionally with a token and destination filled in.
See [Send](https://moss.megaeth.com/developers/methods/sending-funds/send).

```ts title="Types"
send: (request: SendRequest) => Promise<TransactionResult>;

interface SendRequest {
    token?: `0x${string}` | 'native';
    destination?: `0x${string}`;
}
```

```ts title="Example"
const result = await mega.send({});
```

## Tokens

### `deposit`

Opens the wallet's deposit screen, where the user can buy tokens or bridge them in.
See [Deposit](https://moss.megaeth.com/developers/methods/deposit), [Ramps](https://moss.megaeth.com/developers/concepts/ramps) and
[Bridging](https://moss.megaeth.com/developers/concepts/bridging).

```ts title="Types"
deposit: () => Promise<void>;
```

```ts title="Example"
await mega.deposit();
```

### `swap`

Opens the wallet's swap screen, optionally with the tokens filled in.
See [Swap](https://moss.megaeth.com/developers/methods/swap) and [Swaps](https://moss.megaeth.com/developers/concepts/swaps).

```ts title="Types"
swap: (request: SwapRequest) => Promise<TransactionResult>;

interface SwapRequest {
    fromToken?: `0x${string}` | 'native';
    toToken?: `0x${string}` | 'native';
}
```

```ts title="Example"
const result = await mega.swap({
    fromToken: 'native',
    toToken: '0x2715b6d04b6a0AB227631019899282a585Be410F',
});
```

### `balances`

Returns the connected account's token balances, for every token it holds or just the ones you list.
See [Balances](https://moss.megaeth.com/developers/methods/balances).

```ts title="Types"
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;
}
```

```ts title="Example"
const balances = await mega.balances({ tokens: ['0x2715b6d04b6a0AB227631019899282a585Be410F'] });

for (const token of balances) {
    console.log(token.symbol, token.displayBalance);
}
```

### `collectible`

Opens the wallet on one of the user's collectibles.
See [Collectible](https://moss.megaeth.com/developers/methods/collectible).

```ts title="Types"
collectible: (request: CollectibleRequest) => Promise<void>;

interface CollectibleRequest {
    address: `0x${string}`;
    tokenId: string;
}
```

```ts title="Example"
await mega.collectible({
    address: '0x9416E9a7E89ceF6ECF97A6D7Cc4b58E128d0d3bb',
    tokenId: '1',
});
```

## MegaNames

### `fromMegaName`

Returns the address a MegaName points to, or `undefined` when it isn't registered.
See [From MegaName](https://moss.megaeth.com/developers/methods/meganames/from-mega-name).

```ts title="Types"
fromMegaName: (name: string) => Promise<`0x${string}` | undefined>;
```

```ts title="Example"
const address = await mega.fromMegaName('alice.mega');
```

### `toMegaName`

Returns the MegaName for an address, or `undefined` when it has none.
See [To MegaName](https://moss.megaeth.com/developers/methods/meganames/to-mega-name).

```ts title="Types"
toMegaName: (address: `0x${string}`) => Promise<string | undefined>;
```

```ts title="Example"
const name = await mega.toMegaName('0xFD8D73c93385271d06138FA0Ff6E9c639C3Bd8b0');
```

## 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](https://moss.megaeth.com/developers/methods/connecting/initialise).

```ts title="Types"
class MegaInitError extends Error {
    code: 'HANDSHAKE_TIMEOUT' | 'CONNECTION_FAILED';
}
```

```ts title="Example"
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');
    }
}
```
