Building with SettleMint/SDK Developer Guide

Smart Contract Portal

Using the Smart Contract Portal in your SettleMint dApp

About

The SettleMint Smart Contract Portal SDK provides a seamless way to interact with the Smart Contract Portal Middleware API. It enables you to easily interact with your smart contracts using a REST or GraphQL API.

The SDK offers a type-safe interface for all Portal API operations, with comprehensive error handling and validation. It integrates smoothly with modern TypeScript applications while providing a simple and intuitive developer experience.

Examples

Deploy contract

/**
 * This example demonstrates how to deploy a contract.
 *
 * The process involves:
 * 1. Creating a portal client
 * 2. Deploying a forwarder contract
 * 3. Waiting for the forwarder contract deployment to be finalized
 * 4. Deploying a stablecoin factory contract
 * 5. Getting all contracts and filtering by ABI name
 *
 * This pattern is useful for applications that need to deploy smart contracts
 * in the SettleMint Portal, providing a way to track the progress of blockchain operations.
 */
import { loadEnv } from "@settlemint/sdk-utils/environment";
import { createLogger, requestLogger } from "@settlemint/sdk-utils/logging";
import { getAddress } from "viem";
import { createPortalClient } from "../portal.js"; // Replace this path with "@settlemint/sdk-portal"
import { waitForTransactionReceipt } from "../utils/wait-for-transaction-receipt.js";
import type { introspection } from "./schemas/portal-env.d.ts"; // Replace this path with the generated introspection type
 
const env = await loadEnv(false, false);
const logger = createLogger();
 
const { client: portalClient, graphql: portalGraphql } = createPortalClient<{
  introspection: introspection;
  disableMasking: true;
  scalars: {
    // Change unknown to the type you are using to store metadata
    JSON: unknown;
  };
}>(
  {
    instance: env.SETTLEMINT_PORTAL_GRAPHQL_ENDPOINT!,
    accessToken: env.SETTLEMINT_ACCESS_TOKEN!,
  },
  {
    fetch: requestLogger(logger, "portal", fetch) as typeof fetch,
  },
);
 
// Replace with the address of your private key which you use to deploy smart contracts
const FROM = getAddress("0x4B03331cF2db1497ec58CAa4AFD8b93611906960");
 
/**
 * Deploy a forwarder contract
 */
const deployForwarder = await portalClient.request(
  portalGraphql(`
    mutation DeployContractForwarder($from: String!) {
      DeployContractForwarder(from: $from, gasLimit: "0x3d0900") {
        transactionHash
      }
    }
  `),
  {
    from: FROM,
  },
);
 
/**
 * Wait for the forwarder contract deployment to be finalized
 */
const transaction = await waitForTransactionReceipt(deployForwarder.DeployContractForwarder?.transactionHash!, {
  portalGraphqlEndpoint: env.SETTLEMINT_PORTAL_GRAPHQL_ENDPOINT!,
  accessToken: env.SETTLEMINT_ACCESS_TOKEN!,
});
 
/**
 * Deploy a stablecoin factory contract
 */
const deployStableCoinFactory = await portalClient.request(
  portalGraphql(`
    mutation DeployContractStableCoinFactory($from: String!, $constructorArguments: DeployContractStableCoinFactoryInput!) {
      DeployContractStableCoinFactory(from: $from, constructorArguments: $constructorArguments, gasLimit: "0x3d0900") {
        transactionHash
      }
    }
  `),
  {
    from: FROM,
    constructorArguments: {
      forwarder: getAddress(transaction?.receipt.contractAddress!),
    },
  },
);
 
console.log(deployStableCoinFactory?.DeployContractStableCoinFactory?.transactionHash);
 
const contractAddresses = await portalClient.request(
  portalGraphql(`
    query GetContracts {
        getContracts {
            count
            records {
                address
                abiName
                createdAt
            }
        }
    }
  `),
);
// Print total count
console.log(`Total contracts: ${contractAddresses.getContracts?.count}`);
 
