diff --git a/wallet/assets/contract-abi-converter-dialog.png b/wallet/assets/contract-abi-converter-dialog.png new file mode 100644 index 00000000000..521b9001072 Binary files /dev/null and b/wallet/assets/contract-abi-converter-dialog.png differ diff --git a/wallet/assets/unity-empty-template.png b/wallet/assets/unity-empty-template.png new file mode 100644 index 00000000000..6ed04976126 Binary files /dev/null and b/wallet/assets/unity-empty-template.png differ diff --git a/wallet/assets/unity-example-template.png b/wallet/assets/unity-example-template.png new file mode 100644 index 00000000000..ef3da48013a Binary files /dev/null and b/wallet/assets/unity-example-template.png differ diff --git a/wallet/how-to/add-network.md b/wallet/how-to/add-network.md index 312c4742ac6..582a27aa0eb 100644 --- a/wallet/how-to/add-network.md +++ b/wallet/how-to/add-network.md @@ -5,7 +5,7 @@ sidebar_position: 6 # Add a network -In some cases, such as when [interacting with smart contracts](interact-with-smart-contracts.md), +In some cases, such as when [interacting with smart contracts](interact-with-smart-contracts/index.md), your dapp must connect a user to a new network in MetaMask. Instead of the user [adding a new network manually](https://support.metamask.io/hc/en-us/articles/360043227612-How-to-add-a-custom-network-RPC#h_01G63GGJ83DGDRCS2ZWXM37CV5), which requires them to configure RPC URLs and chain IDs, your dapp can use the diff --git a/wallet/how-to/connect/set-up-sdk/gaming/unity.md b/wallet/how-to/connect/set-up-sdk/gaming/unity.md index 17cb5e3c774..44f1ecdd3b3 100644 --- a/wallet/how-to/connect/set-up-sdk/gaming/unity.md +++ b/wallet/how-to/connect/set-up-sdk/gaming/unity.md @@ -53,6 +53,26 @@ with it and its examples in the scene. You also need to install [TextMeshPro](https://docs.unity3d.com/Manual/com.unity.textmeshpro.html). If you don't have TextMeshPro installed, the Unity editor automatically prompts you to install it. +
+ +Unity SDK package structure +

+ +| File or directory | Contents | +| ------------------------ | ---------------------------------------------- | +| `Documentation` | Documentation and link to online documentation | +| `Editor` | Editor-only code such as Setup GUI windows, data persistence for SDK settings | +| `Plugins` | Plugins needed by the package (the ECIES Platform runtime libraries and core SDK Codebase) | +| `Runtime` | Main scripts for the SDK that are environment-agnostic, including the C# scripts that provide the base implementation of the SDK | +| `Samples` | Test application scene that can be used as a referral for your project, including modal popups and dynamic UI scaling | +| `LICENSE.md` | Package license | +| `Third Party Notices.md` | Third party notices | + + +

