Portal Gaming Typescript SDK Documentation

The Portal Gaming SDK provides access to a wide range of features, allowing you to integrate your game with key blockchain functionality. This documentation will guide you through the installation, initialization, and usage of the SDK.

Installation

Prerequisites

  • Node Version: 20 or later (Active LTS version).
  • Package Manager: npm or yarn.

Installing Node.js

We recommend using Node Version Manager (nvm) to install and manage Node.js versions.

  1. Install nvm by following the official instructions.
  2. Install the latest LTS version of Node.js.
nvm install --lts

Installing the SDK

Run one of the following commands in your project root directory:

# Using npm
npm install -D @portalgaming/sdk typescript ts-node

# Using yarn
yarn add -D @portalgaming/sdk typescript ts-node

Quickstart

Initialization

To use the Portal Gaming SDK, you need to initialize it with an IdentityConfiguration instance. This configuration is shared across all SDK modules.

import { id } from '@portalgaming/sdk';

const baseConfig = {
  clientId: 'YOUR_PUBLISHABLE_KEY', // Replace with your Publishable Key from the Portal Gaming Hub
};

const identity = new id.Identity({
  baseConfig,
});

Authentication

The Portal Gaming SDK provides several methods for user authentication:

Standard Authentication

Use the authenticate method to initiate the standard authentication flow:

async function authenticateUser(options?: { useCachedSession: boolean }) {
  const userProfile = await identity.authenticate(options);
  if (userProfile) {
    console.log('User authenticated:', userProfile);
  } else {
    console.log('User not authenticated');
  }
}

Parameters:

  • options (optional): An object with the following property:
    • useCachedSession (boolean): If true, and no active session exists, the user will not be prompted to log in, and the Promise will resolve with a null value.

Device Flow Authentication

For devices that don't have a web browser, you can use the device flow:

async function authenticateWithDeviceFlow() {
  const deviceResponse = await identity.authenticateWithDeviceFlow();
  console.log('Please visit this URL on another device:', deviceResponse.verificationUri);
  console.log('And enter this code:', deviceResponse.userCode);

  const userProfile = await identity.authenticateWithDeviceFlowCallback(
    deviceResponse.deviceCode,
    deviceResponse.interval,
    deviceResponse.expiresIn * 1000
  );
  console.log('User authenticated:', userProfile);
}

Parameters for authenticateWithDeviceFlowCallback:

  • deviceCode (string): The device code received from the initial device flow request.
  • interval (number): The polling interval in seconds.
  • timeoutMs (number, optional): The timeout in milliseconds for the authentication process.

PKCE Flow Authentication

For enhanced security in public clients, use the PKCE (Proof Key for Code Exchange) flow:

function initiatePKCEAuth() {
  const authUrl = identity.authenticateWithPKCEFlow();
  // Redirect the user to authUrl
}

async function handlePKCECallback(authorizationCode: string, state: string) {
  const userProfile = await identity.authenticateWithPKCEFlowCallback(authorizationCode, state);
  console.log('User authenticated:', userProfile);
}

Parameters for authenticateWithPKCEFlowCallback:

  • authorizationCode (string): The authorization code received from the auth server.
  • state (string): The state parameter for CSRF protection.

Logging out

To log the user out:

async function logoutUser() {
  await identity.logout();
  console.log('User logged out');
}

Onchain execution

To execute a transaction on the blockchain:

async function executeTransaction(
  chainId: number,
  contractId: string,
  policyId: string,
  functionName: string,
  functionArgs: string[]
) {
  try {
    const transactionHash = await identity.executeTransaction(
      chainId,
      contractId,
      policyId,
      functionName,
      functionArgs
    );
    console.log('Transaction executed:', transactionHash);
    return transactionHash;
  } catch (error) {
    console.error('Transaction error:', error);
    throw error;
  }
}

// Example usage:
executeTransaction(1, '0x1234...', 'policy123', 'transfer', ['0xabcd...', '100']);

Parameters:

  • chainId (number): The ID of the blockchain network where the transaction will be executed.
  • contractId (string): The address of the smart contract to interact with.
  • policyId (string): The ID of the policy governing this transaction.
  • functionName (string): The name of the function to call on the smart contract.
  • functionArgs (string[]): An array of arguments to pass to the function.

Requesting Wallet Session Key

Here's how to use the requestWalletSessionKey method:

async function requestWalletSession(
  chainId: number,
  policyId?: string,
  whitelistedContracts?: string[],
  limit?: number
) {
  try {
    await identity.requestWalletSessionKey(chainId, policyId, whitelistedContracts, limit);
    console.log('Wallet session key requested successfully');
  } catch (error) {
    console.error('Error requesting wallet session key:', error);
  }
}

// Example usage:
requestWalletSession(
  1, // chainId for Ethereum mainnet
  'policy123', // optional policy ID
  ['0x1234...', '0x5678...'], // optional whitelisted contract addresses
  10 // optional transaction limit
);

Parameters:

  • chainId (required): The ID of the blockchain network you want to interact with.
  • policyId (optional): A specific policy ID to associate with this session key.
  • whitelistedContracts (optional): An array of contract addresses that are allowed to be interacted with using this session key.
  • limit (optional): The maximum number of transactions that can be performed with this session key.

Code splitting

The Portal Gaming SDK supports code splitting, which allows you to import only the modules you need. This can significantly reduce the bundle size in web applications.

Requirements for Code Splitting

  • TypeScript version 5 or higher.
  • Ensure your code editor and project use the same TypeScript version.
  • TypeScript configuration:
    • Set compilerOptions.moduleResolution to bundler in your tsconfig.json.

Troubleshooting

If you encounter issues during installation or usage, try the following steps:

  1. Ensure you have the latest SDK version:

    # Using npm
    rm -Rf node_modules
    npm cache clean --force
    npm install
    
    # Using yarn
    rm -rf node_modules
    yarn cache clean
    yarn install
    
  2. Verify that your Node.js version is 20 or later:

    node --version
    
  3. Check that your TypeScript configuration is correct for code splitting.

  4. If problems persist, please contact our support team or open an issue in our GitHub repository.


What’s Next