// Contracts for StableCoinFactory
console.log(contractAddresses.getContracts?.records.filter((record) => record.abiName === "StableCoinFactory"));

Get pending transactions

/**
 * This example demonstrates how to get the number of pending transactions.
 *
 * The process involves:
 * 1. Creating a portal client
 * 2. Making a GraphQL query to get the number of pending transactions
 *
 * This pattern is useful for applications that need to monitor the status of pending transactions
 * in the SettleMint Portal, providing a way to track the progress of blockchain operations.
 */
import { loadEnv } from "@settlemint/sdk-utils/environment";
import { createLogger, requestLogger } from "@settlemint/sdk-utils/logging";
import { createPortalClient } from "../portal.js"; // Replace this path with "@settlemint/sdk-portal"
import type { introspection } from "./schemas/portal-env.d.ts"; // Replace this path with the generated introspection type
 
const env = await loadEnv(false, false);
const logger = createLogger();
 
const { client: portalClient, graphql: portalGraphql } = createPortalClient<{
  introspection: introspection;
  disableMasking: true;
  scalars: {
    // Change unknown to the type you are using to store metadata
    JSON: unknown;
  };
}>(
  {
    instance: env.SETTLEMINT_PORTAL_GRAPHQL_ENDPOINT!,
    accessToken: env.SETTLEMINT_ACCESS_TOKEN!,
  },
  {
    fetch: requestLogger(logger, "portal", fetch) as typeof fetch,
  },
);
 
// Making GraphQL queries
const query = portalGraphql(`
  query GetPendingTransactions {
    getPendingTransactions {
      count
    }
  }
`);
 
const result = await portalClient.request(query);
console.log(`There are ${result.getPendingTransactions?.count} pending transactions`);

Send transaction using hd wallet

/**
 * This example demonstrates how to send a transaction using an HD wallet.
 *
 * The process involves:
 * 1. Creating a wallet for a user using the HD private key
 * 2. Setting up a pincode for wallet verification
 * 3. Handling the wallet verification challenge
 * 4. Sending a transaction to the blockchain
 *
 * This pattern is useful for applications that need to manage multiple user wallets
 * derived from a single HD wallet, providing a secure and scalable approach to
 * blockchain interactions in enterprise applications.
 */
import { loadEnv } from "@settlemint/sdk-utils/environment";
import { createLogger, requestLogger } from "@settlemint/sdk-utils/logging";
import type { Address } from "viem";
import { createPortalClient } from "../portal.js"; // Replace this path with "@settlemint/sdk-portal"
import { handleWalletVerificationChallenge } from "../utils/wallet-verification-challenge.js"; // Replace this path with "@settlemint/sdk-portal"
import type { introspection } from "./schemas/portal-env.js"; // Replace this path with the generated introspection type
 
const env = await loadEnv(false, false);
const logger = createLogger();
 
const { client: portalClient, graphql: portalGraphql } = createPortalClient<{
  introspection: introspection;
  disableMasking: true;
  scalars: {
    // Change unknown to the type you are using to store metadata
    JSON: unknown;
  };
}>(
  {
    instance: env.SETTLEMINT_PORTAL_GRAPHQL_ENDPOINT!,
    accessToken: env.SETTLEMINT_ACCESS_TOKEN!,
  },
  {
    fetch: requestLogger(logger, "portal", fetch) as typeof fetch,
  },
);
 
/**
 * First create a wallet using the HD private key, this needs to be done for every user that is using your app
 */
const wallet = await portalClient.request(
  portalGraphql(`
    mutation createUserWallet($keyVaultId: String!, $name: String!) {
      createWallet(keyVaultId: $keyVaultId, walletInfo: { name: $name }) {
        address
      }
    }
  `),
  {
    keyVaultId: env.SETTLEMINT_HD_PRIVATE_KEY!,
    name: "My Wallet",
  },
);
 
/**
 * Set a pincode for the wallet, this is used to verify the wallet when the user is sending a transaction to the chain
 */