+ +
+ ### 3. Initialize MetaMask The main class you interface with is called `MetaMaskWallet`. @@ -128,7 +148,7 @@ void OnWalletAuthorized(object sender, EventArgs e) { } ``` -You can call any Ethereum request on the wallet using `wallet.Request(myRequest)`. +You can call any [JSON-RPC API method](/wallet/reference/eth_subscribe) using `wallet.Request(myRequest)`. The following is a sample transaction request: ```csharp @@ -148,6 +168,11 @@ var request = new MetaMaskEthereumRequest await wallet.Request(request); ``` +:::note +See the [Unity SDK API reference](../../../../reference/sdk-unity-api.md) for an overview of the +API methods from the most important classes. +::: + ### 6. Configure MetaMask You can customize the default configuration or create your own configuration. @@ -163,83 +188,6 @@ Create a new configuration by right-clicking on the project window and navigatin **MetaMask > Config**. Name the new configuration and use it when initializing the `MetaMaskUnity` instance. -## API - -The following is an overview of the APIs from the most important classes. - -### MetaMaskUnity - -This is a singleton class that you can use to access the `MetaMaskWallet` instance, which is -specific to Unity. - -#### `Instance` - -This is the singleton instance of the `MetaMaskUnity` class that is lazy-loaded when you access it -for the first time. - -#### `Initialize` - -This method initializes the `MetaMaskWallet` instance and makes it accessible via the `Wallet` property. -You can also pass extra options and parameters to it to customize the wallet instance: - -```csharp -// Initialize using default settings -MetaMaskUnity.Instance.Initialize(); - -// Initialize using custom transport and socket provider -var transport = new MyCustomTransport(); -var socketProvider = new MyCustomSocketProvider(); -MetaMaskUnity.Instance.Initialize(transport, socketProvider); - -// Initialize using custom config, transport and socket provider -var config = myMetaMaskConfig; -var transport = new MyCustomTransport(); -var socketProvider = new MyCustomSocketProvider(); -MetaMaskUnity.Instance.Initialize(config, transport, socketProvider); -``` - -#### `SaveSession` - -This method saves the current session to the persistent storage. -This is useful when you want to save the session and restore it later. -This is automatically called when the application quits, but you can also manually call it. - -#### `LoadSession` - -This method loads the session from the persistent storage. -This is useful when you want to restore the session after the application quits. -This is automatically called when the application starts, but you can also manually call it. - -### MetaMaskWallet - -#### `Connect` - -This method connects to the MetaMask app. -It renders a generated QR code in the user interface for your users to scan with MetaMask Mobile. -After the user scans this QR code, a connect screen appears in MetaMask Mobile where the user can -approve the connection with your game application. - -#### `Disconnect` - -This method disconnects the user that is connected from the MetaMask app session. - -#### `Request` - -This method sends a request to MetaMask. -You can use it to call any [provider API method](../../../../reference/provider-api.md). - -## Package structure - -| File or directory | Contents | -| ------------------------ | ---------------------------------------------- | -| `Documentation` | Documentation and link to online documentation | -| `Editor` | Editor-only code such as Setup GUI windows, data persistence for SDK settings | -| `Plugins` | Plugins needed by the package (the ECIES Platform runtime libraries and core SDK Codebase) | -| `Runtime` | Main scripts for the SDK that are environment-agnostic, including the C# scripts that provide the base implementation of the SDK | -| `Samples` | Test application scene that can be used as a referral for your project, including modal popups and dynamic UI scaling | -| `LICENSE.md` | Package license | -| `Third Party Notices.md` | Third party notices | - ## FAQS
@@ -287,3 +235,8 @@ take longer to build at compile time. The SDK is filled with precompiled libraries to save on runtime compilation.
+ +## Next steps + +Once you have the MetaMask Unity SDK set up, you can +[interact with smart contracts](../../../interact-with-smart-contracts/unity/index.md) from your Unity game. diff --git a/wallet/how-to/interact-with-smart-contracts.md b/wallet/how-to/interact-with-smart-contracts/index.md similarity index 94% rename from wallet/how-to/interact-with-smart-contracts.md rename to wallet/how-to/interact-with-smart-contracts/index.md index 53cdba5f06b..e096ed54c0f 100644 --- a/wallet/how-to/interact-with-smart-contracts.md +++ b/wallet/how-to/interact-with-smart-contracts/index.md @@ -5,6 +5,10 @@ sidebar_position: 5 # Interact with smart contracts +This is a high-level overview of how to interact with smart contracts. +You can also see how to +[interact with smart contracts from your Unity game](unity/index.md). + To interact with a smart contract, your dapp needs the following information: - [Contract network](#contract-network) diff --git a/wallet/how-to/interact-with-smart-contracts/unity/contract-factory.md b/wallet/how-to/interact-with-smart-contracts/unity/contract-factory.md new file mode 100644 index 00000000000..e95ad193596 --- /dev/null +++ b/wallet/how-to/interact-with-smart-contracts/unity/contract-factory.md @@ -0,0 +1,91 @@ +--- +sidebar_position: 2 +--- + +# Contract factory + +When [interacting with smart contracts in Unity](index.md), the contract factory is responsible for +creating the [contract proxy class](contract-proxy-class.md) with the given +[contract interface](contract-interface.md) type `T`. + +## Contract factory types + +### Impromptu contract factory + +The impromptu contract factory uses the `Impromptu` library to return a new instance of `Contract` +that behaves likes the given interface type `T`. +Since the contract is a dynamic object, all method invocations to the returned object of type `T` +are automatically routed to the `Contract` class. + +:::note +The impromptu contract factory is only supported on Mono or in a runtime that has the CLR. +The IL2CPP runtime does not support this factory. +Use the backed type contract factory if you need a more concrete type. +::: + +### Backed type contract factory + +The backed type contract factory uses a concrete `class` type that inherits the `Contract` class and +the given interface type `T`. +To use this factory, the given interface must declare the class attribute `BackedType` +that specifies which concrete `class` type must be used when creating a new `Contract` instance. +The declared `class` must inherit from the given interface type `T`. + +```csharp +[BackedType(typeof(ERC20Backing))] +public interface ERC20 : IContract +{ + [EvmMethodInfo(Name = "decimals", View = true)] + [return: EvmParameterInfo(Type = "uint8")] + Task Decimals(); + + // TODO Define other interface methods +} +``` + +Inside the backed `class`, you must override all interface methods and either invoke custom logic or +use the `Contract` class to automatically perform the correct logic based on the method data. +You can use `var method = System.Reflection.MethodBase.GetCurrentMethod();` to get the current +method being invoked, and then you can use `base.InvokeMethod(MethodInfo method, object[] args)` to +invoke the correct logic for the given `method` and `args`. + +```csharp +public class ERC20Backing : Contract, ERC20 +{ + public string Address + { + get => base.Address; + } + + [EvmMethodInfo(Name = "decimals", View = true)] + [return: EvmParameterInfo(Type = "uint8")] + public Task Decimals() + { + var method = System.Reflection.MethodBase.GetCurrentMethod(); + return (Task) InvokeMethod(method, new object[] { }); + } + + // TODO Define other interface methods +} +``` + +The [contract code generator](index.md#generate-contract-code) automatically generates a backing +`class` for each contract interface generated. + +This contract factory is useful for when you need more concrete definitions of the contract +interface type `T`. +This can be useful in runtimes where `dynamic` or `DynamicObject` are not available (IL2CPP). + +## Set the contract factory + +To set the current contract factory, you can use `Contract.ContractFactory`: + +```csharp +Contract.ContractFactory = new BackedTypeContractFactory(); +``` + +You don't need to do this, unless you create a custom contract factory. +We recommend just using the default contract factories for each runtime: + +- Mono runtime - [Impromptu contract factory](#impromptu-contract-factory) +- IL2CPP runtime - [Backed typed contract factory](#backed-type-contract-factory) diff --git a/wallet/how-to/interact-with-smart-contracts/unity/contract-interface.md b/wallet/how-to/interact-with-smart-contracts/unity/contract-interface.md new file mode 100644 index 00000000000..91240607c11 --- /dev/null +++ b/wallet/how-to/interact-with-smart-contracts/unity/contract-interface.md @@ -0,0 +1,150 @@ +--- +sidebar_position: 1 +--- + +# Contract interface + +When [interacting with smart contracts in Unity](index.md), the `IContract` interface defines an +interface of a given contract. +This interface includes all the functions of the contract, and an optional constructor function and +`Bytecode` field. + +You can use the [contract code generator](index.md#generate-contract-code) to generate a contract +interface given a contract ABI or Hardhat artifact JSON file. + +To manually create a new contract interface, define a new interface that inherits from `IContract`. +Optionally, declare the [`BackedType` attribute](contract-factory.md#backed-type-contract-factory). + +```csharp +#if UNITY_EDITOR || !ENABLE_MONO +[BackedType(typeof(ERC20Backing))] +#endif +public interface ERC20 : IContract +{ + // TODO Declare functions +} +``` + +## Declare contract functions + +To declare a `view` or `pure` function of the contract, first set the return type, the function name +(may differ from the actual name), and all parameters the function takes in a `Task`: + +```csharp +#if UNITY_EDITOR || !ENABLE_MONO +[BackedType(typeof(ERC20Backing))] +#endif +public interface ERC20 : IContract +{ + Task BalanceOf(EvmAddress account); +} +``` + +Once you have the function written, simply add the `EvmMethodInfo` at the top of the function to +declare the metadata about the contract function. +This includes the `Name` and whether it's a `View` function: + +```csharp +#if UNITY_EDITOR || !ENABLE_MONO +[BackedType(typeof(ERC20Backing))] +#endif +public interface ERC20 : IContract +{ + [EvmMethodInfo(Name = "balanceOf", View = true)] + Task BalanceOf(EvmAddress account); +} +``` + +To define the EVM type for a parameter, you can use the `EvmParameterInfo` attribute. +However, this usually isn't needed, because the `Contract` class automatically infers most common +types, such as `EvmAddress` to be `address` and `string` to be `string`. + +```csharp +#if UNITY_EDITOR || !ENABLE_MONO +[BackedType(typeof(ERC20Backing))] +#endif +public interface ERC20 : IContract +{ + [EvmMethodInfo(Name = "balanceOf", View = true)] + Task BalanceOf([EvmParameterInfo(Type = "address")] string account); +} +``` + +To define the EVM return type for the function, you can use `EvmParamterInfo` on the return type: + +```csharp +#if UNITY_EDITOR || !ENABLE_MONO +[BackedType(typeof(ERC20Backing))] +#endif +public interface ERC20 : IContract +{ + [EvmMethodInfo(Name = "balanceOf", View = true)] + Task BalanceOf(EvmAddress account); + + [EvmMethodInfo(Name = "decimals", View = true)] + [return: EvmParameterInfo(Type = "uint8")] + Task Decimals(); +} +``` + +### Use the Task return type + +We recommend always using `Task` as the return type when declaring contract functions, even if +the given [provider](contract-provider.md) does not use `Task`. +When you don't use `Task`, the `Contract` class is blocked until a response from the given +`Provider` is received. +This means if the `Provider` returns a `Task` of the request, the `Contract` class is blocked until +that `Task` completes, which may lead to a deadlock. + +### Define a contract constructor + +To define a constructor function, use the `EvmConstructorMethod` attribute at the top of the +function declaring the constructor. +The return type of the function must be the type of the interface, since a new instance of the +interface is returned by the `Contract` class. + +Also, do one of the following: + +- Declare a `static readonly string Bytecode` in the interface that has the bytecode. + + ```csharp + #if UNITY_EDITOR || !ENABLE_MONO + [BackedType(typeof(ERC20Backing))] + #endif + public interface ERC20 : IContract + { + public static readonly string Bytecode = "0x6080604052348015620000115760008...."; + + [EvmConstructorMethod] + Task DeployNew(String name_, String symbol_); + + [EvmMethodInfo(Name = "balanceOf", View = true)] + Task BalanceOf(EvmAddress account); + + [EvmMethodInfo(Name = "decimals", View = true)] + [return: EvmParameterInfo(Type = "uint8")] + Task Decimals(); + } + ``` + +- Set the `Bytecode` field in the `EvmConstructorMethod` attribute. + + ```csharp + #if UNITY_EDITOR || !ENABLE_MONO + [BackedType(typeof(ERC20Backing))] + #endif + public interface ERC20 : IContract + { + [EvmConstructorMethod(Bytecode = "0x608060405238....")] + Task DeployNew(String name_, String symbol_); + + [EvmMethodInfo(Name = "balanceOf", View = true)] + Task BalanceOf(EvmAddress account); + + [EvmMethodInfo(Name = "decimals", View = true)] + [return: EvmParameterInfo(Type = "uint8")] + Task Decimals(); + } + ``` + +By default, the [contract code generator](index.md#generate-contract-code) uses the second option. diff --git a/wallet/how-to/interact-with-smart-contracts/unity/contract-provider.md b/wallet/how-to/interact-with-smart-contracts/unity/contract-provider.md new file mode 100644 index 00000000000..aa0509073fa --- /dev/null +++ b/wallet/how-to/interact-with-smart-contracts/unity/contract-provider.md @@ -0,0 +1,78 @@ +--- +sidebar_position: 4 +--- + +# Contract provider + +When [interacting with smart contracts in Unity](index.md), the provider is similar to a JavaScript +provider. +The provider is responsible for sending the request formed inside the +[contract proxy class](contract-proxy-class.md) to the blockchain RPC node and optionally decoding +the response. +If the provider doesn't decode the response, then it's considered an [`ILegacyProvider`](#ilegacyprovider). + +## IProvider + +The `IProvider` interface defines the following function: + +```csharp +Task Request(string method, object[] parameters = null); +``` + +This function must send a JSON-RPC request with the given method and parameters. +It must decode the JSON-RPC result response into the type `TR`. + +The `IProvider` must also define two additional properties: + +```csharp +long ChainId { get; } // The current chain ID the provider is connected to + +string ConnectedAddress { get; } // The current address connected to the provider +``` + +For backwards compatibility, the `ILegacyProvider` function is also defined: + +```csharp +object Request(string method, object[] parameters = null); +``` + +To easily support this function, use `Request`: + +```csharp +public object Request(string method, object[] parameters = null) +{ + return this.Request(method, parameters); +} +``` + +## ILegacyProvider + +The `ILegacyProvider` is an interface that declares an interface that does not support response decoding. +The `ILegacyProvider` interface defines the following function: + +```csharp +object Request(string method, object[] parameters = null); +``` + +This function must send a JSON-RPC request with the given method and parameters. +It should decode the response, but it's not required. +It may return any of the following: + +- The response as a JSON string +- The response as a JSON string, wrapped in a `Task` +- The response decoded into some object +- The response decoded into some object, wrapped in a `Task` + +If the function returns a JSON string, then the `Contract` class attempts to deserialize the JSON +string into the desired type. +If it returns any other object type, the `Contract` class attempts to convert to the desired type by +first serializing the object into JSON, then deserializing the JSON back into the desired type. +The desired type is defined in the [contract interface](contract-interface.md) used. + +The `ILegacyProvider` must also define two additional properties: + +```csharp +long ChainId { get; } // The current chain ID the provider is connected to + +string ConnectedAddress { get; } // The current address connected to the provider +``` diff --git a/wallet/how-to/interact-with-smart-contracts/unity/contract-proxy-class.md b/wallet/how-to/interact-with-smart-contracts/unity/contract-proxy-class.md new file mode 100644 index 00000000000..7f9a52e1b15 --- /dev/null +++ b/wallet/how-to/interact-with-smart-contracts/unity/contract-proxy-class.md @@ -0,0 +1,30 @@ +--- +sidebar_position: 3 +--- + +# Contract proxy class + +When [interacting with smart contracts in Unity](index.md), the contract proxy class is responsible +for performing: + +- Transaction serialization +- Transaction execution +- Transaction result deserialization + +The contract proxy class is also responsible for invoking the [provider](contract-provider.md) and attempts +to support both asynchronous and synchronous provider objects. + +Since the proxy class is responsible for a lot, some parts of the class may be decoupled into their +own components. +For example, transaction serialization and deserialization is not very customizable and will likely +be moved into its own component to allow more extendability. + +:::caution important +The contract proxy class should be considered an internal and unstable API. +You should never need to inherit the `Contract` class, unless you're using the +[backed type contract factory](contract-factory.md#backed-type-contract-factory). +However, the [contract code generator](index.md#generate-contract-code) already generates these +classes for you. + +You only need to use `Contract.Attach(string address, IProvider provider)`. +::: diff --git a/wallet/how-to/interact-with-smart-contracts/unity/index.md b/wallet/how-to/interact-with-smart-contracts/unity/index.md new file mode 100644 index 00000000000..0ffee7bd81c --- /dev/null +++ b/wallet/how-to/interact-with-smart-contracts/unity/index.md @@ -0,0 +1,126 @@ +--- +sidebar_position: 1 +--- + +# Interact with smart contracts in Unity + +You can interact with smart contracts from your Unity game with MetaMask SDK installed. + +## Prerequisites + +- [MetaMask SDK set up](../../connect/set-up-sdk/gaming/unity.md) in your Unity game +- A [contract ABI](../index.md#contract-abi) JSON file or + [Hardhat artifact](https://hardhat.org/hardhat-runner/docs/advanced/artifacts#compilation-artifacts) + JSON file + +## Generate contract code + +You can use the MetaMask Unity contract code generator to generate +[contract interface](contract-interface.md) files. +The code generator automatically generates backed types for all contract interfaces to be used by +the [contract factory](contract-factory.md#backed-type-contract-factory). + +In your Unity editor, go to **Tools > MetaMask > Contract ABI Converter**. +A new dialog box opens: + +

