diff --git a/es/sdk/unity/onboard/recovering-sessions.mdx b/es/sdk/unity/onboard/recovering-sessions.mdx new file mode 100644 index 00000000..6f3170f8 --- /dev/null +++ b/es/sdk/unity/onboard/recovering-sessions.mdx @@ -0,0 +1,120 @@ +--- +title: Recuperación segura de sesión +description: El SDK ofrece la opción de almacenar la información de la wallet de sesión de forma segura en ciertas plataformas utilizando el almacenamiento seguro nativo. +--- + +# Recuperación de sesiones +Por defecto, el SDK requerirá que los usuarios inicien sesión cada vez que la aplicación se cierre completamente. Esto se debe a que, por defecto, no guardamos la información de la wallet de sesión (por ejemplo, claves privadas) en ningún tipo de almacenamiento persistente para proteger la seguridad del usuario. + +Sin embargo, en ciertas plataformas, hemos integrado el almacenamiento seguro nativo de la plataforma. + +Si habilita `StoreSessionPrivateKeyInSecureStorage` en su ScriptableObject `SequenceConfig`, almacenaremos automáticamente la información de la wallet de sesión (en plataformas compatibles) y expondremos la opción de intentar recuperar la sesión en `SequenceLogin`. La `SequenceLoginWindow` predeterminada gestionará automáticamente este flujo de UI también (consulte [Autenticación](/sdk/unity/onboard/authentication/intro)). Si la plataforma no es compatible, esta opción no tendrá efecto. + +A continuación puede ver las plataformas compatibles y aprender sobre la solución de almacenamiento seguro de cada una; es importante entender los conceptos básicos de cómo funcionan estos sistemas y pensar cuidadosamente en las implicaciones de seguridad de almacenar claves privadas (o cualquier secreto) en almacenamiento persistente. + +## Integración +Tiene dos opciones para recuperar una wallet desde el almacenamiento. La primera es usar la clase `EmbeddedWalletAdapter`. Si esta llamada tiene éxito, el `EmbeddedWalletAdapter` contendrá la instancia de Wallet. + +```csharp +bool recovered = await EmbeddedWalletAdapter.GetInstance().TryRecoverWalletFromStorage(); +``` + +De lo contrario, utilice la clase subyacente `SequenceLogin`. + +```csharp +(bool storageEnabled, IWallet wallet) = await SequenceLogin.GetInstance().TryToRestoreSessionAsync(); +``` + +En ambos casos, puede escuchar el evento `SequenceWallet.OnWalletCreated` cada vez que una wallet se recupere del almacenamiento o se cree durante el proceso de inicio de sesión. + +## Detalles de la plataforma + +### Editor +En el editor, usamos PlayerPrefs para almacenar la clave privada. También deberá habilitar `EditorStoreSessionPrivateKeyInSecureStorage` en SequenceConfig para usar el almacenamiento seguro y recuperar sesiones dentro del editor. Esta bandera separada le facilita probar ambos flujos sin modificar el comportamiento de sus builds. El almacenamiento seguro en el editor es solo para fines de desarrollo y no debe considerarse seguro para almacenamiento a largo plazo. + +### iOS +En iOS, utilizamos el [iOS Keychain](https://developer.apple.com/documentation/security/keychain_services?language=objc). + +### MacOS +En MacOS, utilizamos el [MacOS Keychain](https://developer.apple.com/documentation/security/keychain_services?language=objc). + +### Windows +En PCs con Windows, utilizamos la [Crypto: Next Generation - Data Protection API (CNG DPAPI)](https://learn.microsoft.com/en-us/windows/win32/seccng/cng-dpapi) + +### Web +En compilaciones Web, utilizamos [IndexedDB](https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API) a través de [PlayerPrefs](https://docs.unity3d.com/ScriptReference/PlayerPrefs.html). + +### Android +En compilaciones Android, utilizamos el [Android Keystore](https://developer.android.com/privacy-and-security/keystore). + +El primer paso es importar el plugin `AndroidKeyBridge.java` en su carpeta Assets. Esto se hace fácilmente desde Samples en el package manager; simplemente importe el sample titulado `Android Secure Storage`. + +Nuestro plugin Keystore para Unity (incluido en el SDK) requiere una Plantilla Gradle Principal personalizada. Por favor, vaya a la configuración de su proyecto y, en `Player > Publishing Settings`, habilite `Custom Main Gradle Template`. Esto creará un archivo `Assets/Plugins/Android/mainTemplate.gradle` (o similar; el editor le mostrará la ruta) si aún no tiene uno. Aquí tiene un ejemplo de archivo `mainTemplate.gradle`; por favor, copie/pegue (o incorpore en su archivo existente). + +``` +apply plugin: 'com.android.library' +**APPLY_PLUGINS** + +dependencies { + implementation fileTree(dir: 'libs', include: ['*.jar']) + implementation 'androidx.security:security-crypto:1.1.0-alpha03' + +**DEPS**} + +android { + compileSdkVersion **APIVERSION** + buildToolsVersion '**BUILDTOOLS**' + + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_8 + targetCompatibility JavaVersion.VERSION_1_8 + } + + defaultConfig { + minSdkVersion **MINSDKVERSION** + targetSdkVersion **TARGETSDKVERSION** + ndk { + abiFilters **ABIFILTERS** + } + versionCode **VERSIONCODE** + versionName '**VERSIONNAME**' + consumerProguardFiles 'proguard-unity.txt'**USER_PROGUARD** + } + + lintOptions { + abortOnError false + } + + aaptOptions { + noCompress = **BUILTIN_NOCOMPRESS** + unityStreamingAssets.tokenize(', ') + ignoreAssetsPattern = "!.svn:!.git:!.ds_store:!*.scc:.*:!CVS:!thumbs.db:!picasa.ini:!*~" + }**PACKAGING_OPTIONS** +}**REPOSITORIES** +**IL_CPP_BUILD_SETUP** +**SOURCE_BUILD_SETUP** +**EXTERNAL_SOURCES** +``` + +Nuestro plugin Keystore también requiere una Plantilla de Propiedades Gradle personalizada. Nuevamente, vaya a la configuración de su proyecto y, en `Player > Publishing Settings`, habilite `Custom Gradle Properties Template`. Esto creará un archivo `Assets/Plugins/Android/gradleTemplate.properties` (o similar; el editor le mostrará la ruta) si aún no tiene uno. Aquí tiene un ejemplo de archivo `gradleTemplate.properties`; por favor, copie/pegue (o incorpore en su archivo existente). + +``` +org.gradle.jvmargs=-Xmx**JVM_HEAP_SIZE**M +org.gradle.parallel=true +android.enableJetifier=true +android.useAndroidX=true +unityStreamingAssets=**STREAMING_ASSETS** +**ADDITIONAL_PROPERTIES** + +android.enableR8=**MINIFY_WITH_R_EIGHT** +``` + +## Solución de problemas +Si tiene problemas con el almacenamiento seguro o Google Sign-In en Android, siga estos pasos de solución de problemas. +- **Google Sign-In:** Asegúrese de que el valor `data android:scheme` en su archivo `AndroidManifest.xml` coincida con el `Url Scheme` en su archivo + `SequenceConfig.asset`. Verifique que esté todo en minúsculas. +- **Almacenamiento seguro:** Asegúrese de que su `mainTemplate.gradle` defina correctamente el plugin `androidx.security:security-crypto` y que no sea + sobrescrito por otro plugin o por el Android Plugin Resolver. +- **Pruebe nuestra demo:** [Instale nuestra build de demostración](https://drive.google.com/file/d/1rAvnPu56Hj3yDRL32_lr887xt-xMQoYK/view?usp=sharing) + y asegúrese de que funcione correctamente en su dispositivo. + - Compare la configuración de su proyecto Unity (AndroidManifest, archivos gradle, configuración del reproductor de Android) con nuestro [proyecto sdk.](https://github.com/0xsequence/sequence-unity) +- **Ideas adicionales:** Desinstale la app antes de instalar una nueva build, cambie su esquema de URL o el bundle id. \ No newline at end of file diff --git a/es/sdk/unity/onboard/session-management.mdx b/es/sdk/unity/onboard/session-management.mdx index bc557c70..d2b2f6e4 100644 --- a/es/sdk/unity/onboard/session-management.mdx +++ b/es/sdk/unity/onboard/session-management.mdx @@ -1,5 +1,5 @@ --- -title: Gestión de sesiones en Unity — Documentación de Sequence +title: Gestión de Sesiones --- Una vez que haya autenticado a su usuario con las APIs de Sequence y establecido una sesión, tiene disponibles varios métodos para gestionar la sesión. diff --git a/es/sdk/unity/power/advanced/contracts.mdx b/es/sdk/unity/power/advanced/contracts.mdx new file mode 100644 index 00000000..4d91c64a --- /dev/null +++ b/es/sdk/unity/power/advanced/contracts.mdx @@ -0,0 +1,156 @@ +--- +title: Smart Contracts +--- + +Crear un objeto `Contract` para un contrato ya desplegado es bastante sencillo. + +```csharp +Contract contract = new Contract(contractAddress, abi); +``` + +Aunque no es estrictamente necesario, se recomienda encarecidamente proporcionar el ABI del contrato como una cadena al crear un objeto contract. Si no lo hace, no podrá aprovechar completamente nuestra codificación y decodificación ABI. +Si decide seguir este camino, deberá proporcionar la firma completa de la función (nombre de la función + tipos de parámetros entre paréntesis - por ejemplo, transfer(address,uint256) para el método transfer de ERC20) al llamar a una función o consultar el contrato, y solo recibirá una cadena como respuesta a las consultas. + +## Llamar funciones de Smart Contract +Para llamar a un smart contract, usará el método `CallFunction` para crear un objeto `CallContractFunction`, que determinará el gasPrice, gasLimit, nonce y data apropiados para incluir en un nuevo `EthTransaction` al proporcionarle un cliente y un objeto `ContractCall` al método `Create` async Task + +Un ejemplo de cómo llamar a un smart contract sería el siguiente: + +```csharp +Contract erc20Contract = new Contract(contractAddress, contractAbi); // We'll use the well-known ERC20 contract as our example case +TransactionReceipt receipt = await erc20Contract.CallFunction("transfer", toAddress, amountAsBigInteger).SendTransactionMethodAndWaitForReceipt(wallet, client); +``` + +Nota: si no desea esperar el recibo, puede usar `SendTransactionMethod` en su lugar. + +Alternativamente, si solo quiere crear el `EthTransaction` y enviarlo más tarde, puede usar directamente el objeto `CallContractFunction` de `CallFunction`. + +```csharp +Contract erc20Contract = new Contract(contractAddress, contractAbi); // We'll use the well-known ERC20 contract as our example case +EthTransaction transaction = await erc20Contract.CallFunction("transfer", toAddress, amountAsBigInteger).Create(client, new ContractCall(wallet.GetAddress())); +TransactionReceipt receipt = await wallet.SendTransactionAndWaitForReceipt(client, transaction); + +// or +CallContractFunction transactionCreator = erc20Contract.CallFunction("transfer", toAddress, amountAsBigInteger); +EthTransaction transaction = await transactionCreator.Create(client, new ContractCall(wallet.GetAddress())); +TransactionReceipt receipt = await wallet.SendTransactionAndWaitForReceipt(client, transaction); + +// or +CallContractFunction transactionCreator = erc20Contract.CallFunction("transfer", toAddress, amountAsBigInteger); +TransactionReceipt receipt = await transactionCreator.SendTransactionMethodAndWaitForReceipt(wallet, client); +``` + +Notará que el método `CallFunction` acepta un número arbitrario de argumentos. Debe proporcionar los argumentos en el orden en que aparecen en el ABI/firma de la función. + +## Comprendiendo los mapeos de tipos de datos +Al interactuar con smart contracts, es importante entender cómo los tipos de datos de EVM se mapean a los tipos de datos de C# en la librería SequenceEthereum. + +Por ejemplo, si proporciona una cadena donde el ABI espera un entero, recibirá una excepción, incluso si esa cadena podría convertirse en un entero. + +### Address +En C# puede usar un tipo `string` o crear una instancia de `Address`. Asegúrese de que su cadena sea hexadecimal, +comience con `0x` y tenga una longitud fija de 42 caracteres. + +```csharp +Address address = new Address("0x123..."); +``` + +### Enteros +Para tipos de enteros como `int256`, `uint8` o `uint256` use el tipo `BigInteger` de System.Numerics. + +```csharp +// Simple number +BigInteger number = new BigInteger(10000); + +// From hex +string hexString = "0x0000000...01"; +BigInteger number = hexString.HexStringToBigInteger(); +``` + +### Bytes +Para definir tipos de datos byte de Solidity en C#, tiene la opción de crear un `FixedByte` para tipos como `byte16` o `byte32`. +Cuando su contrato requiera `bytes`, puede convertir cualquier valor en un `byte[]` de cualquier longitud. + +Si sus datos están representados como una cadena hexadecimal en C#, asegúrese de usar nuestra función `HexStringToByteArray()` para convertir +el valor hexadecimal de vuelta al arreglo de bytes original. + +Para arreglos de bytes como `byte32[]`, simplemente cree un `FixedByte[]` en C#. + +```csharp +// byte16 or byte32 +new FixedByte(16, new byte[] {}); + +// bytes +string someString = "abc0123456789"; +byte[] bytes = someString.ToByteArray(); + +// signature +string signature = "0x0ab123..."; +byte[] bytes = signature.HexStringToByteArray(); +``` + +### Structs +Use Tuples para llamar una función on-chain con un struct. Aquí hay un ejemplo de un struct en Solidity y cómo definirlo +usando el SDK de Unity de Sequence y pasarlo como argumento en una función `Contract.CallFunction`. + +Struct de Solidity + +```solidity +struct ExampleStruct { + address wallet; + uint256 amount; + byte32 data; +} +``` + +Equivalente en C# + +```csharp +Address wallet = new Address("0x..."); +BigInteger amount = new BigInteger(10000); +FixedByte data = new FixedByte(32, byteArrayData); +var arg = new Tuple(wallet, amount, data); +``` + +### Otros tipos +Para tipos de datos tradicionales en Solidity como `string` o `bool`, puede usar los mismos tipos de datos en C#. + +### Tipos de retorno +Cuando lea datos de un smart contract y utilice la función `Contract.SendQuery()`, puede usar TType para tipos de retorno simples como `string`, `BigInteger` o `bool`. Para tipos de retorno complejos como structs, use un `object[]` y analice manualmente los valores en su struct de C#. + +```csharp +// Let's consider a struct with the following variables: SomeStruct { address value1; uint256 value2; } +object[] structValues = Contract.SendQuery("SomeFunction"); + +SomeStruct newStruct = new SomeStruct() { + Value1 = new Address(structValues[0].ToString()), + Value2 = BigInteger.Parse(structValues[1].ToString()) +} +``` + +## Consultar contratos +Para consultar un smart contract (leer datos), use el método `SendQuery` para consultar el contrato y devolver el resultado como tipo T (si es posible). +Un ejemplo de cómo consultar un smart contract sería: + +```csharp +Contract erc20Contract = new Contract(contractAddress, contractAbi); // We'll use the well-known ERC20 contract as our example case +BigIntegar balance = await erc20Contract.SendQuery(client, "balanceOf", address); +``` + +Alternativamente, si desea simplemente construir la consulta y enviarla más tarde, puede usar `QueryContract` para crear un delegado. + +```csharp +Contract erc20Contract = new Contract(contractAddress, contractAbi); // We'll use the well-known ERC20 contract as our example case +QueryContractMessageSender balanceQuery = erc20Contract.QueryContract("balanceOf", address); +BigIntegar balance = await balanceQuery(client); +// or +BigIntegar balance = await balanceQuery.SendQuery(client); +``` + +## Desplegar contratos +Si desea desplegar un contrato, puede usar el `ContractDeployer` + +```csharp +ContractDeploymentResult deploymentResult = await ContractDeployer.Deploy(client, wallet, contractBytecodeAsString); +string newlyDeployedContractAddress = deploymentResult.Receipt.contractAddress; +``` \ No newline at end of file diff --git a/es/sdk/unity/quickstart.mdx b/es/sdk/unity/quickstart.mdx index 9f0b1545..a03f9ff2 100644 --- a/es/sdk/unity/quickstart.mdx +++ b/es/sdk/unity/quickstart.mdx @@ -1,13 +1,13 @@ --- -title: Guía rápida de Unity +title: Inicio rápido description: Documentación de inicio rápido para el SDK de Unity de Sequence. --- - Instale la última versión del SDK de Unity de Sequence desde [OpenUPM](/sdk/unity/installation#openupm), - o utilice la [interfaz del Package Manager de Unity](/sdk/unity/installation#or-using-package-manager-ui) - y use la siguiente URL de Git: `https://github.com/0xsequence/sequence-unity.git?path=/Packages/Sequence-Unity` + Instale la última versión del Unity SDK de Sequence desde [OpenUPM](/sdk/unity/installation#openupm), + o utilice [Unity's Package Manager UI](/sdk/unity/installation#or-using-package-manager-ui) + y use la siguiente URL de Git `https://github.com/0xsequence/sequence-unity.git?path=/Packages/Sequence-Unity` @@ -23,11 +23,15 @@ description: Documentación de inicio rápido para el SDK de Unity de Sequence. - Comience estableciendo una sesión de wallet usando un OTP enviado por correo electrónico. Importe el ejemplo `Setup` desde el Package Manager UI, - lo que colocará un conjunto de plantillas en su proyecto dentro del directorio `Resources/`. - Cree el [Login Boilerplate](/sdk/unity/bootstrap_game#login) para enviar una contraseña de un solo uso al correo electrónico especificado. + Comience verificando si hay una sesión de wallet disponible en el almacenamiento: - Una vez que haya integrado sus primeras funciones, puede continuar con [proveedores de inicio de sesión adicionales](/sdk/unity/onboard/authentication/intro) + ```csharp + bool recovered = await EmbeddedWalletAdapter.GetInstance().TryRecoverWalletFromStorage(); + ``` + + Si eso devuelve `false`, debe pedirle al usuario que inicie sesión. Importe el ejemplo `Setup` desde la interfaz del Package Manager UI, lo que colocará un conjunto de plantillas en su proyecto dentro del directorio `Resources/`. Cree el [Login Boilerplate](/sdk/unity/bootstrap_game#login) para enviar una contraseña de un solo uso al correo electrónico especificado. + + Una vez que haya integrado sus primeras funciones, puede continuar con [proveedores de inicio de sesión adicionales](/sdk/unity/onboard/authentication/intro) como Google, Apple o PlayFab. ```csharp @@ -40,9 +44,9 @@ description: Documentación de inicio rápido para el SDK de Unity de Sequence. - El SDK de Unity de Sequence incluye una variedad de [Boilerplates](/sdk/unity/bootstrap_game) para ayudarte a iniciar tu juego rápidamente. - Una vez que todo esté configurado, puedes crear prefabs para mostrar un Perfil de Jugador, Inventario o Tienda dentro del juego. - Consulta [cómo integrar un Perfil de Jugador.](/sdk/unity/bootstrap_game#player-profile) + El SDK de Unity de Sequence incluye una variedad de [boilerplates](/sdk/unity/bootstrap_game) para ayudarle a iniciar su juego rápidamente. + Cuando todo esté configurado, puede crear prefabs para mostrar el perfil del jugador, el inventario o la tienda dentro del juego. + Vea [cómo integrar un perfil de jugador.](/sdk/unity/bootstrap_game#player-profile) ```csharp BoilerplateFactory.OpenSequencePlayerProfile(parent, wallet, chain); @@ -54,8 +58,8 @@ description: Documentación de inicio rápido para el SDK de Unity de Sequence. - Comience con `EmbeddedWalletAdapter` para iniciar su integración rápidamente con solo unas pocas líneas de código y estará listo para empezar. - Cuando desee personalizar su integración, consulte nuestra otra documentación como [autenticando usuarios](/sdk/unity/onboard/authentication/intro) o [cómo enviar transacciones](/sdk/unity/power/write-to-blockchain). + Comience con `EmbeddedWalletAdapter` para iniciar su integración rápidamente con solo unas líneas de código y estará listo para comenzar. + Cuando quiera personalizar su integración, consulte nuestra documentación sobre [autenticación de usuarios](/sdk/unity/onboard/authentication/intro) o [cómo enviar transacciones.](/sdk/unity/power/write-to-blockchain) ```csharp EmbeddedWalletAdapter adapter = EmbeddedWalletAdapter.GetInstance(); diff --git a/es/sdk/unity/setup.mdx b/es/sdk/unity/setup.mdx index ababde0e..eb31891a 100644 --- a/es/sdk/unity/setup.mdx +++ b/es/sdk/unity/setup.mdx @@ -1,9 +1,9 @@ --- -title: Configuración en Unity +title: Configuración description: Documentación para la configuración del SDK de Unity para la infraestructura de Sequence orientada a juegos web3. --- -# Setup +# Configuración 1. [Configure su Embedded Wallet](/sdk/headless-wallet/quickstart) en el Sequence Builder 2. Descargue el ScriptableObject de configuración de Unity `SequenceConfig.asset` desde la interfaz de Builder diff --git a/ja/sdk/unity/onboard/recovering-sessions.mdx b/ja/sdk/unity/onboard/recovering-sessions.mdx index 1642cd65..dd278638 100644 --- a/ja/sdk/unity/onboard/recovering-sessions.mdx +++ b/ja/sdk/unity/onboard/recovering-sessions.mdx @@ -12,19 +12,39 @@ description: SDK では、一部のプラットフォームでネイティブの 対応プラットフォームや各プラットフォームのセキュアストレージについては下記をご覧ください。これらのシステムの基本的な仕組みや、秘密鍵(またはその他の機密情報)を永続ストレージに保存する際のセキュリティリスクについて十分に理解しておくことが重要です。 -## iOS +## インテグレーション +ウォレットをストレージから復元する方法は2つあります。1つ目は、`EmbeddedWalletAdapter` クラスを使用する方法です。この呼び出しが成功すると、`EmbeddedWalletAdapter` にウォレットインスタンスが格納されます。 + +```csharp +bool recovered = await EmbeddedWalletAdapter.GetInstance().TryRecoverWalletFromStorage(); +``` + +それ以外の場合は、基盤となる `SequenceLogin` クラスを使用してください。 + +```csharp +(bool storageEnabled, IWallet wallet) = await SequenceLogin.GetInstance().TryToRestoreSessionAsync(); +``` + +どちらの場合でも、ウォレットがストレージから復元されたり、サインイン時に作成された際には、`SequenceWallet.OnWalletCreated` イベントを監視できます。 + +## プラットフォームの詳細 + +### エディター +エディターでは、秘密鍵の保存に PlayerPrefs を使用しています。また、セキュアストレージを利用してセッションを復元するには、SequenceConfig で `EditorStoreSessionPrivateKeyInSecureStorage` を有効にする必要があります。このフラグを個別に設定することで、ビルドの挙動を変更せずに両方のフローをテストしやすくなります。エディターでのセキュアストレージは開発用途のみを想定しており、長期的な保存には適していません。 + +### iOS iOS では、[iOS Keychain](https://developer.apple.com/documentation/security/keychain_services?language=objc) を利用しています。 -## MacOS +### MacOS MacOS では、[MacOS Keychain](https://developer.apple.com/documentation/security/keychain_services?language=objc) を利用しています。 -## Windows +### Windows Windows PC では、[Crypto: Next Generation - Data Protection API (CNG DPAPI)](https://learn.microsoft.com/en-us/windows/win32/seccng/cng-dpapi) を利用しています。 -## Web +### Web Web ビルドでは、[PlayerPrefs](https://docs.unity3d.com/ScriptReference/PlayerPrefs.html) を通じて [IndexedDB](https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API) を利用しています。 -## Android +### Android Android ビルドでは、[Android Keystore](https://developer.android.com/privacy-and-security/keystore) を利用しています。 まず最初に、`AndroidKeyBridge.java` プラグインを Assets フォルダにインポートします。これはパッケージマネージャーのサンプルから行うのが最も簡単です。`Android Secure Storage` というサンプルをインポートしてください。 @@ -88,13 +108,10 @@ unityStreamingAssets=**STREAMING_ASSETS** android.enableR8=**MINIFY_WITH_R_EIGHT** ``` -### Troubleshooting +## トラブルシューティング Android でセキュアストレージや Google サインインに問題が発生した場合は、以下のトラブルシューティング手順をお試しください。 - **Google サインイン:** `AndroidManifest.xml` ファイル内の `data android:scheme` の値が、`SequenceConfig.asset` ファイルの `Url Scheme` と一致しているか確認してください。すべて小文字で記載されていることもご確認ください。 - **セキュアストレージ:** `mainTemplate.gradle` で `androidx.security:security-crypto` プラグインが正しく定義されており、他のプラグインや Android Plugin Resolver によって上書きされていないことを確認してください。 - **デモをお試しください:** [デモビルドをインストール](https://drive.google.com/file/d/1rAvnPu56Hj3yDRL32_lr887xt-xMQoYK/view?usp=sharing) し、お使いのデバイスで正常に動作するかご確認ください。 - Unity プロジェクトの設定(AndroidManifest、gradle ファイル、Android プレイヤー設定)を、弊社の [SDK プロジェクト](https://github.com/0xsequence/sequence-unity) と比較してください。 -- **追加のアイデア:** 新しいビルドをインストールする前にアプリをアンインストールする、URL スキームやバンドル ID を変更する、などもお試しください。 - -## エディター -エディター上では、秘密鍵の保存に PlayerPrefs を使用しています。エディター内でセキュアストレージを利用しセッションを復元するには、SequenceConfig で 'EditorStoreSessionPrivateKeyInSecureStorage' を有効にしてください。このフラグを分けていることで、ビルドの挙動を変更せずに両方のフローをテストできます。エディターでのセキュアストレージは開発用途のみであり、長期保存には適していません。 \ No newline at end of file +- **追加のアイデア:** 新しいビルドをインストールする前にアプリをアンインストールする、URL スキームやバンドル ID を変更する、などもお試しください。 \ No newline at end of file diff --git a/ja/sdk/unity/onboard/session-management.mdx b/ja/sdk/unity/onboard/session-management.mdx index bf831c1b..4b56f381 100644 --- a/ja/sdk/unity/onboard/session-management.mdx +++ b/ja/sdk/unity/onboard/session-management.mdx @@ -1,5 +1,5 @@ --- -title: Unity セッション管理 — Sequence ドキュメント +title: セッション管理 --- Sequence API でユーザー認証しセッションを確立した後は、セッション管理のためのさまざまなメソッドが利用できます。 diff --git a/ja/sdk/unity/power/advanced/contracts.mdx b/ja/sdk/unity/power/advanced/contracts.mdx index 2a2a8742..d0db2d05 100644 --- a/ja/sdk/unity/power/advanced/contracts.mdx +++ b/ja/sdk/unity/power/advanced/contracts.mdx @@ -112,6 +112,19 @@ var arg = new Tuple(wallet, amount, data); ### その他の型 Solidityの`string`や`bool`などの基本的なデータ型は、C#でも同じデータ型を使用できます。 +### 返却型 +スマートコントラクトからデータを読み取り、`Contract.SendQuery()` 関数を使用する場合、`string`、`BigInteger`、`bool` などの単純な戻り値型には TType をそのまま使うことができます。構造体のような複雑な戻り値型の場合は、`object[]` を使用し、値を手動で C# の構造体にパースしてください。 + +```csharp +// Let's consider a struct with the following variables: SomeStruct { address value1; uint256 value2; } +object[] structValues = Contract.SendQuery("SomeFunction"); + +SomeStruct newStruct = new SomeStruct() { + Value1 = new Address(structValues[0].ToString()), + Value2 = BigInteger.Parse(structValues[1].ToString()) +} +``` + ## コントラクトのクエリ スマートコントラクトからデータを読み取る場合は、`SendQuery`メソッドを使ってコントラクトにクエリを送り、結果を型Tで受け取ります。 スマートコントラクトをクエリする例は以下の通りです。 diff --git a/ja/sdk/unity/quickstart.mdx b/ja/sdk/unity/quickstart.mdx index bffe9974..c52ff2b5 100644 --- a/ja/sdk/unity/quickstart.mdx +++ b/ja/sdk/unity/quickstart.mdx @@ -1,13 +1,11 @@ --- -title: Unity クイックスタート +title: クイックスタート description: Sequence Unity SDK のクイックスタートドキュメントです。 --- - Sequence Unity SDK の最新版を [OpenUPM](/sdk/unity/installation#openupm) からインストールするか、 - [Unity のパッケージマネージャー UI](/sdk/unity/installation#or-using-package-manager-ui) を利用し、 - 以下の Git URL を指定してください:`https://github.com/0xsequence/sequence-unity.git?path=/Packages/Sequence-Unity` + [OpenUPM](/sdk/unity/installation#openupm) から Sequence の Unity SDK の最新版をインストールするか、[Unity の Package Manager UI](/sdk/unity/installation#or-using-package-manager-ui) を利用して、以下の Git URL を使用してください: `https://github.com/0xsequence/sequence-unity.git?path=/Packages/Sequence-Unity` @@ -23,11 +21,15 @@ description: Sequence Unity SDK のクイックスタートドキュメントで - まず、メールのワンタイムパスワード(OTP)を使ってウォレットセッションを確立します。パッケージマネージャー UI から `Setup` サンプルをインポートすると、 - プロジェクトの `Resources/` ディレクトリに一式のボイラープレートが配置されます。 - [ログイン用ボイラープレート](/sdk/unity/bootstrap_game#login) を作成し、指定したメールアドレスにワンタイムパスワードを送信できるようにします。 + まず、ストレージからウォレットセッションが利用可能かどうかを確認してください。 - 最初の機能が統合できたら、Google、Apple、PlayFab などの[追加ログインプロバイダー](/sdk/unity/onboard/authentication/intro)にも対応できます。 + ```csharp + bool recovered = await EmbeddedWalletAdapter.GetInstance().TryRecoverWalletFromStorage(); + ``` + + もし `false` が返ってきた場合は、ユーザーにサインインを促してください。Package Manager UI から `Setup` サンプルをインポートすると、プロジェクトの `Resources/` ディレクトリに一連のボイラープレートが配置されます。[ログイン用ボイラープレート](/sdk/unity/bootstrap_game#login) を作成し、指定したメールアドレスにワンタイムパスワードを送信できるようにしましょう。 + + 最初の機能を統合できたら、[追加のログインプロバイダー](/sdk/unity/onboard/authentication/intro)(Google、Apple、PlayFabなど)も利用できます。 ```csharp BoilerplateFactory.OpenSequenceLoginWindow(parent); @@ -39,8 +41,8 @@ description: Sequence Unity SDK のクイックスタートドキュメントで - Sequence Unity SDK には、ゲーム開発をすぐに始められるように様々な[ボイラープレート](/sdk/unity/bootstrap_game)が用意されています。 - 設定が完了したら、プレイヤープロフィールやインベントリ、ゲーム内ショップを表示するプレハブを作成できます。 + SequenceのUnity SDKには、ゲームを素早く始めるためのさまざまな[ボイラープレート](/sdk/unity/bootstrap_game)が用意されています。 + 設定が完了したら、プレイヤープロフィールやインベントリ、ゲーム内ショップを表示するプレハブを作成できます。 [プレイヤープロフィールの統合方法](/sdk/unity/bootstrap_game#player-profile)もご覧ください。 ```csharp @@ -53,8 +55,8 @@ description: Sequence Unity SDK のクイックスタートドキュメントで - `EmbeddedWalletAdapter` を使えば、数行のコードで素早く統合を始めることができ、すぐに利用を開始できます。 - さらにカスタマイズしたい場合は、[ユーザー認証について](/sdk/unity/onboard/authentication/intro) や [トランザクション送信方法](/sdk/unity/power/write-to-blockchain) など、他のドキュメントもご覧ください。 + `EmbeddedWalletAdapter`を使えば、数行のコードで素早く統合を始められます。 + さらにカスタマイズしたい場合は、[ユーザー認証](/sdk/unity/onboard/authentication/intro)や[トランザクション送信方法](/sdk/unity/power/write-to-blockchain)など、他のドキュメントもご参照ください。 ```csharp EmbeddedWalletAdapter adapter = EmbeddedWalletAdapter.GetInstance(); diff --git a/ja/sdk/unity/setup.mdx b/ja/sdk/unity/setup.mdx index 110ff673..9f1b5a77 100644 --- a/ja/sdk/unity/setup.mdx +++ b/ja/sdk/unity/setup.mdx @@ -1,5 +1,5 @@ --- -title: Unity セットアップ +title: セットアップ description: Sequence インフラストラクチャスタックを利用した web3 ゲーム向け Unity SDK セットアップのドキュメントです。 --- diff --git a/sdk/unity/onboard/recovering-sessions.mdx b/sdk/unity/onboard/recovering-sessions.mdx index c3235c22..f65c68c8 100644 --- a/sdk/unity/onboard/recovering-sessions.mdx +++ b/sdk/unity/onboard/recovering-sessions.mdx @@ -13,23 +13,45 @@ If you enable `StoreSessionPrivateKeyInSecureStorage` in your `SequenceConfig` S See below the supported platforms and to learn about the platform's secure storage solution - it is important to understand the basics of how these systems work and think carefully about the security implications of storing private keys (or any secret for that matter) in persistent storage. -## iOS +## Integration + +You have two options to recover a wallet from storage. First is to use the `EmbeddedWalletAdapter` class. If this call succeeds, the `EmbeddedWalletAdapter` contains the Wallet instance. + +```csharp +bool recovered = await EmbeddedWalletAdapter.GetInstance().TryRecoverWalletFromStorage(); +``` + +Otherwise, use the underlying `SequenceLogin` class. + +```csharp +(bool storageEnabled, IWallet wallet) = await SequenceLogin.GetInstance().TryToRestoreSessionAsync(); +``` + +In both cases, you can listen to the `SequenceWallet.OnWalletCreated` event whenever a wallet was recovered from storage or created during the sign-in process. + +## Platform Details + +### Editor + +In the editor, we use PlayerPrefs for private key storage. You will also need to enable `EditorStoreSessionPrivateKeyInSecureStorage` in SequenceConfig in order to use secure storage and recover sessions from within the editor. This separate flag makes it easier for you to test both flows without modifying the behaviour of your builds. Secure storage in the editor is for development purposes only and should not be considered secure for long-term storage. + +### iOS On iOS, we leverage the [iOS Keychain](https://developer.apple.com/documentation/security/keychain_services?language=objc). -## MacOS +### MacOS On MacOS, we leverage the [MacOS Keychain](https://developer.apple.com/documentation/security/keychain_services?language=objc). -## Windows +### Windows On Windows PCs, we leverage the [Crypto: Next Generation - Data Protection API (CNG DPAPI)](https://learn.microsoft.com/en-us/windows/win32/seccng/cng-dpapi) -## Web +### Web On Web builds, we leverage [IndexedDB](https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API) via [PlayerPrefs](https://docs.unity3d.com/ScriptReference/PlayerPrefs.html). -## Android +### Android On Android builds, we leverage the [Android Keystore](https://developer.android.com/privacy-and-security/keystore). @@ -94,7 +116,7 @@ unityStreamingAssets=**STREAMING_ASSETS** android.enableR8=**MINIFY_WITH_R_EIGHT** ``` -### Troubleshooting +## Troubleshooting If you run into issues with secure storage or Google Sign-In on Android, go through the following troubleshooting steps. @@ -106,7 +128,3 @@ overwritten by any other plugin or the Android Plugin Resolver. and ensure this build runs fine on your device. - Compare your Unity project settings (AndroidManifest, gradle files, Android player settings) with our [sdk project.](https://github.com/0xsequence/sequence-unity) - **Additional Ideas:** Uninstall your app before installing a new build, change your url scheme or bundle id. - -## Editor - -In the editor, we use PlayerPrefs for private key storage. You will also need to enable 'EditorStoreSessionPrivateKeyInSecureStorage' in SequenceConfig in order to use secure storage and recover sessions from within the editor. This separate flag makes it easier for you to test both flows without modifying the behaviour of your builds. Secure storage in the editor is for development purposes only and should not be considered secure for long-term storage. diff --git a/sdk/unity/onboard/session-management.mdx b/sdk/unity/onboard/session-management.mdx index 63cf4916..734d102d 100644 --- a/sdk/unity/onboard/session-management.mdx +++ b/sdk/unity/onboard/session-management.mdx @@ -1,5 +1,5 @@ --- -title: Unity Session Management — Sequence Docs +title: Session Management --- Once you've authenticated your user with the Sequence APIs and established a session, there are a number of methods available to you to manage the session. diff --git a/sdk/unity/power/advanced/contracts.mdx b/sdk/unity/power/advanced/contracts.mdx index 5b64e09c..5845dd27 100644 --- a/sdk/unity/power/advanced/contracts.mdx +++ b/sdk/unity/power/advanced/contracts.mdx @@ -116,6 +116,21 @@ var arg = new Tuple(wallet, amount, data); For traditional data types in Solidity like `string` or `bool`, you can use the same data types in C#. +### Return Types + +When you read data from a smart contract and use the `Contract.SendQuery()` function, you can use the TType for +simple return types such as `string` `BigInteger` or `bool`. For complex return types like structs, use an `object[]` and manually parse the values into your C# Struct. + +```csharp +// Let's consider a struct with the following variables: SomeStruct { address value1; uint256 value2; } +object[] structValues = Contract.SendQuery("SomeFunction"); + +SomeStruct newStruct = new SomeStruct() { + Value1 = new Address(structValues[0].ToString()), + Value2 = BigInteger.Parse(structValues[1].ToString()) +} +``` + ## Querying Contracts To query a smart contract (read data from it), you'll use the `SendQuery` method to query the contract and return the result as type T (if possible). diff --git a/sdk/unity/quickstart.mdx b/sdk/unity/quickstart.mdx index dca00b70..66cf5c94 100644 --- a/sdk/unity/quickstart.mdx +++ b/sdk/unity/quickstart.mdx @@ -1,5 +1,5 @@ --- -title: "Unity Quickstart" +title: "Quickstart" description: Quickstart Documentation for Sequence's Unity SDK. --- @@ -21,7 +21,13 @@ and use the following Git URL `https://github.com/0xsequence/sequence-unity.git? Place this file in the root of a `Resources` folder. - Start by establishing a wallet session using an email OTP. Import the `Setup` Sample from the Package Manager UI + Start by checking if a wallet session is available from storage: + + ```csharp + bool recovered = await EmbeddedWalletAdapter.GetInstance().TryRecoverWalletFromStorage(); + ``` + + If that returns `false` you should ask the user to sign. Import the `Setup` Sample from the Package Manager UI which will place a set of boilerplates into your project in a `Resources/` directory. Create the [Login Boilerplate](/sdk/unity/bootstrap_game#login) to send a one-time password to the specified email address. @@ -37,9 +43,9 @@ and use the following Git URL `https://github.com/0xsequence/sequence-unity.git? -Sequence's Unity SDK includes a variety of [Boilerplates](/sdk/unity/bootstrap_game) to help you quickly start your game. -Once everything is configured, you can create prefabs to display an Player Profile, Inventory, or In-Game Shop. -Checkout [how to integrate a Player Profile.](/sdk/unity/bootstrap_game#player-profile) + Sequence's Unity SDK includes a variety of [Boilerplates](/sdk/unity/bootstrap_game) to help you quickly start your game. + Once everything is configured, you can create prefabs to display an Player Profile, Inventory, or In-Game Shop. + Checkout [how to integrate a Player Profile.](/sdk/unity/bootstrap_game#player-profile) ```csharp BoilerplateFactory.OpenSequencePlayerProfile(parent, wallet, chain); diff --git a/sdk/unity/setup.mdx b/sdk/unity/setup.mdx index 6265133d..72e0a953 100644 --- a/sdk/unity/setup.mdx +++ b/sdk/unity/setup.mdx @@ -1,5 +1,5 @@ --- -title: Unity Setup +title: Setup description: Documentation for Unity SDK setup for the Sequence infrastructure stack for web3 gaming. ---