# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
This site has an agentic ask interface you may use to query the documentation dynamically by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.aurowallet.com/general/index.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

---

# Getting Started

Welcome to the Auro Wallet documentation!

{% hint style="info" %}
[@aurowallet/mina-provider](https://www.npmjs.com/package/@aurowallet/mina-provider) is the middleware on the Mina Protocol used for interaction between zkApp and Auro Wallet. This document is mainly used to introduce the functions of Mina Provider and how to use the API.
{% endhint %}

## How to integrate

***

Introduce all the methods provided by Mina Provider and how zkApp can better work with Auro Wallet.

{% content-ref url="/pages/W02h0KR0YQ6JauAA5loL" %}
[How to integrate](/general/howto)
{% endcontent-ref %}

## API Reference

***

Dive a little deeper and start exploring our API reference to get an idea of everything that's possible with the API:

{% content-ref url="/pages/kDeq64jDpsNpp5GyENJY" %}
[API Reference](/general/reference/api-reference)
{% endcontent-ref %}

If you want to help us maintain the documentation. please refer to: [Auro Wallet/docs](https://github.com/aurowallet/docs).


# How to integrate

Here are some scenarios, you can find demo of use here.

{% content-ref url="/pages/3NOFYOloB2gb40e8qMKy" %}
[Connect Wallet](/general/howto/connect-wallet)
{% endcontent-ref %}

{% content-ref url="/pages/lfqfz3nBH2nZIGRNM7pb" %}
[Add or Switch Chain](/general/howto/add-or-switch-chain)
{% endcontent-ref %}

{% content-ref url="/pages/Bcr9AOlYBaoV1Vb4t4JD" %}
[Create Nullifier](/general/howto/create-nullifier)
{% endcontent-ref %}

{% content-ref url="/pages/ZJwShen3E4lWd6kWRdxx" %}
[Send zk Transaction](/general/howto/send-zk-transaction)
{% endcontent-ref %}

{% content-ref url="/pages/k52vRMgDFWRzBwFtVulL" %}
[Sign Message](/general/howto/sign-message)
{% endcontent-ref %}

{% content-ref url="/pages/2HPiGQskwWAAteLWfwUk" %}
[VerifyMessage in server-side](/general/howto/verifymessage-in-server-side)
{% endcontent-ref %}

{% hint style="info" %}
Here are only the APIs for some scenarios. For the full API, please see the [API Reference](/general/reference/api-reference).
{% endhint %}


# Connect Wallet

Scenarios for connect wallets and request accounts.

{% hint style="info" %}
When using the API, you need to ensure that the browser has successfully obtained the **`window.mina`** object.
{% endhint %}

The presence of the mina provider object `window.mina`, in a user's browser indicates an Mina Protocol user.

To demonstrate this, verify whether your browser is running Auro Wallet by copying and pasting the following code snippet into your browser's developer console.

```javascript
if (typeof window.mina !== 'undefined') {
  console.log('Auro Wallet is installed!');
}
```

## Request Account

Interactive with Auro Wallet require connect account. This method returns an array when user confirm authorizes, which contains address that authenticated. The current array returns one address at a time. Returns a ProviderError when user reject authorization.

```typescript
const account:string[]|ProviderError = await window.mina.requestAccounts()
    .catch((err: any) => err);

console.log(account)
```

{% hint style="info" %}
**requestAccounts** will show a popup window when Auro Wallet lock or have no connected account, if you want to request account without popup window. You can use [getAccounts](/general/reference/api-reference/methods/mina_accounts).
{% endhint %}

```javascript
let account = await window.mina?.getAccounts();

console.log(account);
```

## Account Event

This method is used to monitor account changes. When the account changes, the monitoring will be trigger.

```typescript
window.mina?.on("accountsChanged", (accounts: string[]) => {
    console.log(accounts);
});
```


# Add or Switch Chain

Scenarios for interact chain with Auro Wallet.

## RequestNetwork

During initialization, zkApp can get current networkID by call `requestNetwork`.

```typescript
const network: ChainInfoArgs = await window.mina?.requestNetwork()
  .catch((err: any) => err);
```

## `SwitchChain`

zkApp can switch chain by this method.&#x20;

The following are the networkID that Auro supports by default. If you want to use other networkID, need to add network first, then use the target networkID as a parameter to switch.

> Current support these networkID (default):
>
> * mina:mainnet
> * mina:devnet // Update from mina:testnet to mina:devnet from extension 2.3.1, App 2.1.0
> * zeko:testnet

```typescript
type ChainInfoArgs = {
    networkID: string;
};

interface ProviderError extends Error {
    message: string;
    code: number;
    data?: unknown;
}

const switchResult:ChainInfoArgs|ProviderError = await window.mina
    ?.switchChain({
        networkID: networkID.trim(),
    }).catch((err: any) => err);
```

{% hint style="danger" %}

```markdown
** Please update as soon as possible. **
`ChainInfoArgs` params have updated from App 2.0.2 & extension 2.2.17.
Only `networkID` is returned, no longer supports returning `chainId` and `name`. 

// @deprecated from App 2.0.2 & extension 2.2.17.
type ChainInfoArgs ={ 
    chainId:string,
    name:string
}
```

{% endhint %}

## Add Chain

If want to custom the adding chain or switch chain, can use this method. When the URL has been added, it will request to switch to chain corresponding to the URL.

```typescript
const addInfo = {
  url: encodeURIComponent("graphQLURL"),
  name: "networkName",
}

const addResult:ChainInfoArgs|ProviderError = await window.mina?.addChain(addInfo)
  .catch((err: any) => err);
```

## Chain Event

This method is used to listen chain changes. When the Auro Wallet chain change, the event will be trigger.

```typescript
window.mina?.on("chainChanged",(chainInfo: ChainInfoArgs) => {
  console.log(chainInfo);
});
```


# Create Nullifier

Mainly used to create nullifier.

```typescript
type Group = {
    x: bigint;
    y: bigint;
};

type Nullifier = {
    publicKey: Group;
    public: {
        nullifier: Group;
        s: bigint;
    };
    private: {
        c: bigint;
        g_r: Group;
        h_m_pk_r: Group;
    };
};

interface ProviderError extends Error {
    message: string;
    code: number;
    data?: unknown;
}

const signResult: Nullifier|ProviderError = await window.mina
    ?.createNullifier({
        message: [1,2,3] // or ["1", "2", "3"]
    }).catch((err: any) => err);
```


# Send Transaction

This scenario is mainly used to handle common methods, such as send payment and stake delegation.

## Send Payment

This method is used to send MINA.

```typescript
// success data
type SendTransactionResult = {
    hash: string;
};
// failed data
interface ProviderError extends Error {
    message: string;
    code: number;
    data?: unknown;
}

let data: SendTransactionResult|ProviderError = await window.mina
    ?.sendPayment({
        amount: amount,
        to: receiveAddress,
        fee: fee, // option
        memo: memo, // option
    })
    .catch((err: any) => err);
```

## Stake Delegation

This method is used to call stake delegation.

```typescript
let data: SendTransactionResult|ProviderError = await window.mina
    ?.sendStakeDelegation({
        to: vaildatorAddress,
        fee: fee, // option
        memo: memo, // option
    }).catch((err: any) => err);
```


# Send zk Transaction

This scenario is mainly used to create zk-contract or update zk-contracts.

## Update zk contract

This method is use to sign and broadcast zk transaction.

```typescript
type SendTransactionHash = {
  hash: string;
};

type SignedZkappCommand = {
  signedData: string; // results of JSON.stringify( signZkappCommand().data )
};

type SendZkTransactionResult = SendTransactionResult | SignedZkappCommand

interface ProviderError extends Error {
    message: string;
    code: number;
    data?: unknown;
}

interface SendTransactionArgs {
    readonly onlySign?: boolean; // auro-extension-wallet support from V2.2.16. 
    readonly nonce?: number; // auro-extension-wallet support from V2.3.0. 
    readonly transaction: string | object;
    readonly feePayer?: {
        readonly fee?: number;
        readonly memo?: string;
    };
}

const updateResult: SendZkTransactionResult| ProviderError= await window.mina?
    .sendTransaction({
      onlySign: onlySign, // only sign zkCommond, not broadcast.
      transaction: transactionJSON, // this is zk commond, create by zkApp.
      feePayer: { // option.
        fee: fee,
        memo: memo
      },
    });

console.log(updateResult);
```

{% hint style="info" %}
Here is an demo of update a zk contract. To create a zkApp contract, you need to use [o1js](https://www.npmjs.com/package/o1js) to sign first, then use Auro Wallet to sign the result of o1js signed. The created zkApp contract demo is [here](https://github.com/aurowallet/test-zkapp/blob/feature/zk/ui/src/components/HomeComponents/SignTransactionBox.tsx#L263).
{% endhint %}


# Sign Message

This scenario is mainly used to sign information. that can be used for login verification.

## Sign Message

This method is used for sign message.

```typescript
interface SignedData {
    publicKey: string;
    data: string;
    signature: {
        field: string;
        scalar: string;
    };
}

interface ProviderError extends Error {
    message: string;
    code: number;
    data?: unknown;
}
type SignMessageArgs = {
    message:string
}

const content = `Click "Sign" to sign in. No password needed!

This request will not trigger a blockchain transaction or cost any gas fees.

I accept the Auro Test zkApp Terms of Service: ${window.location.href}

address: ${currentAccount}
iat: ${new Date().getTime()}`;

const signContent:SignMessageArgs = {
    message:content
}

const signResult: SignedData|ProviderError = await window.mina?
     .signMessage(signContent)
     .catch((err: any) => err);

console.log(signResult)
```

## Sign Json Message

This method is used for sign JSON data , Auro Wallet will format message.

```typescript
type JsonMessageData  = {
    label:string
    value:string
}

type SignJsonMessageArgs = {
    readonly message: Array<JsonMessageData>
}

const msgParams = [
    { label: "Label:", value: "Sign Confirm" },
    {
      label: "Message:",
      value: "Click to sign in and accept the Terms of Service",
    },
    {
      label: "URI:",
      value: window.location.href,
    },
    {
      label: "networkID:",
      value: network.networkID,
    },
    {
      label: "Chain Name:",
      value: network.name,
    },
    {
      label: "Issued At:",
      value: new Date().getTime(),
    },
    {
      label: "Resources:",
      value: "https://docs.aurowallet.com/",
    },
    ];
  
const signResult:SignedData|ProviderError = await window.mina
    ?.signJsonMessage({
        message: msgParams
    })
    .catch((err: any) => err);

console.log(signResult);
```

## Verify Message

This methods is used for verify signed Message.

```typescript
let verifyResult:boolean|ProviderError = await window.mina
    ?.verifyMessage(verifyMessageBody)
    .catch((err: any) => err);
  
console.log(verifyResult); // If the result is successful, it will return true.
```


# VerifyMessage in server-side

This scenario mainly explains how the server-side verify the result of the signMessage. Fields verification can also be implemented using mina-signer. Only signMessage examples are provided here.

{% hint style="info" %}
The features is implemented through [mina-signer](https://www.npmjs.com/package/mina-signer).

**mina-signer** is the NodeJS SDK provided by Mina Protocol for sign, verify signatures, etc.
{% endhint %}

## Verify Message

1. Add **mina-signer** to `package.json`.

```json
"dependencies": {
    "mina-signer": "2.1.1"
}
```

2. Import and init **mina-signer**.

```typescript
var Client = require("mina-signer");

// type Network = 'mainnet' | 'testnet'
var signerClient = new Client({ network: "mainnet" });
```

{% hint style="info" %}
There are two types of initialization supported here. The main network type is **mainnet**, and the type of other network are **testnet**. [See original definition.](https://github.com/o1-labs/o1js/blob/main/src/mina-signer/src/TSTypes.ts#L12)
{% endhint %}

3. Implement code.

```javascript
const publicKey = 'B62qj6z7oseWTr37SQTn53mF8ebHn45cmSfRC58Sy52wG6KcaPZNWjw'

const verifyMessage = `Click "Sign" to sign in. No password needed!

  This request will not trigger a blockchain transaction or cost any gas fees.
  
  I accept the Auro Test zkApp Terms of Service: https://test-zkapp.aurowallet.com
  
  address: B62qj6z7oseWTr37SQTn53mF8ebHn45cmSfRC58Sy52wG6KcaPZNWjw
  iat: 1701069403643`;

const signature = {
    field: '25087624681052481871246375076085075176624243458008290192358519021588472251513',
    scalar: '17285357755862735391605884635523872951699156489623612197745807470058903167470'
}

const verifyBody = {
    data: verifyMessage, // Signature content that needs to be verified.
    publicKey: publicKey, // Public key that needs to be verified.
    signature: signature, // Signature results that need to be verified.
};

// When verifyResult is true, the verification is successful.
const verifyResult = signerClient.verifyMessage(verifyBody);
```

{% hint style="success" %}
This is an [example of server-side](https://github.com/aurowallet/mina-signer-verify-example) verification of signature. You can refer to the implementation or run it locally.
{% endhint %}


# Anonymous Credentials

This scenario is mainly used to handle the store credentials and verifying presentations.

## Store Credentials

This method is mainly used to save credentials.

```typescript
type JSONValue =
    | string
    | number
    | boolean
    | null
    | JSONValue[]
    | { [key: string]: JSONValue };


type Credential<Data = unknown> = { owner: string; data: Data };
type StoredCredential<Data = unknown, Witness = unknown> = {
    version: 'v0';
    witness: Witness;
    metadata: JSONValue | undefined;
    credential: Credential<Data>;
};

type StoredCredentialArgs = {
    credential:StoredCredential
}

const storeResult: IStoreCredentialData = await window.mina
    .storePrivateCredential({
        credential: credential,
    })
    .catch((err: any) => err);
```

## Verifying Presentations

This method is mainly used to verify the presentation.

```typescript
type PresentationRequestType = 'no-context' | 'zk-app' | 'https';
type PresentationRequest<
  RequestType extends PresentationRequestType = PresentationRequestType,
  InputContext = any,
> = {
    type: RequestType;
    spec: any;
    claims: any;
    inputContext: InputContext;
    program?: unknown;
    verificationKey?: unknown;
};

type IPresentationRequest = {
    presentationRequest:PresentationRequest
    zkAppAccount?:any // used for type zk-app
}

type PresentationArgs = {
    presentation:IPresentationRequest
}


const verifyResult: IRequestPresentation = await window.mina
    .requestPresentation({
      presentation: {
        presentationRequest: presentationRequest,
      },
    })
    .catch((err: any) => err);
```

{% hint style="info" %}
The current implementation of Anonymous Credentials is based on [mina-attensions](https://github.com/zksecurity/mina-attestations) v0.5.0
{% endhint %}


# Wallet Basics


# Submit token info

Auro Wallet will support the transfer of token assets submitted by default.

[**Click here to submit the information.**](https://github.com/aurowallet/launch/tree/master/token)

#### 1. Add token information by updating the `token.json` file (in the corresponding network). Do not change the order.

```typescript
// This is an example submission
{
    "id": "xLpobAxWSYZeyKuiEb4kzHHYQKn6X1vKmFR4Dmz9TCADLrYTD1", // token id
    "address": "B62qmMv99rMLCjnApLERcvof6fP4YD4wqeCXUrFuthHfTNoHbYgmy1i", // token address
    "name": "TEST", // token name
    "symbol": "7UjV6", // token symbol
    "decimal": "6", // token decimal
    "description": "Auro test token in Mainnet", // Optional. token description
    "website":"https://www.aurowallet.com/", // Optional. 
    "fungibleTokenVersion": "1.1.0" // Optional. 
}
```

```md
`fungibleTokenVersion` is an optional field. 
The content should be one of the version fields in https://www.npmjs.com/package/mina-fungible-token

The content is the version of mina-fungible-token currently in use.
Auro Wallet uses the latest version by default.

- If set, Auro Wallet will use the target version of the mina-fungible-token.
- If not set, the latest mina-fungible-token will be used by default.

Custom tokens `do not need` to set fungibleTokenVersion.
```

#### 2. Create a folder with the token ID and add your token icon to `{networkID}/assets/{tokenID}/icon.png`.

* Icon resolution must be 128\*128px.
* The icon file name must be `icon.png`.

#### 3. Send token for testing

You can use the Mainnet or Testnet for this. The purpose is to test whether the token can be send normally before the merge. Send tokens to the following address for testing:

**`B62qpjxUpgdjzwQfd8q2gzxi99wN7SCgmofpvw27MBkfNHfHoY2VH32`**

We will send token to your sending address after the test is completed (return to the original address).

#### 4. Provide the token contract source code (Optional)

We currently use the [fungible token contract](https://github.com/MinaFoundation/mina-fungible-token/releases/tag/v1.0.0). If you modify the contract code, it may cause a mismatch between the token contract and the source code. To prevent this, it is recommended to submit the token contract source code in the PR, so it can be integrated into the build service.

* Example location: `token/{networkID}/assets/xLpobAxWSYZeyKuiEb4kzHHYQKn6X1vKmFR4Dmz9TCADLrYTD1/source`

#### 5. Verify Token Ownership

Add the signature of the `token.json` file submitted or updated in step 1 to the PR comment. This should be signed using the token account. Now can get the signed message in [Auro-Test-zkApp](https://test-zkapp.aurowallet.com/token-submit).

* ```js
  // After signed, submit the result in the comment
  {"field":"10082789485841188200651752083435401189651661935760768844006925598425995295018","scalar":"13559698666955008071097956591497128241909562564253145138590504826423557135826"}
  ```

#### 6. Make a PR

Once all steps are completed, create a PR for review.

{% hint style="info" %}
**Disclaimer**

Auro Wallet provides this repository and its contents on an "AS IS" and "AS AVAILABLE" basis without any representations or warranties of any kind, either express or implied. To the fullest extent permitted by applicable law, Auro Wallet expressly disclaims all warranties, including but not limited to:

1. Warranty of Merchantability: No assurance is provided that the tokens or associated services are merchantable or fit for sale.
2. Warranty of Fitness for a Particular Purpose: Auro Wallet does not guarantee that the tokens or associated services will meet your specific requirements or expectations.
3. Warranty of Title: Auro Wallet does not warrant that it owns or has the necessary rights to provide the tokens or associated services without encumbrances.
4. Warranty Against Infringement: Auro Wallet makes no representations regarding non-infringement of intellectual property or other proprietary rights of any third party.

These disclaimers apply regardless of whether the warranties are implied by law, arise from a course of dealing, course of performance, usage of trade, or otherwise.
{% endhint %}


# Mina Providers

Starting from Auro Extension 2.3.0 and Auro App 2.1.0, Auro Wallet introduces a new method to use providers, called "Announce Provider," which supports multiple providers.

## 1. Announce Provider (Recommended)

```ts
let auroProvider: any; 
useEffect(() => {
    const handleAnnounceProvider = async (event: any) => {
      if (!auroProvider) {
        if (
          event?.detail?.info?.slug === "aurowallet" ||
          event?.detail?.provider?.isAuro
        ) {
          auroProvider = event?.detail?.provider;
        }
      }
      if (auroProvider) {
        // can excute action in here
      }
    };

    window.addEventListener("mina:announceProvider", handleAnnounceProvider);

    window.dispatchEvent(new Event("mina:requestProvider"));
    setTimeout(() => {
      window.dispatchEvent(new Event("mina:requestProvider"));
    }, 1000);

    return () => {
      window.removeEventListener(
        "mina:announceProvider",
        handleAnnounceProvider
      );
    };
  }, []);
```

## 2. Use window\.mina

This method is always available and will not be deprecated.

`window.mina && window.mina.isAuro`


# Auro Mobile


# Use with WalletConnect

Auro Mobile supports WalletConnect, allowing seamless integration of zkApp with Auro Mobile with QR code scanning or deep linking.

{% hint style="info" %}
The Auro Wallet in-app browser does not support building zkApps (due to [SharedArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer) limitations). Therefore, you need to build the zkApp in an external mobile browser and interact with Auro Wallet via deeplink.\
\
This feature is available in **Auro Mobile v2.1.2 or later**. Please update to the latest version to use this feature. On iOS, WalletConnect event handling in the mobile browser (e.g., Safari) is supported starting from **v2.2.1**.
{% endhint %}

## Step

1. Get projectId from [Reown](https://cloud.reown.com/).
2. Init client.

```ts
const client = await SignClient.init({
  projectId: process.env.NEXT_PUBLIC_WALLET_CONNECT_PROJECY_ID,
  metadata: {
    name: "Auro Wallet Demo",
    description: "A Mina Protocol dApp with WalletConnect",
    url: window.location.origin,
    icons: ["https://www.aurowallet.com/imgs/auro_icon.png"],
  },
  logger: "warn",
});
```

3. Request connect wallet.

```ts
const connectParams = {
  requiredNamespaces: {
    mina: {
      chains: ["mina:mainnet", "mina:devnet", "zeko:testnet"], // Chains currently supported by the zkApp, requiring Auro Wallet support.
      methods: [
        // The current zkApp requires the following methods, consistent with other methods supported by Auro Wallet.
        // The supported methods are listed below:
        // List only the required methods:
        "mina_sendPayment",
        "mina_sendStakeDelegation",
        "mina_sendTransaction",
        "mina_signMessage",
        "mina_sign_JsonMessage",
        "mina_signFields",
        "mina_createNullifier",
        "mina_verifyMessage",
        "mina_verify_JsonMessage",
        "mina_verifyFields",
        "wallet_info",
      ],
      events: ["accountsChanged", "chainChanged"],
    },
  },
};
```

4. Set Up Event Listener (Optional).\
   If the app requires authorization or signing, you can configure it to trigger the app for operations upon a successful callback, or prompt the user in the zkApp to manually switch to Auro Wallet. Note that on iOS, ensure user interaction for any deep link redirects as per the considerations above.

```ts
client.on("session_request_sent", (event: any) => {
  console.log("Session request sent:", event);
  if (
    [
      "mina_sendPayment",
      "mina_sendStakeDelegation",
      "mina_sendTransaction",
      "mina_signMessage",
      "mina_sign_JsonMessage",
      "mina_signFields",
      "mina_createNullifier",
    ].includes(event?.request?.method)
  ) {
    const isMobile = /iPhone|iPad|iPod|Android/i.test(navigator.userAgent);
    const isIOS = /iPhone|iPad|iPod/i.test(navigator.userAgent);
    if (isMobile) {
      if (isIOS) {
        console.log("iOS: Dispatching wallet prompt for", event.request.method);
        window.dispatchEvent(new CustomEvent("showOpenWalletPrompt", { detail: { action: "request", method: event.request.method } }));
      } else {
        const deepLink = `aurowallet://`;
        console.log("Auro Wallet Deep Link for request (Android):", deepLink);
        openDeepLink(deepLink);
      }
    }
  }
});
```

5. UI Interaction.

```ts
const handleSendZkTransaction = async () => {
  if (!client || !session || !account) {
    setError("Please connect wallet first");
    return;
  }
  const zkTransaction = await getZkBuildBody(selectedChain, account);
  const zkRequest = {
    topic: session.topic,
    chainId: selectedChain,
    request: {
      method: "mina_sendTransaction",
      params: {
        // Optional: Specifies the current browser's scheme.
        // If set, the app automatically returns to the provided scheme's browser;
        // otherwise, the app only displays a pop-up prompting the user to return.
        scheme: chromeScheme,
        from: account,
        transaction: zkTransaction,
        feePayer: {
          fee: "0.01", // Optional
          memo: "test zkApp", // Optional
        },
      },
    },
  };
  const result = await client.request(zkRequest);
};
```

{% hint style="warning" %}

### iOS-Specific Considerations

Auro Wallet on iOS supports WalletConnect, but there are platform-specific differences compared to Android due to iOS security and background execution policies.

#### 1. Redirect (Jump) Issues

iOS only supports Universal Links (applinks) for redirects, and these require genuine user interaction (e.g., a tap) to trigger the app opening. This is a security measure to prevent malicious programmatic redirection without user consent. For more details, see Apple's documentation on [Universal Links](https://developer.apple.com/library/archive/documentation/General/Conceptual/AppSearch/UniversalLinks.html).

Without user interaction, attempting a redirect may first open the associated webpage before launching Auro Wallet, leading to a suboptimal user experience.

On Android, custom URL schemes are recommended for direct redirects. Using Universal Links on Android can result in similar issues as on iOS.

#### 2. Background Execution Issues

When Auro Wallet is in the background on iOS, the app is suspended by the operating system, preventing it from receiving WalletConnect service messages (e.g., via WebSocket connections to the relay server). This affects events that do not trigger an app wake-up, such as `wallet_info` or `verify` requests. To handle these, you must explicitly open Auro Wallet (e.g., via deep link) to process the response.

For official guidance on iOS background execution, refer to Apple's [Configuring background execution modes](https://developer.apple.com/documentation/xcode/configuring-background-execution-modes).

Android handles background WalletConnect messages normally without suspension.
{% endhint %}

#### Reference Links

**Test Website**\
[Visit Test Website](https://test-zkapp.aurowallet.com/wallet-connect) **Core Code Examples**

* [UI Code](https://github.com/aurowallet/test-zkapp/blob/master/ui/src/pages/wallet-connect.page.tsx)
* [Initialization Code](https://github.com/aurowallet/test-zkapp/blob/master/ui/src/utils/walletConnect.ts) **WalletConnect Integration Documentation**
* [WalletConnect Sign Client](https://docs.reown.com/advanced/api/sign/overview)
* [Reown AppKit](https://docs.reown.com/appkit-overview)


# ​Pull Up Auro Wallet with DeepLink

This document describes how to use a deep link to open the Auro Mobile Wallet and launch a zkApp within the App. This feature is supported starting from Auro Mobile Wallet version 2.1.0.

## **Pull Up the wallet to** launch **zkApp**

```javascript
let targetURL = ""; // Required, the target URL, e.g., https://www.aurowallet.com/
let paramsURL = encodeURIComponent(targetURL);

let targetNetworkId = ""; // Optional, the target network ID, e.g., mina:mainnet. You can retrieve this from the daemon node. If not provided, the App will use its current network by default.
let networkId = encodeURIComponent(targetNetworkId);

const endURL = `https://applinks.aurowallet.com/applinks?action=openurl&networkid=${networkId}&url=${paramsURL}`;
window.location.href = endURL;

```

Currently, there are 3 parameters supported:

* **`action`** (Required)

  The action that the App will excute. Currently, only `openurl` is supported.
* **`networkid`** (Optional)

  The ID of the target network. You can get this value from a GraphQL endpoint. If supported, the App will switch to the target network. If not supported, no changes will be made. If not set, the App will default to its current network.

```graphql
## Example GraphQL query:
query myQuery {
    networkID
}
```

* **`url`** (Required)

  The URL the App will open. It is recommended to include this at the end of the deep link URL.

{% hint style="info" %}
**Note**: This method is limited to pulling up the Auro Wallet via the mobile phone's system browser.
{% endhint %}


# API Reference

Dive into the specifics of each API endpoint by checking out our complete documentation.

## Mina Provider

{% content-ref url="/pages/6wNFqOIMbzvxwQg5ACzC" %}
[Methods](/general/reference/api-reference/methods)
{% endcontent-ref %}

{% content-ref url="/pages/GyzjGEJboe6V4ZeRhJG6" %}
[Events](/general/reference/api-reference/events)
{% endcontent-ref %}

{% content-ref url="/pages/jOG5RMexB3fPFUygvW5W" %}
[Error](/general/reference/api-reference/error)
{% endcontent-ref %}

{% content-ref url="/pages/JxlTijHasfN0jOZgT5CA" %}
[Source](/general/reference/api-reference/source)
{% endcontent-ref %}


# Methods

Here are descriptions and examples of all methods.


# mina\_accounts

This method is used to request the current connected account. It is a silent request. If there is a connected account, it will return the connected account. If not, it will return an empty array.

### Params

null

### Result

string\[]

### Errors

null

### Example

#### Request

```typescript
await window.mina?.getAccounts();
```

#### Result

```typescript
// have connect account.
["address"]

// if not 
[] 
```


# mina\_requestAccounts

This method is used to request the current connect account. If there is a connected account, the connected account will be returned. If not, a popup window will show to request a connection.

### Params

null

### Result

```typescript
interface ProviderError extends Error {
    message: string; // error message.
    code: number; // error code.
    data?: unknown; // error body. 
}

// string[] will contain the connected account address.
Promise<string[] | ProviderError>
```

### Error

<table><thead><tr><th></th><th width="332.3333333333333"></th><th></th></tr></thead><tbody><tr><td>1002</td><td>The request was rejected by the user.</td><td></td></tr><tr><td>20001</td><td>No account found.</td><td>Need create or restore account in Auro Wallet first.</td></tr><tr><td>23001</td><td>Origin dismatch.</td><td>Check origin safe.</td></tr></tbody></table>

## Example

### Request

```typescript
await window.mina.requestAccounts().catch((err: any) => err);
```

### Result

```typescript
// user reject.
{
  "code": 1002,
  "message": "User rejected the request. "
}

// successful result.
[
  "B62qpjxUpgdjzwQfd8q2gzxi99wN7SCgmofpvw27MBkfNHfHoY2VH32"
]
```


# mina\_requestNetwork

This method is used to request the chain info of the Auro wallet.

### Params

null

### Result

```typescript
type ChainInfoArgs ={
    // current networkID, now will return mina:mainnet, mina:devnet, zeko:testnet
    networkID:string
}

Promise<ChainInfoArgs>
```

{% hint style="danger" %}

```markdown
** Please update as soon as possible. **
`ChainInfoArgs` params have updated from App 2.0.2 & extension 2.2.17.
Only `networkID` is returned, no longer supports returning `chainId` and `name`. 

// @deprecated from App 2.0.2 & extension 2.2.17.
type ChainInfoArgs ={ 
    chainId:string,
    name:string
}
```

{% endhint %}

### Errors

null

## Example

### Request

```typescript
await window.mina?.requestNetwork().catch((err: any) => err);
```

### Result

```typescript
{
  "networkID": "mina:mainnet"
}
```


# mina\_sendPayment

This method is used to call  Auro Wallet send payment (current support send MINA ) by zkApp.

### Params

```typescript
interface SendPaymentArgs  {
    // to is the target address. require base58 address. 
    readonly to: string
    // amount is the send amount, with decimal. e.g. 1.1
    readonly amount: number
    // option. Auro Wallet also provide advance option to change fee.
    readonly fee?: number
    // option.
    readonly memo?:string
}
```

### Result

<pre class="language-typescript"><code class="lang-typescript"><strong>type SendTransactionResult = {
</strong>    // broadcast hash, you can query tx info by this hash.
    hash: string
}

interface ProviderError extends Error {
    message: string; // error message.
    code: number; // error code.
    data?: unknown; // error body. 
}

Promise&#x3C;SendTransactionResult | ProviderError>
</code></pre>

### Errors

|       |                                            |                                    |
| ----- | ------------------------------------------ | ---------------------------------- |
| 1001  | User disconnect, need connect Auro Wallet. | Can not get connected account.     |
| 1002  | The request was rejected by the user.      |                                    |
| 20003 | The parameters were invalid.               | Please check address, amount, fee. |
| 23001 | Origin dismatch.                           | Check origin safe.                 |

## Example

### Request

```typescript
const amount = 0.1;
const receiveAddress = "B62qpjxUpgdjzwQfd8q2gzxi99wN7SCgmofpvw27MBkfNHfHoY2VH32"
const fee = 0.012
const memo = "Auro Wallet"

await window.mina?.sendPayment({
        amount: amount,
        to: receiveAddress,
        fee: fee,
        memo: memo,
    }).catch((err: any) => err);
```

### Result

```typescript
// successful result.
{
  "hash": "CkpZj7QwDkfzoyPfMiJj9zTC6R41Sbh9fY4yvKsSYM9zjyyTUDwW9"
}

// user reject.
{
  "code": 1002,
  "message": "User rejected the request."
}

// can not get connect address.
{
  "code": 1001,
  "message": "User disconnect, please connect first."
}

// params check error. there check addres, amount and fee.
{
  "code": 20003,
  "message": "Invalid method parameter(s)."
}
```


# mina\_sendStakeDelegation

This method is used by zkApp to call Auro Wallet stake delegation.

### Params

```typescript
type SendStakeDelegationArgs  = {
    // block producer address. require base58 address.
    readonly to: string,
    // option. Auro Wallet also provide advance option to change fee.
    readonly fee?: number,
    // option.
    readonly memo?:string
}
```

### Result

```typescript
type SendTransactionResult = {
    // broadcast hash, you can query tx info by this hash.
    hash: string
}

interface ProviderError extends Error {
    message: string; // error message.
    code: number; // error code.
    data?: unknown; // error body. 
}

Promise<SendTransactionResult | ProviderError>
```

### Errors

|       |                                            |                                |
| ----- | ------------------------------------------ | ------------------------------ |
| 1001  | User disconnect, need connect Auro Wallet. | Can not get connected account. |
| 1002  | user reject transaction.                   |                                |
| 20003 | The parameters were invalid.               | Please check address, fee.     |
| 23001 | Origin dismatch.                           | Check origin safe.             |

## Example

### Request

```typescript
const vaildatorAddress = "B62qq3TQ8AP7MFYPVtMx5tZGF3kWLJukfwG1A1RGvaBW1jfTPTkDBW6"
const fee = 0.011
const memo = ""

await window.mina?.sendStakeDelegation({
    to: vaildatorAddress,
    fee: fee, // option. If not use, can delet this params.
    memo: memo, // option. If not use, can delet this params.
}).catch((err: any) => err);
```

### Result

```typescript
// successful result.
{
  "hash": "CkpYTcQv2obKrD78X7QoHF9j3CfmQWNjNb8UFeDaCVRjcGZpUdxUz"
}

// user reject.
{
  "code": 1002,
  "message": "User rejected the request."
}

// can not get connect address.
{
  "code": 1001,
  "message": "User disconnect, please connect first."
}

// params check error. there check addres and fee.
{
  "code": 20003,
  "message": "Invalid method parameter(s)."
}
```


# mina\_sendTransaction

This method is used for sign and broadcast zkApp transaction.

{% hint style="info" %}
You need to create zk commond in zkApp first, then call Auro Wallet to sign and broadcast.
{% endhint %}

### Params

```typescript
interface SendTransactionArgs  {
    // only sign with auro wallet, auro-extension-wallet support from V2.2.16. 
    readonly onlySign?: boolean; 
    // custom nonce with auro wallet, auro-extension-wallet support from V2.3.0. 
    readonly nonce?: number; 
    // transaction is zk commond that create by contract.
    readonly transaction: string | object;
    // option. 
    readonly feePayer?: {
        // option. Auro Wallet also provide advance option to change fee.
        readonly fee?: number;
        // option.
        readonly memo?: string;
    };
}
```

### Result

```typescript
type SendTransactionHash = {
    // broadcast hash, you can query tx info by this hash.
    hash: string;
};

type SignedZkappCommand = {
    // results of JSON.stringify( signZkappCommand().data )
    signedData: string; 
};

type SendZkTransactionResult = SendTransactionResult | SignedZkappCommand

interface ProviderError extends Error {
    message: string; // error message.
    code: number; // error code.
    data?: unknown; // error body. 
}

Promise<SendTransactionResult | ProviderError>
```

### Errors

|       |                                            |                                |
| ----- | ------------------------------------------ | ------------------------------ |
| 1001  | User disconnect, need connect Auro Wallet. | Can not get connected account. |
| 1002  | The request was rejected by the user.      |                                |
| 20003 | The parameters were invalid.               | Please check address, fee.     |
| 23001 | Origin dismatch.                           | Check origin safe.             |

## Example

### Request

```typescript
const transactionJSON = {"feePayer":{"body":{"publicKey":"B62qiTKpEPjGTSHZrtM8uXiKgn8So916pLmNJKDhKeyBQL9TDb3nvBG","fee":"0","validUntil":null,"nonce":"0"},"authorization":"7mWxjLYgbJUkZNcGouvhVj5tJ8yu9hoexb9ntvPK8t5LHqzmrL6QJjjKtf5SgmxB4QWkDw7qoMMbbNGtHVpsbJHPyTy2EzRQ"},"accountUpdates":[{"body":{"publicKey":"B62qnwTPcbNqvrpw3pxdsD3NLnbadNJFk5MZnxQLUaX52EiGX7x9TM8","tokenId":"wSHV2S4qX9jFsLjQo8r1BsMLH2ZRKsZx6EJd1sbozGPieEC4Jf","update":{"appState":["33",null,null,null,null,null,null,null],"delegate":null,"verificationKey":null,"permissions":null,"zkappUri":null,"tokenSymbol":null,"timing":null,"votingFor":null},"balanceChange":{"magnitude":"0","sgn":"Positive"},"incrementNonce":false,"events":[],"actions":[],"callData":"9480311477670922688987895225723267062012786366393322319448750791657739847081","callDepth":0,"preconditions":{"network":{"snarkedLedgerHash":null,"blockchainLength":null,"minWindowDensity":null,"totalCurrency":null,"globalSlotSinceGenesis":null,"stakingEpochData":{"ledger":{"hash":null,"totalCurrency":null},"seed":null,"startCheckpoint":null,"lockCheckpoint":null,"epochLength":null},"nextEpochData":{"ledger":{"hash":null,"totalCurrency":null},"seed":null,"startCheckpoint":null,"lockCheckpoint":null,"epochLength":null}},"account":{"balance":null,"nonce":null,"receiptChainHash":null,"delegate":null,"state":["31",null,null,null,null,null,null,null],"actionState":null,"provedState":null,"isNew":null},"validWhile":null},"useFullCommitment":false,"implicitAccountCreationFee":false,"mayUseToken":{"parentsOwnToken":false,"inheritFromParent":false},"authorizationKind":{"isSigned":false,"isProved":true,"verificationKeyHash":"10245640308479032248697049003357984740828440340040477697922362566190589502399"}},"authorization":{"proof":null,"signature":null}}],"memo":"E4YM2vTHhWEg66xpj52JErHUBU4pZ1yageL4TVDDpTTSsv8mK6YaH"}"
const fee = ""
const memo = ""
const onlySign = true;

await window.mina?.sendTransaction({
        onlySign: onlySign,
        transaction: transactionJSON,
        feePayer: {
            fee: fee,
            memo: memo,
        },
    });
```

### Result

```typescript
// successful result.
{
  "hash": "5JuVoDUC2kb3m1dQxG1B9Ar9VhZh4HuABGLgCoYnEJqZVhthk4TV"
}

// can not get connect address.
{
  "code": 1001,
  "message": "User disconnect, please connect first."
}

// user reject.
{
  "code": 1002,
  "message": "User rejected the request."
}

// params check error. there check addres, fee.
{
  "code": 20003,
  "message": "Invalid method parameter(s)."
}

// only sign with auro wallet
{
  "signedData":'{"zkappCommand":{"feePayer":{"body":{"publicKey":"B62qr2zNMypNKXmzMYSVotChTBRfXzHRtshvbuEjAQZLq6aEa8RxLyD","fee":"10100000","validUntil":null,"nonce":"98"},"authorization":"7mXMsb2cc2RR8qnrubXZ3Wjsx13WhRbuetD9yGbGD7Do58vaph8VanDTb5jZmbX8oUA5koPdAiixvqZ2a2bDyRcjQDDwdiHA"},"accountUpdates":[{"body":{"publicKey":"B62qpSvbc66k2ecSmdryPAUFCPQStHo4Vc8rxYU8K4LSGRSMVwxw6nk","tokenId":"wSHV2S4qX9jFsLjQo8r1BsMLH2ZRKsZx6EJd1sbozGPieEC4Jf","update":{"appState":["63",null,null,null,null,null,null,null],"delegate":null,"verificationKey":null,"permissions":null,"zkappUri":null,"tokenSymbol":null,"timing":null,"votingFor":null},"balanceChange":{"magnitude":"0","sgn":"Positive"},"incrementNonce":false,"events":[],"actions":[],"callData":"21961609069728653483958795532181351452085718952361457203914335723687686999994","callDepth":0,"preconditions":{"network":{"snarkedLedgerHash":null,"blockchainLength":null,"minWindowDensity":null,"totalCurrency":null,"globalSlotSinceGenesis":null,"stakingEpochData":{"ledger":{"hash":null,"totalCurrency":null},"seed":null,"startCheckpoint":null,"lockCheckpoint":null,"epochLength":null},"nextEpochData":{"ledger":{"hash":null,"totalCurrency":null},"seed":null,"startCheckpoint":null,"lockCheckpoint":null,"epochLength":null}},"account":{"balance":null,"nonce":null,"receiptChainHash":null,"delegate":null,"state":[null,null,null,null,null,null,null,null],"actionState":null,"provedState":null,"isNew":null},"validWhile":null},"useFullCommitment":false,"implicitAccountCreationFee":false,"mayUseToken":{"parentsOwnToken":false,"inheritFromParent":false},"authorizationKind":{"isSigned":false,"isProved":true,"verificationKeyHash":"2463176747116618058094797786079315209173315865869177351205687923345657415010"}},"authorization":{"proof":null,"signature":null}}],"memo":"E4YM2vTHhWEg66xpj52JErHUBU4pZ1yageL4TVDDpTTSsv8mK6YaH"},"feePayer":{"feePayer":"B62qr2zNMypNKXmzMYSVotChTBRfXzHRtshvbuEjAQZLq6aEa8RxLyD","fee":"10100000","nonce":"98","memo":"","validUntil":null}}'
}
```


# mina\_addChain

This method is used to add a custom chain to Auro Wallet.

{% hint style="success" %}
if you want to switch by URL , you can use this method . if URL is added to wallet , will call switch\_chain auto.
{% endhint %}

### Params

```typescript
type AddChainArgs = {
    // the GraphQL URL that need add.
    readonly url: string
    // custom name.
    readonly name: string
}
```

### Result

```typescript
type ChainInfoArgs ={
    // current networkID, now will return mina:mainnet, mina:testnet, mina:berkeley
    networkID:string,
}

interface ProviderError extends Error {
    message: string; // error message.
    code: number; // error code.
    data?: unknown; // error body. 
}

Promise<ChainInfoArgs | ProviderError>
```

{% hint style="danger" %}

```markdown
** Please update as soon as possible. **
`ChainInfoArgs` params have updated from App 2.0.2 & extension 2.2.17.
Only `networkID` is returned, no longer supports returning `chainId` and `name`. 

// @deprecated from App 2.0.2 & extension 2.2.17.
type ChainInfoArgs ={ 
    chainId:string,
    name:string
}
```

{% endhint %}

### Errors

|       |                                            |                                                    |
| ----- | ------------------------------------------ | -------------------------------------------------- |
| 1001  | User disconnect, need connect Auro Wallet. | Can not get connected account.                     |
| 1002  | The request was rejected by the user.      |                                                    |
| 20003 | The parameters were invalid.               | Please check GraphQL URL and name.                 |
| 20004 | Not support chain.                         | Please use support chain.                          |
| 20005 | Request already pending. Please wait.      | Chain action current support one at the same time. |
| 23001 | Origin dismatch                            | Check origin safe.                                 |

## Example

### Request

```typescript
const addInfo = {
    url: encodeURIComponent("GraphQL URL"),
    name: "networkName",
}

await window.mina?.addChain(addInfo).catch((err: any) => err);
```

### Result

```typescript
// successful result.
{
  "networkID": "mina:mainnet"
}

// user reject.
{
  "code": 1002,
  "message": "User rejected the request. "
}

// params check error. there check GraphQL URL.
{
  "code": 20003,
  "message": "Invalid method parameter(s). "
}

// have pending chain action.
{
  "code": 20005,
  "message": "Request already pending. Please wait. "
}
```


# mina\_switchChain

This method is used to switch chain of Auro Wallet by chainId.

### Params

```typescript
type SwitchChainArgs = {
    // Target networkID. now will return mina:mainnet, mina:devnet, zeko:testnet
    readonly networkID: string
}
```

### Result

```typescript
type ChainInfoArgs ={
    // current networkID, now will return mina:mainnet, mina:testnet, mina:berkeley
    networkID:string
}

interface ProviderError extends Error {
    message: string; // error message.
    code: number; // error code.
    data?: unknown; // error body. 
}

Promise<ChainInfoArgs | ProviderError>
```

{% hint style="danger" %}

```markdown
** Please update as soon as possible. **
`ChainInfoArgs` params have updated from App 2.0.2 & extension 2.2.17.
Only `networkID` is returned, no longer supports returning `chainId` and `name`. 

// @deprecated from App 2.0.2 & extension 2.2.17.
type ChainInfoArgs ={ 
    chainId:string,
    name:string
}
```

{% endhint %}

### Errors

|       |                                       |                                                    |
| ----- | ------------------------------------- | -------------------------------------------------- |
| 1002  | The request was rejected by the user. |                                                    |
| 20005 | Request already pending. Please wait. | Chain action current support one at the same time. |
| 23001 | Origin dismatch.                      | Check origin safe.                                 |

## Example

### Request

```typescript
await window.mina?.switchChain({ networkID: "mina:mainnet" }).catch((err: any) => err);
```

### Result

```typescript
// successful result.
{
  "networkID": "mina:mainnet"
}

// user reject.
{
  "code": 1002,
  "message": "User rejected the request."
}

// have pending chain action.
{
  "code": 20005,
  "message": "Request already pending. Please wait."
}
```


# mina\_createNullifier

Mainly used to create nullifiers.

### Params

```typescript
type CreateNullifierArgs = {
    readonly message: (string | number)[]
}
```

### Result

```typescript
type Group = {
    x: bigint;
    y: bigint;
};

export type Nullifier = {
    publicKey: Group;
    public: {
        nullifier: Group;
        s: bigint;
    };
    private: {
        c: bigint;
        g_r: Group;
        h_m_pk_r: Group;
    };
};

interface ProviderError extends Error {
    message: string; // error message.
    code: number; // error code.
    data?: unknown; // error body.
}

Promise<Nullifier | ProviderError>
```

### Errors

|       |                                            |                                |
| ----- | ------------------------------------------ | ------------------------------ |
| 1001  | User disconnect, need connect Auro Wallet. | Can not get connected account. |
| 1002  | The request was rejected by the user.      |                                |
| 23001 | Origin dismatch.                           | Check origin safe.             |

## Example

### Request

```typescript
const signContent = [1,2,3]
await window.mina?.createNullifier({ message: signContent }).catch((err: any) => err);
```

### Result

```typescript
// successful result.
{
  "publicKey": {
    "x": "5248528914034818597164419364515906783046550751002313167808067803822526836450",
    "y": "8499673205188463960219287503467053771967554971086609841768360242543765381807"
  },
  "private": {
    "c": "9902185640563099798552538703361718566830920909287274415375718449173766417439",
    "g_r": {
      "x": "23709477331717770451048134593130727683043593683401466930366147533380855637145",
      "y": "18760208553553506432939082676972461624515683232329707805004444151147449487796"
    },
    "h_m_pk_r": {
      "x": "15858225469987785242406457588027706230191637416882043355002940613645441083323",
      "y": "25708145549986256124255195010233858317380687279717405739951366139000324110011"
    }
  },
  "public": {
    "nullifier": {
      "x": "3361150403274954664604230770379378491388033780248903656881561776735665100150",
      "y": "13198964082679393929618472402851291476272996295959277116839569765356779886575"
    },
    "s": "15386289247285176606445846857509398164434569113204850486864311070500369459309"
  },
  "data": [
    1,
    2,
    3
  ]
}

// can not get connect address.
{
  "code": 1001,
  "message": "User disconnect, please connect first."
}

// user reject.
{
  "code": 1002,
  "message": "User rejected the request."
}
```


# mina\_signMessage

This method is used to sign message.

### Params

```typescript
type SignMessageArgs = {
    // The message that need to sign.
    readonly message: string
}
```

### Result

```typescript
interface SignedData {
    // sign account address.
    publicKey: string;
    // sign message.
    data: string;
    // sign result.
    signature: {
        field: string;
        scalar: string;
    }
}

interface ProviderError extends Error {
    message: string; // error message.
    code: number; // error code.
    data?: unknown; // error body. 
}


Promise<SignedData | ProviderError> 
```

### Errors

|       |                                            |                                |
| ----- | ------------------------------------------ | ------------------------------ |
| 1001  | User disconnect, need connect Auro Wallet. | Can not get connected account. |
| 1002  | The request was rejected by the user.      |                                |
| 23001 | Origin dismatch.                           | Check origin safe.             |

## Example

### Request

```typescript
const content = `Click "Sign" to sign in. No password needed!

This request will not trigger a blockchain transaction or cost any gas fees.

I accept the Auro Test zkApp Terms of Service: ${window.location.href}

address: ${currentAccount}
iat: ${new Date().getTime()}`;

await window.mina?.signMessage({ message: content }).catch((err: any) => err);
```

### Result

```typescript
// successful result.
{
  "signature": {
    "field": "13468724101429370746602596170094552502200193721398063751467629418902449650534",
    "scalar": "5638584219029837254561020594864591092072844530049610703222272818700774330907"
  },
  "publicKey": "B62qr2zNMypNKXmzMYSVotChTBRfXzHRtshvbuEjAQZLq6aEa8RxLyD",
  "data": "Click \"Sign\" to sign in. No password needed!\n\nThis request will not trigger a blockchain transaction or cost any gas fees.\n\nI accept the Auro Test zkApp Terms of Service: http://localhost:3000/\n\naddress: \niat: 1699294808439"
}

// can not get connect address.
{
  "code": 1001,
  "message": "User disconnect, please connect first."
}

// user reject.
{
  "code": 1002,
  "message": "User rejected the request."
}
```


# mina\_sign\_JsonMessage

This method is used to sign Json message.

### Params

```typescript
type JsonMessageData  = {
    // show title.
    label:string
    // show value.
    value:string
}

export type SignJsonMessageArgs = {
    readonly message: Array<JsonMessageData>
}
```

### Result

```typescript
interface SignedData {
    // sign account address.
    publicKey: string;
    // sign message.
    data: string;
    // sign result.
    signature: {
        field: string;
        scalar: string;
    }
}

interface ProviderError extends Error {
    message: string; // error message.
    code: number; // error code.
    data?: unknown; // error body.
}


Promise<SignedData | ProviderError> 
```

### Errors

|       |                                            |                                |
| ----- | ------------------------------------------ | ------------------------------ |
| 1001  | User disconnect, need connect Auro Wallet. | Can not get connected account. |
| 1002  | The request was rejected by the user.      |                                |
| 23001 | Origin dismatch.                           | Check origin safe.             |

## Example

### Request

```typescript
const msgParams = [
    { label: "Label:", value: "Sign Confirm" },
    {
      label: "Message:",
      value: "Click to sign in and accept the Terms of Service",
    },
    {
      label: "URI:",
      value: "window.location.href",
    },
    {
      label: "networkID:",
      value: network.networkID,
    },
    {
      label: "Issued At:",
      value: new Date().getTime(),
    },
    {
      label: "Resources:",
      value: "https://docs.aurowallet.com/",
    },
];

await window.mina?.signJsonMessage({ message: msgParams }).catch((err: any) => err);
```

### Result

```typescript
// successful result.
{
  "signature": {
    "field": "53162080350849153826967095054833981754739013396707431795337381755943299841",
    "scalar": "15611159828454615720437923596295410541639103513124421213633470429174796003052"
  },
  "publicKey": "B62qr2zNMypNKXmzMYSVotChTBRfXzHRtshvbuEjAQZLq6aEa8RxLyD",
  "data": "[{"label":"Label:","value":"Sign Confirm"},{"label":"Message:","value":"Click to sign in and accept the Terms of Service"},{"label":"URI:","value":"window.location.href"},{"label":"networkID:","value":"mina:testnet"},{"label":"Issued At:","value":1718168623709},{"label":"Resources:","value":"https://docs.aurowallet.com/"}]"
}

// can not get connect address.
{
  "code": 1001,
  "message": "User disconnect, please connect first."
}

// user reject.
{
  "code": 1002,
  "message": "User rejected the request."
}
```


# mina\_verifyMessage

This method is used to verify the validity of the signature info.

### Params

```typescript
interface VerifyMessageArgs{
    // sign account address.
    publicKey: string;
    // sign message.
    data: string;
    // sign result.
    signature: {
        field: string;
        scalar: string;
    }
}
```

### Result

```typescript
interface ProviderError extends Error {
    message: string; // error message.
    code: number; // error code.
    data?: unknown; // error body. 
}

Promise<boolean | ProviderError>
```

### Errors

|       |                                |                                                                                            |
| ----- | ------------------------------ | ------------------------------------------------------------------------------------------ |
| 20002 | Signature verification failed. | This error is returned because an exception was thrown, please check the signature format. |
| 23001 | Origin dismatch.               | Check origin safe.                                                                         |

## Example

### Request

```typescript
let verifyMessageBody = {
  "signature": {
    "field": "13468724101429370746602596170094552502200193721398063751467629418902449650534",
    "scalar": "5638584219029837254561020594864591092072844530049610703222272818700774330907"
  },
  "publicKey": "B62qr2zNMypNKXmzMYSVotChTBRfXzHRtshvbuEjAQZLq6aEa8RxLyD",
  "data": "Click \"Sign\" to sign in. No password needed!\n\nThis request will not trigger a blockchain transaction or cost any gas fees.\n\nI accept the Auro Test zkApp Terms of Service: http://localhost:3000/\n\naddress: \niat: 1699294808439"
};

await window.mina?.verifyMessage(verifyMessageBody).catch((err: any) => err);
```

### Result

```typescript
// successful result.
false | true

// verify failed.
{
  "message": "Verify failed",
  "code": 20002
}
```


# mina\_signFields

This method is used to sign the field.

{% hint style="info" %}
The output of numbers and string type numbers is the same in sign fields.
{% endhint %}

### Params

```typescript
type SignFieldsArguments = {
    readonly message: (string|number)[],
}
```

### Result

```typescript
type SignedFieldsData  = {
    // sign data.
    data: (string|number)[],
    // signature.
    signature:string
}

interface ProviderError extends Error {
    message: string; // error message.
    code: number; // error code.
    data?: unknown; // error body.
}

Promise<SignedFieldsData | ProviderError>
```

### Error

|       |                                            |                                |
| ----- | ------------------------------------------ | ------------------------------ |
| 1001  | User disconnect, need connect Auro Wallet. | Can not get connected account. |
| 1002  | The request was rejected by the user.      |                                |
| 23001 | Origin dismatch.                           | Check origin safe.             |

## Example

### Request

```typescript
await window.mina?.signFields({ message: [1,2,3] }).catch((err: any) => err);
```

### Result

```typescript
// successful result
{
  "signature": "7mX4QDZBoq3eTfLhvoWzBBQnUhxBfVCUcXwnPsDoEqcpiGacuoeYq3i9HpMfFUvvTz5qG4C2zqCDDBoB5KPamAko15m4wMiS",
  "publicKey": "B62qr2zNMypNKXmzMYSVotChTBRfXzHRtshvbuEjAQZLq6aEa8RxLyD",
  "data": [
    1,
    2,
    3
  ]
}

// can not get connect address.
{
  "code": 1001,
  "message": "User disconnect, please connect first."
}

// user reject.
{
  "code": 1002,
  "message": "User rejected the request."
}
```


# mina\_verifyFields

This method is used to verify the signature results of fields.

### Params

```typescript
interface VerifyFieldsArguments {
    // sign publicKey.
    publicKey: string,
    // sign fields.
    data: (string|number)[],
    signature:string
}
```

### Result

```typescript
interface ProviderError extends Error {
    message: string; // error message.
    code: number; // error code.
    data?: unknown; // error body.
}

Promise<boolean | ProviderError> 
```

### Error

|       |                                |                                                                                            |
| ----- | ------------------------------ | ------------------------------------------------------------------------------------------ |
| 20002 | Signature verification failed. | This error is returned because an exception was thrown, please check the signature format. |
| 23001 | Origin dismatch.               | Check origin safe.                                                                         |

## Example

### Request

```typescript
const verifyMessageBody = {
      publicKey: "B62qr2zNMypNKXmzMYSVotChTBRfXzHRtshvbuEjAQZLq6aEa8RxLyD",
      signature: "7mX4QDZBoq3eTfLhvoWzBBQnUhxBfVCUcXwnPsDoEqcpiGacuoeYq3i9HpMfFUvvTz5qG4C2zqCDDBoB5KPamAko15m4wMiS",
      data:  [1,2,3]
    };

await window.mina?.verifyFields(verifyMessageBody).catch((err: any) => err);
```

### Result

```typescript
// successful result.
false | true

// verify failed.
{
  "message": "Verify failed",
  "code": 20002
}
```


# mina\_storePrivateCredential

This method is used to store private credentials.

{% hint style="info" %}
Support from Auro-Wallet-extension v2.3.2.
{% endhint %}

## Params

```typescript
type JSONValue =
    | string
    | number
    | boolean
    | null
    | JSONValue[]
    | { [key: string]: JSONValue };


type Credential<Data = unknown> = { owner: string; data: Data };
type StoredCredential<Data = unknown, Witness = unknown> = {
    version: 'v0';
    witness: Witness;
    metadata: JSONValue | undefined;
    credential: Credential<Data>;
};

type StoredCredentialArgs = {
    credential:StoredCredential
}
```

## Result

```typescript
type IStoreCredentialData = {
    credential: string;
};
```

## Errors

|       |                                            |                                |
| ----- | ------------------------------------------ | ------------------------------ |
| 1001  | User disconnect, need connect Auro Wallet. | Can not get connected account. |
| 1002  | The request was rejected by the user.      |                                |
| 20003 | The parameters were invalid.               | Please check address, fee.     |
| 23001 | Origin dismatch.                           | Check origin safe.             |

## Example

### Request

```typescript
const credential = {"version":"v0","witness":{"type":"native","issuer":{"_type":"PublicKey","value":"B62qp6y93m7HztH5jvn12gHJphzAZrZq3daD792hi8a6WSivDS62M6y"},"issuerSignature":{"_type":"Signature","value":{"r":"20488774605787391652280562339538477966865965211091577050649120180217379031673","s":"16708818945490883015829890483065574022023217519234257567358763357703611506560"}}},"credential":{"owner":{"_type":"PublicKey","value":"B62qpjxUpgdjzwQfd8q2gzxi99wN7SCgmofpvw27MBkfNHfHoY2VH32"},"data":{"nationality":"KR","name":"zvCICx","birthDate":{"_type":"Int64","value":{"magnitude":"215913411073","sgn":"Negative"}},"id":{"_type":"Bytes","size":16,"value":"2a4dc0212e4c68fff1ae6ffbb2c194fb"},"expiresAt":{"_type":"UInt64","value":"1777182333186"}}}}

await window.mina.storePrivateCredential({
    credential: credential,
})
.catch((err: any) => err);

```

### Result

```typescript
// successful result.
{
    credential:"{\"version\":\"v0\",\"witness\":{\"type\":..."
}
```


# mina\_requestPresentation

This method is used to verify presentation.

{% hint style="info" %}
Support from Auro-Wallet-extension v2.3.2.
{% endhint %}

## Params

```typescript
type PresentationRequestType = 'no-context' | 'zk-app' | 'https';
type PresentationRequest<
    RequestType extends PresentationRequestType = PresentationRequestType,
    InputContext = any,
> = {
    type: RequestType;
    spec: any;
    claims: any;
    inputContext: InputContext;
    program?: unknown;
    verificationKey?: unknown;
};

type IPresentationRequest = {
    presentationRequest:PresentationRequest
    zkAppAccount?:any // used for type zk-app
}

type PresentationArgs = {
    presentation:IPresentationRequest
}
```

## Result

```typescript
type IRequestPresentation = {
    presentation: string;
};
```

## Errors

|       |                                            |                                |
| ----- | ------------------------------------------ | ------------------------------ |
| 1001  | User disconnect, need connect Auro Wallet. | Can not get connected account. |
| 1002  | The request was rejected by the user.      |                                |
| 20003 | The parameters were invalid.               | Please check address, fee.     |
| 23001 | Origin dismatch.                           | Check origin safe.             |

## Example

### Request

```typescript
const presentationRequest = {"type":"https","spec":{"inputs":{"credential":{"type":"credential","credentialType":"native","witness":null,"data":{"_type":"DynamicRecord","maxEntries":20,"knownShape":{"expiresAt":{"_type":"UInt64"}},"_isFactory":true}},"expectedIssuer":{"type":"claim","data":{"_type":"Field"}},"createdAt":{"type":"claim","data":{"_type":"UInt64"}}},"assert":{"type":"and","inputs":[{"type":"equals","left":{"type":"issuer","credentialKey":"credential"},"right":{"type":"property","key":"expectedIssuer","inner":{"type":"root"}}},{"type":"lessThanEq","left":{"type":"property","key":"createdAt","inner":{"type":"root"}},"right":{"type":"property","key":"expiresAt","inner":{"type":"credential","credentialKey":"credential","credentialType":"native"}}}]},"outputClaim":{"type":"constant","data":{"_type":"Undefined","value":null}}},"claims":{"expectedIssuer":{"_type":"Field","value":"16167289078389923610953595615737668731080372316578280370618447557903825457595"},"createdAt":{"_type":"UInt64","value":"1745647048630"}},"inputContext":{"type":"https","serverNonce":{"_type":"Field","value":"817980905302159961768471044132257779624448992114290456026544408364528955972"},"action":"credentials-web-demo-server:anonymous-login"}}

await window.mina.requestPresentation({
    presentation: {
      presentationRequest: presentationRequest,
    },
})
.catch((err: any) => err);
```

### Result

```typescript
// successful result.
{
    presentation:"{\"version\":\"v0\",\"claims\"...}"
}
```


# Events

Here are the monitoring events of the provider. There are currently two types of events, account update and chain update.

### **accountsChanged**

When user switch account in Auro Wallet, `accountsChanged` will be trigger.

```javascript
window.mina?.on('accountsChanged', handler: (accounts: string[]) => void);
```

```javascript
window.mina?.on('accountsChanged', handler: (accounts: string[]) => {
   console.log('connected accounts', accounts)
});
```

{% hint style="success" %}
**NOTE**\
When switching to an unconnected account, an empty array will be returned.
{% endhint %}

### **chainChanged**

When user switch chain in Auro Wallet, `chainChanged` will be trigger.&#x20;

```javascript
type ChainInfoArgs ={
  networkID:string
}

window.mina?.on('chainChanged', handler: (chainInfo: ChainInfoArgs) => void);
```

```javascript
window.mina?.on('chainChanged', handler: (chainInfo: ChainInfoArgs) => {
   console.log('current networkID', chainInfo.networkID)
});
```

{% hint style="danger" %}

```markdown
** Please update as soon as possible. **
`ChainInfoArgs` params have updated from App 2.0.2 & extension 2.2.17.
Only `networkID` is returned, no longer supports returning `chainId` and `name`. 

// @deprecated from App 2.0.2 & extension 2.2.17.
type ChainInfoArgs ={ 
    chainId:string,
    name:string
}
```

{% endhint %}


# Error

Here is the error message returned by Auro Wallet.

Now we use error message and error code show the error, zkApp can show the error to user.

```typescript
/** error info type */
interface ProviderError extends Error {
    message: string;
    code: number;
    data?: unknown;
}
```

## Error code information

if return failed info , zkApp can get error code.

```typescript
* code 1001  User disconnect, need connect first.
* code 1002  The request was rejected by the user.
* code 20001 Can not find account, may need create or restore in Auro Wallet first.
* code 20002 Verify failed.
* code 20003 The parameters were invalid.
* code 20004 Not support chain.
* code 20005 Have Pending chain action.
* code 20006 Method not supported.
* code 21001 Internal error.
* code 22001 Unspecified error message.
* code 23001 Origin dismatch.
```


# Source

* [Online zkApp Demo](https://test-zkapp.aurowallet.com/)
* [Demo Source Code](https://github.com/aurowallet/test-zkapp)
* [Mina-Provider](https://github.com/aurowallet/mina-provider)