+ +![dialog](../../../assets/contract-abi-converter-dialog.png) + +

+ +Paste your contract ABI JSON file or Hardhat artifact JSON file. +If you plan to deploy your contract, you must provide a Hardhat artifact, since this +has the required [contract bytecode](../index.md#contract-bytecode) needed for deployment. + +You can also specify the `Root Namespace` for the generated contract code. +The default value is `Contracts`, so make sure to add `using Contracts;` at the top of your scripts +before using the generated code. + +Select **Convert**, which opens a save dialog box. +Select a folder to save the generated code files to, somewhere inside the `Assets` folder. + +## Use the contract + +After generating the contract code, you can use the contract using the +`Contract.Attach(...)` function. + +This function takes a type `T` which must be the interface type of the contract to use. +This function returns that type `T`. + +You must provide the `address` string the contract should be loaded from, and the +[provider](contract-provider.md) to use to interact with the contract. +Usually, the provider is `MetaMaskUnity.Instance.Wallet`. + +The following is an example of using a contract: + +```csharp +public async void Start() +{ + var metaMask = MetaMaskUnity.Instance.Wallet; + var address = "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"; + + ERC20 usdc = Contract.Attach(address, metaMask); +} +``` + +Once you have an instance of your contract interface of type `T` (in this example, `ERC20`), you may +invoke any function inside the interface type. +For example: + +```csharp +public async void Start() +{ + // ... setup ... + + var balance = await usdc.BalanceOf(metaMask.SelectedAddress); + Debug.Log(balance); +} +``` + +### Use contract templates + +The MetaMask Unity SDK offers several contract templates that you can create and manage inside the +Unity editor. +These templates are scriptable objects, so you can configure them once inside the editor and use +them throughout your scripts. +These templates automatically perform the `Contract.Attach` function for you and automatically +switch contract addresses when the network changes. + +You can create a new template by going to **Assets > Create > MetaMask > Contract Templates** and +selecting one of the following: + +- **ERC20** +- **ERC721** +- **ERC1155** + +Before using the contract template, configure the contract address to use for each chain: + +

+ +![empty template](../../../assets/unity-empty-template.png) + +

+ +Select **+** to add a new address/chain pair. +When adding a new address, if you don't see your desired blockchain listed, you can modify the +`ScriptableContract.ChainId` enum to include your chain and chain ID. + +

+ +![full template](../../../assets/unity-example-template.png) + +

+ +Once configured, you can use this scriptable object as a variable inside your scripts. +The contract template has the same interface and usage as if you used `Contract.Attach`, but the +setup and network switching is done for you. + +## Advanced topics + +To learn more about and customize your contract interactions using the Unity SDK, see the following topics: + +- [Contract interface](contract-interface.md) +- [Contract factory](contract-factory.md) +- [Contract proxy class](contract-proxy-class.md) +- [Contract provider](contract-provider.md) diff --git a/wallet/index.md b/wallet/index.md index 39830a76f17..f530c7d6587 100644 --- a/wallet/index.md +++ b/wallet/index.md @@ -47,7 +47,7 @@ functions, including: - [Sign data](how-to/sign-data) - [Display tokens, contract methods, and icons in MetaMask](how-to/display) -- [Interact with smart contracts](how-to/interact-with-smart-contracts.md) +- [Interact with smart contracts](how-to/interact-with-smart-contracts/index.md) - [Access a user's MetaMask provider](how-to/access-provider.md) ## Questions? diff --git a/wallet/reference/provider-api.md b/wallet/reference/provider-api.md index 2fc096ccf36..1f38027b6c5 100644 --- a/wallet/reference/provider-api.md +++ b/wallet/reference/provider-api.md @@ -1,6 +1,6 @@ --- description: MetaMask Ethereum provider API reference -sidebar_position: 2 +sidebar_position: 3 --- # Ethereum provider API diff --git a/wallet/reference/rpc-api.md b/wallet/reference/rpc-api.md index e2fd9ecc3ec..a84360d4aee 100644 --- a/wallet/reference/rpc-api.md +++ b/wallet/reference/rpc-api.md @@ -1,6 +1,6 @@ --- description: MetaMask Ethereum JSON-RPC API reference -sidebar_position: 3 +sidebar_position: 4 toc_max_heading_level: 2 --- diff --git a/wallet/reference/sdk-unity-api.md b/wallet/reference/sdk-unity-api.md new file mode 100644 index 00000000000..8b4aadd7cec --- /dev/null +++ b/wallet/reference/sdk-unity-api.md @@ -0,0 +1,71 @@ +--- +description: Unity SDK API reference +sidebar_position: 2 +--- + +# Unity SDK API + +The following is an overview of the API methods used in the [Unity SDK](../how-to/connect/set-up-sdk/gaming/unity.md). + +## MetaMaskUnity + +This is a singleton class that you can use to access the `MetaMaskWallet` instance, which is +specific to Unity. + +### Instance + +This is the singleton instance of the `MetaMaskUnity` class that is lazy-loaded when you access it +for the first time. + +### Initialize + +This method initializes the `MetaMaskWallet` instance and makes it accessible via the `Wallet` property. +You can also pass extra options and parameters to it to customize the wallet instance: + +```csharp +// Initialize using default settings +MetaMaskUnity.Instance.Initialize(); + +// Initialize using custom transport and socket provider +var transport = new MyCustomTransport(); +var socketProvider = new MyCustomSocketProvider(); +MetaMaskUnity.Instance.Initialize(transport, socketProvider); + +// Initialize using custom config, transport and socket provider +var config = myMetaMaskConfig; +var transport = new MyCustomTransport(); +var socketProvider = new MyCustomSocketProvider(); +MetaMaskUnity.Instance.Initialize(config, transport, socketProvider); +``` + +### SaveSession + +This method saves the current session to persistent storage. +It is useful when you want to save the session and restore it later. +When the application starts, it automatically calls this method. +You can also manually call this method. + +### LoadSession + +This method loads the session from persistent storage. +It is useful when you want to restore the session after the application quits. +When the application starts, it automatically calls this method. +You can also manually call this method. + +## MetaMaskWallet + +### Connect + +This method connects to MetaMask. +It renders a generated QR code in the user interface for your users to scan with MetaMask Mobile. +After the user scans this QR code, a connection screen appears in MetaMask Mobile where the user can +approve the connection with your Unity game. + +### Disconnect + +This method disconnects the user from the MetaMask session. + +### Request + +This method sends a request to MetaMask. +You can use it to call any [provider API method](provider-api.md).