### Install Marketplace Extension
Source: https://docs.gaming.chainsafe.io/current/getting-started
A guide for installing the Marketplace extension for the Web3 Unity SDK. This extension enables marketplace features and depends on the core SDK. Installation is performed via Git URL in the Unity Package Manager.
```git
https://github.com/ChainSafe/web3.unity.git?path=/Packages/io.chainsafe.web3-unity.marketplace
```
--------------------------------
### Install Web3Auth Login Provider
Source: https://docs.gaming.chainsafe.io/current/getting-started
Guide to installing the Web3Auth Login Provider extension for the Web3 Unity SDK. This module enables users to log in using Web3Auth, requiring the core SDK as a dependency. Installation is done via Git URL in the Unity Package Manager.
```git
https://github.com/ChainSafe/web3.unity.git?path=/Packages/io.chainsafe.web3-unity.web3auth
```
--------------------------------
### Install Fiat On/Off Ramp Support
Source: https://docs.gaming.chainsafe.io/current/getting-started
Guide to installing the Fiat On/Off Ramp support extension for the Web3 Unity SDK. This module facilitates fiat currency transactions and depends on the core SDK. Installation is performed using a Git URL within the Unity Package Manager.
```git
https://github.com/ChainSafe/web3.unity.git?path=/Packages/io.chainsafe.web3-unity.ramp
```
--------------------------------
### Install Core Web3 Unity SDK
Source: https://docs.gaming.chainsafe.io/current/getting-started
Instructions for installing the core Web3 Unity SDK package using the Unity Package Manager via a Git URL. This package is essential for standard chain interactions and forms the foundation for other modules.
```git
https://github.com/ChainSafe/web3.unity.git?path=/Packages/io.chainsafe.web3-unity
```
--------------------------------
### Install MUD Extension
Source: https://docs.gaming.chainsafe.io/current/getting-started
Instructions for installing the MUD (Machina Unity Development) extension for the Web3 Unity SDK. This module integrates MUD capabilities and requires the core SDK. Installation is done via Git URL in the Unity Package Manager.
```git
https://github.com/ChainSafe/web3.unity.git?path=/Packages/io.chainsafe.web3-unity.mud
```
--------------------------------
### Install Hyperplay Login Provider
Source: https://docs.gaming.chainsafe.io/current/getting-started
Instructions for installing the Hyperplay Login Provider extension for the Web3 Unity SDK. This provider facilitates login through Hyperplay and depends on the core SDK. Installation is performed using a Git URL within the Unity Package Manager.
```git
https://github.com/ChainSafe/web3.unity.git?path=/Packages/io.chainsafe.web3-unity.hyperplay
```
--------------------------------
### Install Lootboxes Extension
Source: https://docs.gaming.chainsafe.io/current/getting-started
Details on installing the Lootboxes extension for the Web3 Unity SDK. This module provides functionality related to lootboxes and requires the core SDK. Installation is managed through the Unity Package Manager using a Git URL.
```git
https://github.com/ChainSafe/web3.unity.git?path=/Packages/io.chainsafe.web3-unity.lootboxes
```
--------------------------------
### Start Local WebGL Server (Windows)
Source: https://docs.gaming.chainsafe.io/current/ramp
This command starts a simple web server on port 8000 for Unity WebGL builds on Windows. It requires the path to your Unity Editor installation and the build directory.
```bash
"C:/Program Files/Unity/Hub/Editor/2022.3.../Editor/Data/MonoBleedingEdge/bin/mono.exe" "C:/Program Files/Unity/Hub/Editor/2022.3.../Editor/Data/PlaybackEngines/WebGLSupport/BuildTools/SimpleWebServer.exe" "[Build Directory]" 8000
```
--------------------------------
### Start Local WebGL Server (Mac/Linux)
Source: https://docs.gaming.chainsafe.io/current/ramp
This command starts a local HTTP server on port 8000 using Python for Unity WebGL builds on Mac and Linux. Ensure Python is installed and you are in the build directory.
```bash
py -m http.server
```
--------------------------------
### Add Wallet Providers in Unity Inspector
Source: https://docs.gaming.chainsafe.io/current/choose-your-wallet
This snippet describes how to add wallet providers to a Unity game using the Web3Unity prefab. It guides users to the Connection Handler script in the inspector, expanding the Connection Providers dropdown, and clicking 'Add Provider' to configure WalletConnect and MetaMask. It also mentions installing additional packages for Web3Auth (social login) and Hyperplay.
```C#
/*
In the Web3Unity prefab, navigate to the Connection Handler script in the inspector.
Expand the Connection Providers dropdown.
Click the 'Add Provider' button to add WalletConnect (Reown) and MetaMask.
To add social login (Google, Facebook, X), install the web3auth package.
To publish on the Hyperplay launcher, install the Hyperplay package.
*/
```
--------------------------------
### Initialize and Get ERC-20 Balance with Web3.unity SDK
Source: https://docs.gaming.chainsafe.io/index
This C# code snippet demonstrates how to initialize the Web3.unity SDK and retrieve the ERC-20 token balance for a given contract address. It requires the Web3.unity SDK to be installed and configured within a Unity project.
```csharp
public class ExampleClass : MonoBehaviour
{
public async void Start()
{
await Web3Unity.Instance.Initialize(false);
await Web3Unity.Web3.Erc20.BalanceOf("0xd25b827D92b0fd656A1c829933e9b0b836d5C3e2");
}
}
```
--------------------------------
### C# Contract Write Call Example
Source: https://docs.gaming.chainsafe.io/current/block-racers-game
This C# script demonstrates how to make a write call to a smart contract, modifying its state. It includes an example of adding to a state variable and logging the transaction response. Dependencies include the ChainSafe Gaming SDK.
```csharp
using UnityEngine;
using ChainSafe.Gaming.UnityPackage;
using Scripts.EVM.Token;
/* This prefab script should be copied & placed on the root of an object in a scene.
Change the class name, variables and add any additional changes at the end of the function.
The scripts function should be called by a method of your choosing - button, function etc */
///
/// Makes a write call to a contract
///
publicclassContractSend:MonoBehaviour
{
// Variables
privatestring abi ="[ { \"inputs\": [ { \"internalType\": \"uint256\", \"name\": \"_myArg\", \"type\": \"uint256\" } ], \"name\": \"addTotal\", \"outputs\": [], \"stateMutability\": \"nonpayable\", \"type\": \"function\" }, { \"inputs\": [], \"name\": \"getStore\", \"outputs\": [ { \"internalType\": \"string[]\", \"name\": \"\", \"type\": \"string[]\" } ], \"stateMutability\": \"view\", \"type\": \"function\" }, { \"inputs\": [ { \"internalType\": \"address\", \"name\": \"\", \"type\": \"address\" } ], \"name\": \"myTotal\", \"outputs\": [ { \"internalType\": \"uint256\", \"name\": \"\", \"type\": \"uint256\" } ], \"stateMutability\": \"view\", \"type\": \"function\" }, { \"inputs\": [ { \"internalType\": \"string[]\", \"name\": \"_addresses\", \"type\": \"string[]\" } ], \"name\": \"setStore\", \"outputs\": [], \"stateMutability\": \"nonpayable\", \"type\": \"function\" } ]";
privatestring contractAddress ="0x9839293240C535d8009920390b4D3DA256d31177";
privatestring method ="addTotal";
privateint increaseAmount =1;
// Function
publicasyncvoidSendContract()
{
object[] args =
{
increaseAmount
};
var data =await Evm.ContractSend(Web3Accessor.Web3, method, abi, contractAddress, args);
var response = SampleOutputUtil.BuildOutputValue(data);
Debug.Log($"TX: {response}");
// You can make additional changes after this line
}
}
```
--------------------------------
### C# Contract Read Call Example
Source: https://docs.gaming.chainsafe.io/current/block-racers-game
This C# script allows you to make a read call to a smart contract. It checks a contract's state variable and logs the output. It requires the ChainSafe Gaming SDK and uses a predefined ABI and contract address.
```csharp
using UnityEngine;
using ChainSafe.Gaming.UnityPackage;
using Scripts.EVM.Token;
/* This prefab script should be copied & placed on the root of an object in a scene.
Change the class name, variables and add any additional changes at the end of the function.
The scripts function should be called by a method of your choosing - button, function etc */
///
/// Makes a read call to a contract
///
publicclassContractCall:MonoBehaviour
{
// Variables
privatestring abi ="[ { \"inputs\": [ { \"internalType\": \"uint256\", \"name\": \"_myArg\", \"type\": \"uint256\" } ], \"name\": \"addTotal\", \"outputs\": [], \"stateMutability\": \"nonpayable\", \"type\": \"function\" }, { \"inputs\": [], \"name\": \"getStore\", \"outputs\": [ { \"internalType\": \"string[]\", \"name\": \"\", \"type\": \"string[]\" } ], \"stateMutability\": \"view\", \"type\": \"function\" }, { \"inputs\": [ { \"internalType\": \"address\", \"name\": \"\", \"type\": \"address\" } ], \"name\": \"myTotal\", \"outputs\": [ { \"internalType\": \"uint256\", \"name\": \"\", \"type\": \"uint256\" } ], \"stateMutability\": \"view\", \"type\": \"function\" }, { \"inputs\": [ { \"internalType\": \"string[]\", \"name\": \"_addresses\", \"type\": \"string[]\" } ], \"name\": \"setStore\", \"outputs\": [], \"stateMutability\": \"nonpayable\", \"type\": \"function\" } ]";
privatestring contractAddress ="0x9839293240C535d8009920390b4D3DA256d31177";
privatestring method ="myTotal";
// Function
publicasyncvoidCallContract()
{
object[] args =
{
await Web3Accessor.Web3.Signer.GetAddress()
};
var data =await Evm.ContractCall(Web3Accessor.Web3, method, abi, contractAddress, args);
var response = SampleOutputUtil.BuildOutputValue(data);
Debug.Log($"Output: {response}");
// You can make additional changes after this line
}
}
```
--------------------------------
### Install ChainSafe Lootboxes SDK for Unity
Source: https://docs.gaming.chainsafe.io/current/lootboxes
Instructions on how to install the ChainSafe Gaming lootboxes package for Unity using a Git URL in the Package Manager. This enables the lootbox functionality within your Unity project.
```bash
https://github.com/ChainSafe/web3.unity.git?path=/Packages/io.chainsafe.web3-unity.lootboxes
```
--------------------------------
### Chain Switching Example in C#
Source: https://docs.gaming.chainsafe.io/current/chain-switching
Demonstrates how to switch between blockchain chains and interact with smart contracts using the ChainSafe SDK in Unity. It includes setting up the contract and calling a method, then switching back to the original chain.
```C#
publicclassChainSwitchingSample:MonoBehaviour
{
[SerializeField]privatestring newChainId;
[SerializeField]privatestring newChainContractAddress;
[SerializeField]privatestring newChainContractAbi;
asyncvoidStart()
{
//Make sure web3 instance is initialized
var currentChainId = Web3Unity.Web3.Chains.Current.ChainId;
await Web3Unity.Web3.SwitchChain(newChainId);
//For the sake of simplicity, we're demonstrating the 'old-fashioned' way of building contracts.
var contract =await Web3Unity.Web3.ContractBuilder.Build(newChainContractAbi, newChainContractAddress);
//Use the return value however you want. You can always call the contract.Call method even if you don't have the wallet bound to the web3 instance.
var returnValue =await contract.Call("exampleMethod");
//It's recommended to return back to the old chain as soon as you finish interaction with contracts on the other chains.
await Web3Unity.Web3.SwitchChain(currentChainId);
}
}
```
--------------------------------
### Install Ramp Package via Git URL
Source: https://docs.gaming.chainsafe.io/current/ramp
Instructions on how to add the ChainSafe web3.unity SDK Ramp package to your project using a Git URL in the Unity Package Manager.
```bash
https://github.com/ChainSafe/web3.unity.git?path=/Packages/io.chainsafe.web3-unity.ramp
```
--------------------------------
### Convert Wallet Address to Checksum Format (C#)
Source: https://docs.gaming.chainsafe.io/current/faq
This C# code snippet demonstrates how to convert a wallet address to its checksum format using the Nethereum.Util library. It includes a helper method for the conversion and an example of how to call it.
```csharp
using Nethereum.Util;
private string ConvertToChecksum(string address)
{
string checksumAddress = new AddressUtil().ConvertToChecksumAddress(address);
return checksumAddress;
}
var checksumAddress = ConvertToChecksum(Your Address Here);
```
--------------------------------
### QuickNode: Create Endpoint and Retrieve URLs
Source: https://docs.gaming.chainsafe.io/current/setting-up-an-rpc-node
Instructions for creating an endpoint on QuickNode and obtaining the RPC and WebSocket URLs. This process includes selecting the chain and network, then accessing the endpoint dashboard to find the necessary URLs for configuring the ChainSafe server settings in the SDK.
```JavaScript
const { Web3 } = require('web3');
// Replace with your QuickNode HTTPS and WSS endpoints
const rpcUrl = 'YOUR_QUICKNODE_HTTPS_ENDPOINT';
const wsUrl = 'YOUR_QUICKNODE_WSS_ENDPOINT';
const web3 = new Web3(rpcUrl);
console.log('Connected to QuickNode RPC:', rpcUrl);
// Example: Get block number
web3.eth.getBlockNumber().then((blockNumber) => {
console.log('Current Block Number:', blockNumber);
}).catch((error) => {
console.error('Error getting block number:', error);
});
// Example: Subscribe to new blocks using WebSocket
const subscription = web3.eth.subscribe('newHeads', (error, result) => {
if (error) {
console.error('Subscription error:', error);
return;
}
console.log('New block received:', result);
});
console.log('Subscribed to new block headers.');
// To unsubscribe later:
// subscription.unsubscribe((error, success) => {
// if (success)
// console.log('Successfully unsubscribed!');
// else
// console.error('Failed to unsubscribe:', error);
// });
```
--------------------------------
### Initialize Contract (Solidity)
Source: https://docs.gaming.chainsafe.io/assets/files/marketplace_abi-97f6fc0bf7e880279f7cc3faaee8856b
Sets up the initial configuration of the contract, including project and marketplace IDs, creator, updater, treasury, whitelisting status, and fee percentages. This function can only be called once.
```solidity
function initialize(string memory projectID, string memory marketplaceID, address creator, address updater, address treasury, bool isWhitelistingEnable, uint256 chainsafeFeePercent, uint256 maxPercent) public
```
--------------------------------
### Display Marketplace Items in Unity
Source: https://docs.gaming.chainsafe.io/marketplace/tutorial
This C# script, intended for Unity, shows how to initialize the Web3Unity SDK, load marketplace items, and display them in the UI. It includes error handling and a loading overlay. The script iterates through fetched items and instantiates UI elements for each.
```csharp
namespace ChainSafe.Gaming.Marketplace.Samples {
public class MarketplaceSample : MonoBehaviour {
[SerializeField] private Transform parentForItems;
[SerializeField] private UI_MarketplaceItem marketplaceItem;
[SerializeField] private Button nextPageButton;
private MarketplacePage _currentPage;
private async void Start() {
//Always make sure to initialize the Web3Unity instance first.
await Web3Unity.Instance.Initialize(false);
try {
LoadingOverlay.ShowLoadingOverlay();
//This gets all items from the marketplace
//LoadPage has a lot of parameters that you can fill out in order to filter out the results.
_currentPage = await Web3Unity.Web3.Marketplace().LoadPage();
nextPageButton.interactable = !string.IsNullOrEmpty(_currentPage.Cursor);
await DisplayItems();
}
catch (Exception e) {
Debug.LogError("Caught an exception whilst loading the marketplace page " + e.Message);
}
finally {
LoadingOverlay.HideLoadingOverlay();
}
}
private async Task DisplayItems() {
for (int i = parentForItems.childCount - 1; i >= 0; i--) {
Destroy(parentForItems.GetChild(i).gameObject);
}
//_currentPage.Items holds the reference to all the items fetched from the marketplace
foreach (var pageItem in _currentPage.Items) {
var item = Instantiate(marketplaceItem, parentForItems);
await item.Initialize(pageItem);
}
}
}
}
```
--------------------------------
### Connect to Wallet (C#)
Source: https://docs.gaming.chainsafe.io/current/login-process
This C# script demonstrates how to initialize the Web3 SDK and connect to a wallet using a specific connection provider, such as WalletConnect. It checks if the connection was successful and provides access to the initialized Web3 instance.
```csharp
public class ConnectToWallet : MonoBehaviour
{
private async void Start()
{
await Web3Unity.Instance.Initialize(true);
await Web3Unity.Instance.Connect();
if (Web3Unity.Connected)
{
Debug.Log("Connected");
var web3 = Web3Unity.Web3;
}
}
}
```
--------------------------------
### Chainstack: Create Project and Deploy RPC Node
Source: https://docs.gaming.chainsafe.io/current/setting-up-an-rpc-node
Steps to create a project and deploy an RPC node on Chainstack. This involves navigating the Chainstack dashboard, selecting network details, choosing node deployment options, and joining the network. The process concludes with retrieving the HTTPS endpoint for use with the web3.unity SDK.
```C#
using UnityEngine;
using System.Collections;
using TMPro;
public class ChainstackExample : MonoBehaviour
{
public string rpcUrl = "YOUR_CHAINSTACK_HTTPS_ENDPOINT";
private Web3 web3;
async void Start()
{
web3 = new Web3(rpcUrl);
Debug.Log("Connected to Chainstack RPC: " + rpcUrl);
// Example: Get block number
var blockNumber = await web3.Eth.Blocks.GetBlockNumber.SendRequestAsync();
Debug.Log("Current Block Number: " + blockNumber.Value);
}
}
```
--------------------------------
### Create Web3 Instance with Private Key
Source: https://docs.gaming.chainsafe.io/current/sample-scripts
Demonstrates how to create a Web3 instance using a private key without a wallet provider. It configures the instance with Unity environment, RPC provider, and an in-process signer and transaction executor, then sets the client for the transaction manager.
```C#
var web3Builder =newWeb3Builder(Web3Unity.Web3.ProjectConfig, Web3Unity.Web3.ChainConfig).Configure(s =>
{
s.UseUnityEnvironment();
s.UseRpcProvider();
TempAccountProvider tempAccountProvider =newTempAccountProvider()
{
//Private key should be in the string format
Account =newAccount("PRIV_KEY")
};
s.AddSingleton(tempAccountProvider);
s.UseInProcessSigner();
s.UseInProcessTransactionExecutor();
});
var web3 =await web3Builder.LaunchAsync();
var account = web3.ServiceProvider.GetService();
//We need to set the client of the transaction manager in order to send transactions properly.
account.Account.TransactionManager.Client = web3.ServiceProvider.GetService();
publicclassTempAccountProvider:IAccountProvider
{
IAccount Account {get;set;}
}
```
--------------------------------
### Get Collection Token API Response Sample
Source: https://docs.gaming.chainsafe.io/token-api/docs/tokenapi
This is a sample JSON response for the 'Get Collection Token' API endpoint, which returns details for a single token within a collection. It includes all relevant token attributes.
```json
{
"id": "string",
"token_id": "string",
"chain_id": "string",
"project_id": "string",
"collection_id": "string",
"token_type": "string",
"contract_address": "string",
"supply": "string",
"uri": "string",
"metadata": {}
}
```
--------------------------------
### Get Collection Tokens API Response Sample
Source: https://docs.gaming.chainsafe.io/token-api/docs/tokenapi
This JSON sample represents the response from the 'Get Collection Tokens' API endpoint. It provides pagination information and a list of tokens within a specific collection, detailing each token's attributes.
```json
{
"page_number": 0,
"page_size": 0,
"total": 0,
"cursor": "string",
"tokens": [
{
"id": "string",
"token_id": "string",
"chain_id": "string",
"project_id": "string",
"collection_id": "string",
"token_type": "string",
"contract_address": "string",
"supply": "string",
"uri": "string",
"metadata": {}
}
]
}
```
--------------------------------
### Block Blasterz Game Project Files
Source: https://docs.gaming.chainsafe.io/current/block-blasterz-game
Access the repository containing the complete source code for the Block Blasterz FPS game. This project serves as a practical demonstration of the ChainSafe SDK's integration within a game environment. The code is provided for educational purposes.
```N/A
Block Blasterz Project Files
```
--------------------------------
### Provide a Demo Version for App Store Review
Source: https://docs.gaming.chainsafe.io/current/faq
This approach addresses app store rejections by suggesting the implementation of a demo mode. This mode allows store reviewers to test the application's functionality without requiring a live blockchain connection or external wallet, simplifying the review process.
```csharp
/*
* Add a demo button that leads to a free-to-play version of the game.
* This version should not include blockchain calls.
*/
public void GoToDemoVersion() {
// Implementation to load a demo scene or mode
Debug.Log("Loading demo version of the game...");
// UnityEngine.SceneManagement.SceneManager.LoadScene("DemoScene");
}
```
--------------------------------
### Get Project Tokens API Response Sample
Source: https://docs.gaming.chainsafe.io/token-api/docs/tokenapi
This is a sample JSON response for the 'Get Project Tokens' API endpoint. It includes pagination details and a list of tokens, each with its associated properties like ID, chain ID, project ID, and metadata.
```json
[
{
"page_number": 0,
"page_size": 0,
"total": 0,
"cursor": "string",
"tokens": [
{
"id": "string",
"token_id": "string",
"chain_id": "string",
"project_id": "string",
"collection_id": "string",
"token_type": "string",
"contract_address": "string",
"supply": "string",
"uri": "string",
"metadata": {}
}
]
}
]
```
--------------------------------
### Get Marketplace Items API Response Sample
Source: https://docs.gaming.chainsafe.io/marketplace-api/docs/marketplaceapi
This is a sample JSON response for the 'Get Marketplace Items' API endpoint. It illustrates the structure of data returned when querying items within a specific marketplace, including pagination details and item properties.
```json
{
"page_number": 0,
"page_size": 0,
"total": 0,
"cursor": "string",
"items": [
{
"id": "string",
"chain_id": "string",
"project_id": "string",
"marketplace_id": "string",
"token": {
"id": "string",
"token_id": "string",
"token_type": "string",
"contract_address": "string",
"uri": "string",
"metadata": {
"property1": "string",
"property2": "string"
}
},
"marketplace_contract_address": "string",
"seller": "string",
"buyer": "string",
"price": "string",
"listed_at": 0,
"status": "sold"
}
]
}
```
--------------------------------
### Download Minter Contract ABIs
Source: https://docs.gaming.chainsafe.io/launchpad/tutorial
Provides links to download the minter contract ABIs for ERC721 and ERC1155 token types. These ABIs are necessary for interacting with the smart contracts used in the NFT launchpad.
```text
721 minter contract ABI
1155 minter contract ABI
```
--------------------------------
### Get Project Items API Response Sample
Source: https://docs.gaming.chainsafe.io/marketplace-api/docs/marketplaceapi
This is a sample JSON response for the 'Get Project Items' API endpoint. It details the structure of the returned data, including pagination information and a list of items with their associated properties like ID, chain ID, token details, and marketplace status.
```json
[
{
"page_number": 0,
"page_size": 0,
"total": 0,
"cursor": "string",
"items": [
{
"id": "string",
"chain_id": "string",
"project_id": "string",
"marketplace_id": "string",
"token": {
"id": "string",
"token_id": "string",
"token_type": "string",
"contract_address": "string",
"uri": "string",
"metadata": {
"property1": "string",
"property2": "string"
}
},
"marketplace_contract_address": "string",
"seller": "string",
"buyer": "string",
"price": "string",
"listed_at": 0,
"status": "sold"
}
]
}
]
```
--------------------------------
### Assigning web3UnityInstance in JavaScript
Source: https://docs.gaming.chainsafe.io/current/faq
This snippet demonstrates the core logic for assigning the Unity instance to the global `web3UnityInstance` variable after the Unity instance is created and loaded. It includes handling the progress of the loading bar and setting up a fullscreen button.
```javascript
script.onload=()=>{
createUnityInstance(canvas, config,(progress)=>{
progressBarFull.style.width=100* progress +"%";
}).then((unityInstance)=>{
web3UnityInstance = unityInstance;
loadingBar.style.display="none";
fullscreenButton.onclick=()=>{
unityInstance.SetFullscreen(1);
};
}).catch((message)=>{
alert(message);
});
};
```
--------------------------------
### Get Collection ID
Source: https://docs.gaming.chainsafe.io/assets/files/1155_minter_contract_abi-729b2f38234ddcaf241eab3c882bb037
Returns the unique identifier for the NFT collection. This is a view function.
```solidity
function collectionID() public view returns (string memory) {
// Implementation details omitted for brevity
}
```
--------------------------------
### Gaming Chainsafe Constructor
Source: https://docs.gaming.chainsafe.io/assets/files/marketplace_abi-97f6fc0bf7e880279f7cc3faaee8856b
Initializes the Gaming Chainsafe smart contract. It sets up the contract's state upon deployment.
```Solidity
{
"inputs": [],
"stateMutability": "nonpayable",
"type": "constructor"
}
```
--------------------------------
### Get Contract Name (name)
Source: https://docs.gaming.chainsafe.io/assets/files/721_minter_contract_abi-7214c606563b8deb770e202493c45552
Returns the name of the NFT collection. This is a view function.
```solidity
function name() public view returns (string memory)
```
--------------------------------
### UI Marketplace Item Display in Unity
Source: https://docs.gaming.chainsafe.io/marketplace/tutorial
This C# script for Unity handles the display of individual marketplace items in the UI. It initializes item details, including image, type, ID, and price, and sets up a button for interaction, such as purchasing.
```csharp
//Monobehaviour that handles the display of the marketplace items.
public class UI_MarketplaceItem : MonoBehaviour {
[SerializeField] private Image marketplaceItemImage;
[SerializeField] private TMP_Text type, itemId, itemPrice, itemStatus;
[SerializeField] private Button button;
private MarketplaceItem _marketplaceItemModel;
private static Dictionary _spritesDict = new();
public async Task Initialize(MarketplaceItem model) {
_marketplaceItemModel = model;
button.interactable = model.Status == MarketplaceItemStatus.Listed;
itemStatus.text = model.Status == MarketplaceItemStatus.Listed ? "Purchase" : model.Status.ToString();
marketplaceItemImage.sprite = await GetSprite(model);
type.text = model.Token.Type;
itemId.text = "ID " + model.Token.Id;
itemPrice.text =
((decimal)BigInteger.Parse(model.Price) / (decimal)BigInteger.Pow(10, 18)).ToString("0.############",
CultureInfo.InvariantCulture) + Web3Unity.Web3.ChainConfig.Symbol;
button.onClick.AddListener(Purchase);
}
private async Task GetSprite(MarketplaceItem model) {
Sprite sprite = null;
string imageUrl = (string)model.Token.Metadata["image"];
//Caching data for faster retreival of the sprites.
if (_spritesDict.TryGetValue(imageUrl, out sprite)) return sprite;
var unityWebRequest = UnityWebRequestTexture.GetTexture(imageUrl);
await unityWebRequest.SendWebRequest();
if (unityWebRequest.error != null) {
Debug.LogError("There was an error getting the texture " + unityWebRequest.error);
return null;
}
var myTexture = ((DownloadHandlerTexture)unityWebRequest.downloadHandler).texture;
sprite = Sprite.Create(myTexture, new Rect(0, 0, myTexture.width, myTexture.height), Vector2.one * 0.5f);
return sprite;
}
private async void Purchase() {
try {
await Web3Unity.Web3.Marketplace().Purchase(_marketplaceItemModel.Id, _marketplaceItemModel.Price);
}
catch (Exception e) {
Debug.LogError("Error purchasing item: " + e.Message);
}
}
}
```
--------------------------------
### Get Project ID
Source: https://docs.gaming.chainsafe.io/assets/files/1155_minter_contract_abi-729b2f38234ddcaf241eab3c882bb037
Returns the unique identifier for the project associated with this contract. This is a view function.
```solidity
function projectID() public view returns (string memory) {
// Implementation details omitted for brevity
}
```
--------------------------------
### Load Marketplace Page in Unity
Source: https://docs.gaming.chainsafe.io/marketplace/tutorial
This C# code demonstrates how to load a page of items from the ChainSafe marketplace using the Web3Unity SDK. It retrieves a marketplace page, which may contain paginated results.
```csharp
var marketplacePage =await Web3Unity.Web3.Marketplace().LoadPage();
```
--------------------------------
### Get Role Admin (getRoleAdmin)
Source: https://docs.gaming.chainsafe.io/assets/files/721_minter_contract_abi-7214c606563b8deb770e202493c45552
Retrieves the admin role for a given role. This is a view function.
```solidity
function getRoleAdmin(bytes32 role) public view returns (bytes32)
```
--------------------------------
### Get Collection ID (collectionID)
Source: https://docs.gaming.chainsafe.io/assets/files/721_minter_contract_abi-7214c606563b8deb770e202493c45552
Retrieves the unique identifier for the NFT collection. This is a view function.
```solidity
function collectionID() public view returns (string memory)
```
--------------------------------
### Add ChainSafe Marketplace Package to Unity
Source: https://docs.gaming.chainsafe.io/marketplace/tutorial
This snippet shows how to add the ChainSafe marketplace package to your Unity project using the Package Manager with a Git URL. Ensure you have the correct path to the package.
```bash
https://github.com/ChainSafe/web3.unity.git?path=/Packages/io.chainsafe.web3-unity.marketplace
```
--------------------------------
### Subscribe to Web3 Initialized Event (C#)
Source: https://docs.gaming.chainsafe.io/current/login-process
This C# script shows how to subscribe to the Web3Initialized event to be notified when the Web3 instance is created. It includes methods for subscribing in Awake and unsubscribing in OnDestroy to manage the event listener lifecycle.
```csharp
public class SubscribeToWeb3Created : MonoBehaviour
{
private void Awake()
{
//Make sure to subscribe to the Web3Initialized event in awake so that you don't miss out the event invocation.
Web3Unity.Web3Initialized += Web3Initialized;
}
private async void Web3Initialized((Web3 web3, bool isLightweight) obj)
{
}
private void OnDestroy()
{
Web3Unity.Web3Initialized -= Web3Initialized;
}
}
```
--------------------------------
### Get Role Admin
Source: https://docs.gaming.chainsafe.io/assets/files/1155_minter_contract_abi-729b2f38234ddcaf241eab3c882bb037
Retrieves the admin role for a given role. This is part of the access control mechanism.
```solidity
function getRoleAdmin(bytes32 role) public view returns (bytes32) {
// Implementation details omitted for brevity
}
```
--------------------------------
### Get Current Lootbox Price
Source: https://docs.gaming.chainsafe.io/current/lootboxes
Retrieves the current price of lootboxes. This information can be displayed to users to show the current cost.
```C#
publicasyncTaskGetPrice()
{
var response =awaitthis.contract.Call("getPrice",newobject[]{});
return BigInteger.Parse(response[0].ToString());
}
```
--------------------------------
### Get NFT Token Address (Solidity)
Source: https://docs.gaming.chainsafe.io/assets/files/marketplace_abi-97f6fc0bf7e880279f7cc3faaee8856b
Returns the address of an NFT contract associated with a given ID. This is a view function.
```solidity
function nftToken(uint256 id) public view returns (address token) {
// ... implementation details ...
}
```
--------------------------------
### Configure Web3 Client for MUD in Unity
Source: https://docs.gaming.chainsafe.io/current/mud
This C# code configures the Web3 client in Unity to connect to a MUD world. It demonstrates initializing the Web3 client with project and chain configurations, and enabling the MUD module using MudConfigAsset. It also shows how to set up the client to use a local Ethereum node account for transactions.
```C#
public MudConfigAsset mudConfig;
private Web3 web3;
async void Awake()
{
web3 = await new Web3Builder(
ProjectConfigUtilities.Load(),// project config
ProjectConfigUtilities.BuildLocalhostConfig())// chain config
.Configure(services =>
{
// ...
services.UseMud(mudConfig);// enable MUD
})
.LaunchAsync();
}
```
```C#
web3 = await new Web3Builder(/* ... */)
.Configure(services =>
{
// ...
// Initializes wallet as the first account of the locally running Ethereum Node (Anvil).
services.Debug().UseJsonRpcWallet(new JsonRpcWalletConfig{ AccountIndex =0});
// ...
})
.LaunchAsync();
```
--------------------------------
### Add Custom IRpcProvider Implementation
Source: https://docs.gaming.chainsafe.io/current/extending-the-sdk
Demonstrates how to create a custom implementation for the IRpcProvider interface and bind it using an extension method for IWeb3ServiceCollection.
```C#
public class MyXmlRpcProvider : IRpcProvider
{
// ...
}
```
```C#
using Microsoft.Extensions.DependencyInjection
public static class MyXMLRpcProviderExtensions
{
public static IWeb3ServiceCollection UseMyXmlProvider(this IWeb3ServiceCollection services)
{
services.AddSingleton();
return services;
}
}
```
```C#
public static void UseMyXmlProvider(this IWeb3ServiceCollection services)
{
services.AssertServiceNotBound();
services.AddSingleton();
}
```
```C#
var web3 = await new Web3Builder(ProjectConfigUtilities.Load())
.Configure(services =>
{
services.UseMyXmlProvider();
})
.LaunchAsync();
```
--------------------------------
### Get Max Fee Percent (Solidity)
Source: https://docs.gaming.chainsafe.io/assets/files/marketplace_abi-97f6fc0bf7e880279f7cc3faaee8856b
Retrieves the maximum allowed fee percentage for marketplace transactions. This is a view function.
```solidity
function maxFeePercent() public view returns (uint256) {
// ... implementation details ...
}
```
--------------------------------
### C# ERC20 Contract Interaction
Source: https://docs.gaming.chainsafe.io/current/sample-scripts
Demonstrates interacting with an ERC20 contract in C#. It covers initializing the Web3 SDK, building a custom contract instance, subscribing to transfer events, and disposing of the contract. This method is recommended for efficient blockchain interactions.
```C#
publicclassCustomContractSample:MonoBehaviour
{
[SerializeField]privatestring contractAddress;
Erc20Contract _erc20Contract;
voidAwake()
{
//Make sure to subscribe to the Web3Initialized event in awake so that you don't miss out the event invocation.
Web3Unity.Web3Initialized += Web3Initialized;
}
publicasyncvoidStart()
{
//You should call the Initialize only from a single place.
//That way there is no potential race condition and the behaviour of the app can become unpredictable.
if(Web3Unity.Web3 ==null)
await Web3Unity.Instance.Initialize(false);
}
//Always create your custom contract inside of the event handler. That way you always have the up-to-date data inside of it.
privateasyncvoidWeb3Initialized((Web3 web3,bool isLightweight) obj)
{
//Since Web3Initialized event can be invoked multiple times during the app lifecycle (once you open the app and don't have a wallet, then when there is a wallet etc.)
//You need to properly dispose the previously created contract to remove any potential memory leaks.
if(_erc20Contract !=null)
{
_erc20Contract.OnTransfer -= Erc20Transfer;
await _erc20Contract.DisposeAsync();
}
_erc20Contract =await web3.ContractBuilder.Build(contractAddress);
_erc20Contract.OnTransfer += Erc20Transfer;
}
publicasyncstringBalanceOf(string address)
{
returnawait _erc20Contract.BalanceOf(address);
}
publicasyncvoidTransfer(string destinationAddress,BigInteger amount)
{
await _erc20.Transfer(destinationAddress, amount);
}
publicasyncvoidOnDestroy()
{
Web3Unity.Web3Initialized -= Web3Initialized;
await _erc20Contract.DisposeAsync();
}
}
```
--------------------------------
### Get Token Owner (ownerOf)
Source: https://docs.gaming.chainsafe.io/assets/files/721_minter_contract_abi-7214c606563b8deb770e202493c45552
Retrieves the owner's address for a given token ID. This is a view function.
```solidity
function ownerOf(uint256 tokenId) public view returns (address)
```
--------------------------------
### Get Approved Address for Token (getApproved)
Source: https://docs.gaming.chainsafe.io/assets/files/721_minter_contract_abi-7214c606563b8deb770e202493c45552
Returns the approved address for a specific token ID. This function is viewable.
```solidity
function getApproved(uint256 tokenId) public view returns (address)
```
--------------------------------
### Configure Web3 Service with RPC Provider
Source: https://docs.gaming.chainsafe.io/current/extending-the-sdk
Demonstrates how to configure a Web3 service with a custom RPC provider during the build time. It involves creating a new class for configuration data and adding a dependency of this type to the service.
```C#
var web3 =awaitnewWeb3Builder(ProjectConfigUtilities.Load())
.Configure(services =>
{
services.UseRpcProvider(newJsonRpcProviderConfig
{
RpcNodeUrl ="letsplayvideogamesallday.org/json-rpc"
});
})
.LaunchAsync();
```
--------------------------------
### Claim and Claim Rewards in Unity SDK
Source: https://docs.gaming.chainsafe.io/current/lootboxes
Example C# code demonstrating how to claim a lootbox and subsequently claim rewards using the ChainSafe Gaming SDK within a Unity project. It includes logic for selecting a lootbox, specifying the amount to open, and handling asynchronous operations.
```csharp
privateasyncTaskClaimLootbox()
{
var selectedText = lootboxDropdown.options[lootboxDropdown.value].text;
Debug.Log("Claiming Lootbox");
if(uint.TryParse(selectedText.Replace("ID: ","),outuint selectedId)&& lootboxBalances.TryGetValue(selectedId,outuint selectedAmount))
{
uint amountToOpen =1;
await lootboxService.OpenLootbox(selectedId, amountToOpen);
}
Debug.Log("Claiming rewards");
awaitnewWaitForSeconds(30);
await lootboxService.ClaimRewards();
}
```
--------------------------------
### Get Role Admin (Solidity)
Source: https://docs.gaming.chainsafe.io/assets/files/marketplace_abi-97f6fc0bf7e880279f7cc3faaee8856b
Retrieves the administrative role assigned to a specific role. This is fundamental for understanding role-based access control.
```solidity
function getRoleAdmin(bytes32 role) public view returns (bytes32)
```
--------------------------------
### Build MUD World Client in Unity
Source: https://docs.gaming.chainsafe.io/current/mud
This C# code snippet shows how to build a MUD world client in Unity after configuring the Web3 client. It demonstrates calling the `BuildWorld` method with manual configuration for the MUD world, including contract address, ABI, namespace, and table schemas.
```C#
world = await web3.Mud().BuildWorld(new MudWorldConfig
{
ContractAddress = worldContractAddress,
ContractAbi = worldContractAbi.text,
DefaultNamespace = "app",
TableSchemas = new List
{
new()
{
Namespace = "app",
TableName = "Counter",
Columns = new List>
{
new("value","uint32"),
},
KeyColumns = new string[0],// empty key schema - singleton table (one record only)
},
},
});
```
--------------------------------
### Get Chainsafe Treasury Address (Solidity)
Source: https://docs.gaming.chainsafe.io/assets/files/marketplace_abi-97f6fc0bf7e880279f7cc3faaee8856b
Retrieves the address of the Chainsafe treasury. This is a view function, meaning it does not modify the contract state.
```solidity
function chainsafeTreasury() public view returns (address)
```
--------------------------------
### Get NFT Inventory
Source: https://docs.gaming.chainsafe.io/current/lootboxes
Fetches all NFTs in the connected wallet's inventory based on the contract provided to the service adapter. It deserializes the result into a LootboxItemList.
```csharp
public async Task GetInventory()
{
var result = await this.contract.Call("getInventory");
var jsonResult = JsonConvert.DeserializeObject(JsonConvert.SerializeObject(result));
return jsonResult;
}
```