// PLUS Game SDK for Unity (preview v0.1.0) // https://plusmain.net/developers/games // // All platforms : GetBalance (JSON-RPC), Checkout (opens PLUS Pay in the browser and polls the invoice). // WebGL builds : Connect, SignIn, SendPlus and an in-page Checkout through the PLUS web SDK (plus-game-sdk.js). // // Never put your PLUS Pay API key in the game client: create invoices on your server and grant items // only when your server receives the signed "invoice.paid" webhook. using System; using System.Collections.Generic; using System.Globalization; using System.Numerics; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; using UnityEngine; using UnityEngine.Networking; namespace PlusMainnet { public static class PlusGame { public const string Version = "0.1.0"; public const long ChainId = 88088; public static string BaseUrl = "https://plusmain.net"; public static string RpcUrl = "https://rpc.plusmain.net"; // ---------- public types ---------- [Serializable] public class Session { public string address; public string token; public long expiresAt; } [Serializable] public class CheckoutResult { public string status; public string id; public string txHash; } public class PlusGameException : Exception { public readonly string Code; public PlusGameException(string code, string message) : base(message) { Code = code; } } /// True in WebGL builds, where wallet features of the web SDK are available. public static bool IsWebGL => Application.platform == RuntimePlatform.WebGLPlayer; // ---------- all platforms ---------- /// PLUS balance of an address as a decimal string (18 decimals), read from the PLUS RPC. public static async Task GetBalance(string address) { if (!IsAddress(address)) throw new PlusGameException("BAD_ADDRESS", "Invalid address."); var body = "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"eth_getBalance\",\"params\":[\"" + address + "\",\"latest\"]}"; var json = await Send(RpcUrl, "POST", body); var r = JsonUtility.FromJson(json); if (r == null || string.IsNullOrEmpty(r.result)) throw new PlusGameException("RPC_ERROR", "Could not read the balance."); return FromUnits(r.result); } /// /// Pay an invoice your SERVER created (POST /api/pay/invoice). WebGL: opens the checkout in the page. /// Other platforms: opens the PLUS Pay page in the system browser and waits for the invoice to be paid. /// Throws PlusGameException with Code EXPIRED, CLOSED or TIMEOUT. /// public static async Task Checkout(string invoiceId, int timeoutSeconds = 900) { var id = ParseInvoiceId(invoiceId); if (IsWebGL) return JsonUtility.FromJson(await CallWeb("checkout", "[\"" + id + "\"]")); Application.OpenURL(BaseUrl + "/pay/i/" + id); var deadline = DateTime.UtcNow.AddSeconds(timeoutSeconds); while (DateTime.UtcNow < deadline) { await Task.Delay(3000); InvoiceStatus s; try { s = await GetInvoice(id); } catch (PlusGameException) { continue; } // network blip: retry if (s.status == "paid") return new CheckoutResult { status = "paid", id = id, txHash = s.txHash }; if (s.status == "expired") throw new PlusGameException("EXPIRED", "The payment expired."); } throw new PlusGameException("TIMEOUT", "No payment was seen before the timeout."); } /// Public status of an invoice (pending / paid / expired). Your server should still rely on the webhook. public static async Task GetInvoice(string invoiceId) { var id = ParseInvoiceId(invoiceId); var json = await Send(BaseUrl + "/api/pay/invoice/" + id, "GET", null); var r = JsonUtility.FromJson(json); if (r == null || r.invoice == null || string.IsNullOrEmpty(r.invoice.status)) throw new PlusGameException("NOT_FOUND", "Invoice not found."); return r.invoice; } [Serializable] public class InvoiceStatus { public string id; public string status; public string txHash; public string asset; public string amount; } // ---------- WebGL only (browser wallet) ---------- /// Connect a browser wallet and switch it to PLUS Mainnet. Returns the address. public static async Task Connect() { RequireWebGL("Connect"); return JsonUtility.FromJson(await CallWeb("connect", "[]")).address; } /// Sign-In with PLUS (EIP-4361). Send session.token to your server and check it with GET /api/game/auth/session. public static async Task SignIn(string statement = null) { RequireWebGL("SignIn"); var args = statement == null ? "[]" : "[{\"statement\":" + JsonString(statement) + "}]"; return JsonUtility.FromJson(await CallWeb("signIn", args)); } /// Send PLUS from the connected wallet. Returns the transaction hash. public static async Task SendPlus(string to, string amount) { RequireWebGL("SendPlus"); if (!IsAddress(to)) throw new PlusGameException("BAD_ADDRESS", "Invalid recipient address."); var json = await CallWeb("sendPlus", "[" + JsonString(to) + "," + JsonString(amount) + "]"); return JsonUtility.FromJson(json).value; } // ---------- internals ---------- [Serializable] class RpcResult { public string result; } [Serializable] class InvoiceResponse { public InvoiceStatus invoice; } [Serializable] class AddressResult { public string address; } [Serializable] class ValueResult { public string value; } // plain (non-object) results from the web SDK [Serializable] class BridgeMessage { public int id; public bool ok; public string result; public string error; public string code; } static bool IsAddress(string a) => a != null && a.Length == 42 && a.StartsWith("0x") && IsHex(a.Substring(2)); static bool IsHex(string s) { foreach (var c in s) if (!Uri.IsHexDigit(c)) return false; return s.Length > 0; } static string ParseInvoiceId(string idOrUrl) { var s = (idOrUrl ?? "").Trim().TrimEnd('/'); var id = s.Length >= 16 ? s.Substring(s.Length - 16) : ""; if (!IsHex(id) || (s.Length > 16 && s[s.Length - 17] != '/')) throw new PlusGameException("BAD_INVOICE", "Pass the invoice id (16 hex characters) or its payment URL."); return id.ToLowerInvariant(); } /// 0x-hex wei to a decimal PLUS string without trailing zeros. public static string FromUnits(string hexWei) { var hex = hexWei.StartsWith("0x") ? hexWei.Substring(2) : hexWei; var wei = BigInteger.Parse("0" + (hex.Length == 0 ? "0" : hex), NumberStyles.HexNumber); var unit = BigInteger.Pow(10, 18); var whole = BigInteger.DivRem(wei, unit, out var frac); if (frac.IsZero) return whole.ToString(); return whole + "." + frac.ToString().PadLeft(18, '0').TrimEnd('0'); } static string JsonString(string s) { var sb = new StringBuilder("\""); foreach (var c in s ?? "") { if (c == '"' || c == '\\') sb.Append('\\').Append(c); else if (c < 0x20) sb.Append("\\u").Append(((int)c).ToString("x4")); else sb.Append(c); } return sb.Append('"').ToString(); } static Task Send(string url, string method, string jsonBody) { var tcs = new TaskCompletionSource(); var req = new UnityWebRequest(url, method) { downloadHandler = new DownloadHandlerBuffer(), timeout = 15 }; if (jsonBody != null) { req.uploadHandler = new UploadHandlerRaw(Encoding.UTF8.GetBytes(jsonBody)); req.SetRequestHeader("Content-Type", "application/json"); } req.SendWebRequest().completed += _ => { try { if (req.result == UnityWebRequest.Result.ConnectionError) tcs.SetException(new PlusGameException("NETWORK", req.error)); else if (req.responseCode >= 400 && req.responseCode != 404) tcs.SetException(new PlusGameException("HTTP_" + req.responseCode, req.downloadHandler.text)); else tcs.SetResult(req.downloadHandler.text); } finally { req.Dispose(); } }; return tcs.Task; } static void RequireWebGL(string what) { if (!IsWebGL) throw new PlusGameException("WEBGL_ONLY", what + " needs a browser wallet and works in WebGL builds only. On other platforms sign in on your web page or use Checkout."); } // WebGL bridge: one JS function, results come back through SendMessage to a hidden GameObject. #if UNITY_WEBGL && !UNITY_EDITOR [DllImport("__Internal")] static extern void PlusGame_Call(string objectName, int callId, string method, string argsJson, string baseUrl); #else static void PlusGame_Call(string objectName, int callId, string method, string argsJson, string baseUrl) => throw new PlusGameException("WEBGL_ONLY", "The web SDK bridge is available in WebGL builds only."); #endif static int nextId; static readonly Dictionary> pending = new Dictionary>(); static Task CallWeb(string method, string argsJson) { PlusGameBridge.Ensure(); var id = ++nextId; var tcs = new TaskCompletionSource(); pending[id] = tcs; PlusGame_Call(PlusGameBridge.ObjectName, id, method, argsJson, BaseUrl); return tcs.Task; } internal static void OnBridgeMessage(string json) { var m = JsonUtility.FromJson(json); if (m == null || !pending.TryGetValue(m.id, out var tcs)) return; pending.Remove(m.id); if (m.ok) tcs.SetResult(m.result ?? "{}"); else tcs.SetException(new PlusGameException(string.IsNullOrEmpty(m.code) ? "ERROR" : m.code, m.error ?? "Failed.")); } } /// Hidden GameObject that receives results from the WebGL bridge. Created automatically. public class PlusGameBridge : MonoBehaviour { public const string ObjectName = "PlusGameBridge"; static PlusGameBridge instance; internal static void Ensure() { if (instance != null) return; var go = new GameObject(ObjectName); instance = go.AddComponent(); DontDestroyOnLoad(go); } // Called from PlusGame.jslib with SendMessage(ObjectName, "OnResult", json) public void OnResult(string json) => PlusGame.OnBridgeMessage(json); } }