const pincodeVerification = await portalClient.request(
  portalGraphql(`
    mutation setPinCode($address: String!, $pincode: String!) {
      createWalletVerification(
        userWalletAddress: $address
        verificationInfo: {pincode: {name: "PINCODE", pincode: $pincode}}
      ) {
        id
        name
        parameters
        verificationType
      }
    }
    `),
  {
    address: wallet.createWallet?.address!,
    pincode: "123456",
  },
);
 
/**
 * Generate a challenge response for the pincode verification
 */
const challengeResponse = await handleWalletVerificationChallenge({
  portalClient,
  portalGraphql,
  verificationId: pincodeVerification.createWalletVerification?.id!,
  userWalletAddress: wallet.createWallet?.address! as Address,
  code: "123456",
  verificationType: "pincode",
});
 
/**
 * Send a transaction to the chain
 * This is a sample of how to send a transaction to the chain using the portal client and the asset tokenization kit
 * The challenge response is generated using the handleWalletVerificationChallenge function, this is used to verifiy wallet access
 * @see https://github.com/settlemint/asset-tokenization-kit
 */
const result = await portalClient.request(
  portalGraphql(`
    mutation StableCoinFactoryCreate(
      $challengeResponse: String!
      $verificationId: String
      $address: String!
      $from: String!
      $input: StableCoinFactoryCreateInput!
    ) {
      StableCoinFactoryCreate(
        challengeResponse: $challengeResponse
        verificationId: $verificationId
        address: $address
        from: $from
        input: $input
      ) {
        transactionHash
      }
    }
  `),
  {
    challengeResponse: challengeResponse.challengeResponse,
    verificationId: pincodeVerification.createWalletVerification?.id!,
    address: "0x5e771e1417100000000000000000000000000004",
    from: wallet.createWallet?.address!,
    input: {
      name: "Test Coin",
      symbol: "TEST",
      decimals: 18,
      collateralLivenessSeconds: 3_600,
    },
  },
);
 
// Log the transaction hash
console.log("Transaction hash:", result.StableCoinFactoryCreate?.transactionHash);

API Reference

Functions

createPortalClient()

createPortalClient<Setup>(options, clientOptions?): object

Defined in: sdk/portal/src/portal.ts:71

Creates a Portal GraphQL client with the provided configuration.

Type Parameters
Type Parameter
Setup extends AbstractSetupSchema
Parameters
ParameterTypeDescription
options{ accessToken: string; cache?: "default" | "force-cache" | "no-cache" | "no-store" | "only-if-cached" | "reload"; instance: string; }Configuration options for the Portal client
options.accessTokenstring-
options.cache?"default" | "force-cache" | "no-cache" | "no-store" | "only-if-cached" | "reload"-
options.instance?string-
clientOptions?RequestConfigAdditional GraphQL client configuration options
Returns

object

An object containing the configured GraphQL client and graphql helper function

NameTypeDefined in
clientGraphQLClientsdk/portal/src/portal.ts:75
graphqlinitGraphQLTada<Setup>sdk/portal/src/portal.ts:76
Throws

If the provided options fail validation

Example
import { createPortalClient } from "@settlemint/sdk-portal";
import { loadEnv } from "@settlemint/sdk-utils/environment";
import { createLogger, requestLogger } from "@settlemint/sdk-utils/logging";
import type { introspection } from "@schemas/portal-env";
 
const env = await loadEnv(false, false);
const logger = createLogger();
 
const { client: portalClient, graphql: portalGraphql } = createPortalClient<{
  introspection: introspection;
  disableMasking: true;
  scalars: {
    // Change unknown to the type you are using to store metadata
    JSON: unknown;
  };
}>(
  {
    instance: env.SETTLEMINT_PORTAL_GRAPHQL_ENDPOINT!,
    accessToken: env.SETTLEMINT_ACCESS_TOKEN!,
  },
  {
    fetch: requestLogger(logger, "portal", fetch) as typeof fetch,
  },
);
 
// Making GraphQL queries
const query = portalGraphql(`
  query GetPendingTransactions {
    getPendingTransactions {
      count
    }
  }
`);
 
const result = await portalClient.request(query);

