diff --git a/docs/unity/connecting-accounts.md b/docs/unity/connecting-accounts.md new file mode 100644 index 000000000..c34202217 --- /dev/null +++ b/docs/unity/connecting-accounts.md @@ -0,0 +1,80 @@ +--- +title: Connecting accounts +authors: Tim McMackin +last_update: + date: 11 January 2024 +--- + +Connecting to a user's wallet is a prerequisite to working with Tezos in any application. +Accessing the wallet allows your project to see the tokens in it and to prompt the user to submit transactions, but it does not give your project direct control over the wallet. +Users still confirm or reject all transactions in their wallet application, so you must handle both of these use cases. + +Using a wallet application in this way saves you from having to implement payment processing and security in your application. +Game developers can also use the wallet and its account as a unique account identifier and as the user's inventory. + +For an example of connecting to wallets, see the [WalletConnection tutorial scene](./scenes#wallet-connection-scene). + +## Best practices + +When working with wallets, be sure to follow the advice in [Best practices and avoiding flaws](../dApps/best-practices) for wallet connections. +For example, don't force the user to connect their wallet as soon as the application loads. +Instead, let them see the application first. +Also, provide a prominent disconnect button to allow users to disconnect one account and connect a different one. + +## The `TezosAuthenticator` prefab + +The `TezosAuthenticator` prefab provides the tools that you need to connect to user's Tezos wallets in a Unity project. +You can copy the `TezosAuthenticator` and `TezosManager` prefabs to your scene, and the `TezosAuthenticator` prefab automatically adds features that connect to users' wallets. + +## Connection methods + +This table shows the ways that the SDK can connect to wallets and which platforms they are appropriate for: + +Connection method | Description | Web platform (WebGL) | Mobile apps | Standalone applications +--- | --- | --- | --- | --- +QR code | Users scan a QR code with a wallet app | Yes | No | Yes +Deep link | The application opens the user's wallet app directly | Yes | Yes | No +Social wallets | The application opens the user's Kukai web-based wallet | Yes | No | No + +Regardless of the connection method, the Tezos SDK for Unity runs the `WalletConnected` or `WalletConnectionFailed` event, as appropriate. +For more information about events, see the [Unity SDK EventManager object](./reference/EventManager). + + + + +### QR code connections + +This method generates a QR code that a user scans with their wallet application: + +1. The Unity application calls the [`Wallet.Connect()`](./reference/Wallet#connect) method with the `walletProvider` parameter set to `WalletProviderType.beacon` to send a connection request to a wallet application via the [TZIP-10 protocol](https://gitlab.com/tezos/tzip/-/tree/master/proposals/tzip-10). +1. The wallet returns a handshake that includes pairing information for the wallet, which triggers the `HandshakeReceived` event. +1. From the handshake information, the SDK generates a QR code. +The `TezosAuthenticator` prefab handles the QR code generation with the `QrCodeGenerator` class. +1. The user scans the QR code with their wallet app and approves the connection. +1. The SDK receives the connection approval, which triggers the `WalletConnected` event and includes information about the connected account. + +### Deep link connections + +Deep link connections open the user's wallet app directly, which can be a mobile app or a browser extension. +This method relies on the Beacon SDK to interact with wallet apps: + +1. The Unity WebGL application calls the [`Wallet.Connect()`](./reference/Wallet#connect) method with the `walletProvider` parameter set to `WalletProviderType.beacon`. +The Beacon SDK detects that it is running in a web application and opens a popup window with the wallets that Beacon can connect to: + + Beacon popup window with wallet types including Temple and Umami + +1. The [Beacon](https://walletbeacon.io/) SDK handles the process of connecting to the wallet. +1. The SDK receives the connection approval, which triggers the `WalletConnected` event and includes information about the connected account. + +### Social connections + +Social wallets exist as accounts managed by web apps such as [Kukai](https://kukai.app/). + +To connect to a social wallet, the Unity WebGL application calls [`Wallet.Connect()`](./reference/Wallet#connect) with the `walletProvider` parameter set to `WalletProviderType.kukai`. + + + +## Disconnecting + +It's important to provide a disconnect button so the user can disconnect when they are finished with the application or if they want to connect with a different account. +To disconnect the active wallet, call the [`Wallet.Disconnect()`](./reference/Wallet#disconnect) method. diff --git a/docs/unity/managing-contracts.md b/docs/unity/managing-contracts.md new file mode 100644 index 000000000..97df80546 --- /dev/null +++ b/docs/unity/managing-contracts.md @@ -0,0 +1,300 @@ +--- +title: Managing contracts +authors: Tim McMackin +last_update: + date: 18 December 2023 +--- + +Smart contracts are backend programs that run on the Tezos blockchains. +Smart contracts can do many tasks, but for gaming they have two main purposes: + +- They handle tokens, which are digital assets stored on the blockchain +- They provide backend logic that users can trust because it cannot change + +For more information about contracts, see [Smart contracts](../smart-contracts). + +You can create your own smart contracts or use the built-in contract that the SDK provides for managing tokens in Unity projects. + +The Contract tutorial scene shows how to deploy a copy of the built-in contract from a Unity project. + +## The built-in contract + +The SDK includes a built-in contract that you can use to manage tokens for your Unity projects. + +The contract has entrypoints that allow you to create and transfer tokens. +See [Managing tokens](./managing-tokens). + +The Michelson source code of the built-in contract is in the `Resources/Contracts` folder of the SDK, but it isn't very human-readable. +For a list of the entrypoints in the contract, see [TokenContract object](./reference/TokenContract). + +## Deploying the built-in contract + +To deploy the built-in contract, call the [`TokenContract.Deploy()`](./reference/TokenContract#deploy) method and pass a callback function: + +```csharp +public void DeployContract() +{ + TezosManager + .Instance + .Tezos + .TokenContract + .Deploy(OnContractDeployed); +} + +private void OnContractDeployed(string contractAddress) +{ + Debug.Log(contractAddress); +} +``` + +The project sends the deployment transaction to the connected wallet, which must approve the transaction and pay the related fees. +The callback function receives the address of the deployed contract, which the project uses to send requests to the contract. +It can take a few minutes for the contract to deploy and be confirmed in multiple blocks on the blockchain. + +The address that deployed the contract becomes the administrator of the contract and is the only account that can create tokens. + +The SDK provides information about the contract such as its address in the [`TokenContract`](./reference/TokenContract) object. +You can use block explorers such as [Better Call Dev](https://better-call.dev/) to see information about the deployed contract. + +For information about using the built-in contract, see [Managing tokens](./managing-tokens). + +## Getting the contract address + +When you deploy a contract with the [`TokenContract.Deploy()`](./reference/TokenContract#deploy) method, the SDK saves the contract address by running this code: + +```csharp +PlayerPrefs.SetString("CurrentContract:" + Tezos.Wallet.GetActiveAddress(), contractAddress); +``` + +Then during SDK initialization, the SDK saves the address to the [`TokenContract.Address`](./reference/TokenContract) property. + +To retrieve the address of contracts that you haven't deployed through the project, you can use the [`API.GetOriginatedContractsForOwner()`](./reference/API#getoriginatedcontractsforowner) method. + +## Calling contracts + +The built-in contract has convenience methods for minting and transferring tokens; see [Managing tokens](./managing-tokens). + +To call the contract's other entrypoints, use the [`Wallet.CallContract()`](./reference/Wallet#callcontract) method. +For example, to call the contract's `set_administrator` entrypoint to set a new administrator account, use this code: + +```csharp +TezosManager.Instance.Tezos.Wallet.CallContract( + contractAddress: TezosManager.Instance.Tezos.TokenContract.Address, + entryPoint: "set_administrator", + input: new MichelineString(newAdminAddress).ToJson() +); +``` + +For information about the entrypoints in the built-in contract, see [Unity SDK TokenContract object](./reference/TokenContract#entrypoints). + +You can call any other contract by using its address, entrypoint name, and parameter value, as in this example: + +```csharp +TezosManager.Instance.Tezos.Wallet.CallContract( + contractAddress: address, + entryPoint: entryPointName, + input: new MichelineInt(12).ToJson() +); +``` + +This example passes the value 12 to the entrypoint in the variable `entryPointName`. + +Note that the parameter is encoded as a Michelson value. +For information about encoding more complex parameters, see [Encoding parameters](#encoding-parameters). + +To get the hash of the transaction, use the `ContractCallCompleted` event. + +## Encoding parameters + +When you call contract entrypoints or views with the `Wallet.CallContract()` or `Wallet.ReadView()` methods, you must encode the parameter as a Micheline value. +For example, if an entrypoint accepts two integers and one string as parameters, you must pass a list of two `Netezos.Encoding.MichelineInt` values and one `Netezos.Encoding.MichelineString` value: + +```csharp +var input = new MichelinePrim +{ + Prim = PrimType.Pair, + Args = new List + { + new MichelineInt(1), + new MichelineInt(2), + new MichelineString("My string value") + } +}.ToJson(); + +TezosManager.Instance.Tezos.Wallet.CallContract( + contractAddress: address, + entryPoint: entryPointName, + input: input +); +``` + +You can also use the value of the parameters in Michelson JSON. +The previous example looks like this with a JSON parameter value: + +```csharp +var input = @"{ + ""prim"": ""Pair"", + ""args"": [ + { + ""int"": ""1"" + }, + { + ""prim"": ""Pair"", + ""args"": [ + { + ""int"": ""2"" + }, + { + ""string"": ""My string value"" + } + ] + } + ] +}"; + +TezosManager.Instance.Tezos.Wallet.CallContract( + contractAddress: address, + entryPoint: entryPointName, + input: input +); +``` + +Some block explorers allow you to fill in parameter values for an entrypoint and then download the Michelson JSON to use in your code. + +You can build more complex parameters out of `Netezos.Encoding` objects. +For example, the built-in contract has an entrypoint named `update_operators`, which is an FA2 standard entrypoint that gives an account control over another account's tokens. +It accepts a list of changes to make to token operators, each including these fields in this order: + +- Either "add_operator" or "remove_operator" +- The address of the operator, which will be able to control the owner's tokens of the specified ID. +- The ID of the token +- The address of the token owner + +This is the Michelson parameter type for the endpoint: + +``` +(list %update_operators (or + (pair %add_operator (address %owner) + (pair (address %operator) + (nat %token_id))) + (pair %remove_operator (address %owner) + (pair + (address %operator) + (nat %token_id))))) +``` + +In this case, you set the "add_operator" value by passing a `PrimType.Left` Michelson primitive or the "remove_operator" value by passing a `PrimType.Right` primitive. +The values in the primitive are a series of nested pairs called a [right comb](../smart-contracts/data-types/complex-data-types#right-combs), as in this example: + +```json +{ + "prim": "LEFT", + "args": [ + { + "prim": "Pair", + "args": [ + { + "string": "tz1QCVQinE8iVj1H2fckqx6oiM85CNJSK9Sx" + }, + { + "prim": "Pair", + "args": [ + { + "string": "tz1hQKqRPHmxET8du3fNACGyCG8kZRsXm2zD" + }, + { + "int": "1" + } + ] + } + ] + } + ] +} +``` + +The code to create a list of these elements to pass to the entrypoint looks like this: + +```csharp +var operatorAddress = "tz1hQKqRPHmxET8du3fNACGyCG8kZRsXm2zD"; +var ownerAddress = "tz1QCVQinE8iVj1H2fckqx6oiM85CNJSK9Sx"; +int[] tokenIds = {1, 2, 3}; + +var operatorArray = new MichelineArray(); +foreach (var tokenId in tokenIds) +{ + operatorArray.Add(new MichelinePrim + { + Prim = PrimType.Left, + Args = new List + { + new MichelinePrim + { + Prim = PrimType.Pair, + Args = new List + { + new MichelineString(ownerAddress), + new MichelinePrim + { + Prim = PrimType.Pair, + Args = new List + { + new MichelineString(operatorAddress), + new MichelineInt(tokenId) + } + } + + } + } + } + }); +}; + +TezosManager.Instance.Tezos.Wallet.CallContract( + contractAddress: address, + entryPoint: "update_operators", + input: operatorArray.ToJson() +); +``` + +## Deploying other contracts + +To deploy a contract from Unity, you must compile the contract to Michelson in JSON format. +For example, to compile a contract in LIGO to Michelson JSON, run this code: + +```bash +ligo compile contract MyContract.jsligo \ + -m MyContract -o MyContract.json --michelson-format json +``` + +Then, ensure that the code of the code and initial storage value of the contract are wrapped in `code` and `storage` fields at the root of the file, as in this example: + +```json +{ + "code": [ + { + "prim": "parameter", + "args": [ + ... + }, + ], + "storage": { + "int": "0" + } +} +``` + +To deploy the contract from the Unity project, use the [`Wallet.OriginateContract()`](./reference/Wallet#originatecontract) method, as in this example: + +```csharp +var contractJSON = Resources.Load("Contracts/MyContract").text; +TezosManager.Instance.Tezos.Wallet.OriginateContract(contractJSON); +``` + +To get the address of the deployed contract, use the `ContractCallCompleted` event. + + + diff --git a/docs/unity/managing-tokens.md b/docs/unity/managing-tokens.md new file mode 100644 index 000000000..e91cc7dce --- /dev/null +++ b/docs/unity/managing-tokens.md @@ -0,0 +1,157 @@ +--- +title: Managing tokens +authors: Tim McMackin +last_update: + date: 11 January 2024 +--- + +The SDK's built-in contract is compatible with the [FA2 token standard](../architecture/tokens/FA2), which means that you can use a single smart contract to manage any number of types of tokens, including: + +- Fungible tokens, which are collections of interchangeable tokens with a quantity that you define. +Fungible tokens can be quantifiable commodities like in-game currency, fuel, ammunition, or energy, or they can be identical items with a limited quantity. +- Non-fungible tokens (NFTs), which are unique assets with only one unit. +Games use NFTs for items that are unique and must not be duplicated. + +You can create as many tokens and types of tokens as you need in one contract, but each transaction to create or transfer tokens incurs fees. + +## Creating (minting) tokens + +To create a token type, call the contract's `mint` entrypoint and pass these parameters: + +- A callback function to run when the token is created +- The metadata for the token, which includes a name and description, URIs to preview media or thumbnails, and how many decimal places the token can be broken into +- The destination account that owns the new tokens, which can be a user account, this smart contract, or any other smart contract +- The number of tokens to create + +For example, this code creates a token type with a quantity of 100: + +```csharp +var initialOwner = TezosManager + .Instance + .Wallet + .GetActiveAddress(); + +const string imageAddress = "ipfs://QmX4t8ikQgjvLdqTtL51v6iVun9tNE7y7Txiw4piGQVNgK"; + +var tokenMetadata = new TokenMetadata +{ + Name = "My token", + Description = "Description for my token", + Symbol = "MYTOKEN", + Decimals = "0", + DisplayUri = imageAddress, + ArtifactUri = imageAddress, + ThumbnailUri = imageAddress +}; + +TezosManager + .Instance + .Tezos + .TokenContract + .Mint( + completedCallback: OnTokenMinted, + tokenMetadata: tokenMetadata, + destination: initialOwner, + amount: 100); + +private void OnTokenMinted(TokenBalance tokenBalance) +{ + Debug.Log($"Successfully minted token with Token ID {tokenBalance.TokenId}"); +} +``` + +For a complete example of creating tokens, see the file `TezosSDK/Examples/Contract/Scripts/MintToken.cs` and the Contract tutorial scene. + +## Transferring tokens + +To transfer tokens, call the contract's `Transfer` entrypoint and pass these parameters: + +- A callback function to run when the transfer is complete +- The account to transfer the tokens to +- The ID of the token +- The amount of tokens to transfer + +This example transfers 12 tokens with the ID 5 to the account in the variable `destinationAccountAddress`. + +```csharp +public void HandleTransfer() +{ + TezosManager + .Instance + .Tezos + .TokenContract + .Transfer( + completedCallback: TransferCompleted, + destination: destinationAccountAddress, + tokenId: 5, + amount: 12); +} + +private void TransferCompleted(string txHash) +{ + Logger.LogDebug($"Transfer complete with transaction hash {txHash}"); +} +``` + +For a complete example, see the Transfer tutorial scene. + +## Getting token balances + +To get the tokens that the connected account owns, call the [`API.GetTokensForOwner()`](./reference/API#gettokensforowner) method in a coroutine. +This example prints information about the tokens that the account owns to the log: + +```csharp +private void Start() +{ + // Subscribe to account connection event + TezosManager.Instance.EventManager.WalletConnected += OnWalletConnected; +} + +private void OnWalletConnected(WalletInfo walletInfo) +{ + // Address of the connected wallet + var address = walletInfo.Address; + + // Prepare the coroutine to fetch the tokens + var routine = TezosManager.Instance.Tezos.API.GetTokensForOwner( + OnTokensFetched, // Callback to be called when the tokens are fetched + address, true, 10_000, new TokensForOwnerOrder.ByLastTimeAsc(0)); + + StartCoroutine(routine); +} + +private void OnTokensFetched(IEnumerable tokenBalances) +{ + var walletAddress = TezosManager.Instance.Wallet.GetWalletAddress(); + var contractAddress = TezosManager.Instance.Tezos.TokenContract.Address; + + var tokens = new List(tokenBalances); + + // Filter the tokens by the current contract address + var filteredTokens = tokens.Where(tb => tb.TokenContract.Address == contractAddress).ToList(); + + if (filteredTokens.Count > 0) + { + foreach (var tb in filteredTokens) + { + Debug.Log($"{walletAddress} has {tb.Balance} tokens on contract {tb.TokenContract.Address}"); + Debug.Log(tb.TokenMetadata); + } + } + else + { + Debug.Log($"{walletAddress} has no tokens in the active contract"); + } +} +``` + +## Destroying (burning) tokens + +The built-in contract does not have a burn entrypoint, so you can't destroy its tokens. +If you want to make tokens unusable, send them to an address that doesn't exist or to an account that you can't use. +For example, you can create an account in a wallet app, send the tokens to it, and delete the private key for the account. + + \ No newline at end of file diff --git a/sidebars.js b/sidebars.js index 715afac1e..2e14f2228 100644 --- a/sidebars.js +++ b/sidebars.js @@ -207,6 +207,9 @@ const sidebars = { 'unity/quickstart', 'unity/scenes', 'unity/prefabs', + 'unity/connecting-accounts', + 'unity/managing-contracts', + 'unity/managing-tokens', { type: 'category', label: 'Reference', diff --git a/static/img/unity/unity-connecting-beacon-popup.png b/static/img/unity/unity-connecting-beacon-popup.png new file mode 100644 index 000000000..32a650b63 Binary files /dev/null and b/static/img/unity/unity-connecting-beacon-popup.png differ