handleWalletVerificationChallenge()

handleWalletVerificationChallenge<Setup>(options): Promise<{ challengeResponse: string; verificationId?: string; }>

Defined in: sdk/portal/src/utils/wallet-verification-challenge.ts:106

Handles a wallet verification challenge by generating an appropriate response

Type Parameters
Type Parameter
Setup extends AbstractSetupSchema
Parameters
ParameterTypeDescription
optionsHandleWalletVerificationChallengeOptions<Setup>The options for handling the wallet verification challenge
Returns

Promise<{ challengeResponse: string; verificationId?: string; }>

Promise resolving to an object containing the challenge response and optionally the verification ID

Throws

If the challenge cannot be created or is invalid

Example
import { createPortalClient } from "@settlemint/sdk-portal";
import { handleWalletVerificationChallenge } from "@settlemint/sdk-portal";
 
const { client, graphql } = createPortalClient({
  instance: "https://portal.example.com/graphql",
  accessToken: "your-access-token"
});
 
const result = await handleWalletVerificationChallenge({
  portalClient: client,
  portalGraphql: graphql,
  verificationId: "verification-123",
  userWalletAddress: "0x123...",
  code: "123456",
  verificationType: "otp"
});

waitForTransactionReceipt()

waitForTransactionReceipt(transactionHash, options): Promise<Transaction>

Defined in: sdk/portal/src/utils/wait-for-transaction-receipt.ts:82

Waits for a blockchain transaction receipt by subscribing to transaction updates via GraphQL. This function polls until the transaction is confirmed or the timeout is reached.

Parameters
ParameterTypeDescription
transactionHashstringThe hash of the transaction to wait for
optionsWaitForTransactionReceiptOptionsConfiguration options for the waiting process
Returns

Promise<Transaction>

The transaction details including receipt information when the transaction is confirmed

Throws

Error if the transaction receipt cannot be retrieved within the specified timeout

Example
import { waitForTransactionReceipt } from "@settlemint/sdk-portal";
 
const transaction = await waitForTransactionReceipt("0x123...", {
  portalGraphqlEndpoint: "https://example.settlemint.com/graphql",
  accessToken: "your-access-token",
  timeout: 30000 // 30 seconds timeout
});

Interfaces

HandleWalletVerificationChallengeOptions<Setup>

Defined in: sdk/portal/src/utils/wallet-verification-challenge.ts:73

Options for handling a wallet verification challenge

Type Parameters
Type ParameterDescription
Setup extends AbstractSetupSchemaThe GraphQL schema setup type

Transaction

Defined in: sdk/portal/src/utils/wait-for-transaction-receipt.ts:25

Represents the structure of a blockchain transaction with its receipt


WaitForTransactionReceiptOptions

Defined in: sdk/portal/src/utils/wait-for-transaction-receipt.ts:58

Options for waiting for a transaction receipt

Type Aliases

ClientOptions

ClientOptions = object

Defined in: sdk/portal/src/portal.ts:24

Type representing the validated client options.

Type declaration
NameTypeDefault valueDefined in
accessTokenstringApplicationAccessTokenSchemasdk/portal/src/portal.ts:17
cache?"default" | "force-cache" | "no-cache" | "no-store" | "only-if-cached" | "reload"-sdk/portal/src/portal.ts:18
instancestringUrlOrPathSchemasdk/portal/src/portal.ts:16

RequestConfig

RequestConfig = ConstructorParameters<typeof GraphQLClient>[1]

Defined in: sdk/portal/src/portal.ts:10

Configuration options for the GraphQL client, excluding 'url' and 'exchanges'.

Variables

ClientOptionsSchema

const ClientOptionsSchema: ZodObject<ClientOptions>

Defined in: sdk/portal/src/portal.ts:15

Schema for validating Portal client configuration options.

Contributing

We welcome contributions from the community! Please check out our Contributing guide to learn how you can help improve the SettleMint SDK through bug reports, feature requests, documentation updates, or code contributions.

License

The SettleMint SDK is released under the FSL Software License. See the LICENSE file for more details.