Skip to content

Integrate with @phala/sdk

The official way to integrate Phat Contract is with the @phala/sdk. It's based on Polkadot's @polkadot/api and @polkadot/api-contract. We suggest you let @phala/sdk manage these packages, so you don't have to include them in your package.json.

Compatibility

The SDK works with Node 18.x and all modern browsers like Chrome, Edge, and Firefox. Check the Providers section for browser wallet extensions.

The SDK was also tested with Bun using HttpProvider.

Installation

npm
npm install --save @phala/sdk@beta

Quick Start

1. Set up the Client

To begin, configure your Client instance (formerly called the OnChainRegistry).

mainnet
import { getClient } from '@phala/sdk'
 
const client = await getClient({ transport: 'wss://api.phala.network/ws' }) 

2. Set up a Provider

Next, set up a provider. This is an additional layer that works with your client to handle the signing and sending of transactions.

You can use the SDK with any major Polkadot wallet extension for browsers. It also fits well with EVM wallets on the Phala blockchain, thanks to evm_account_mapping. Wallets like MetaMask, RobbyWallet, and SubWallet work with it.

KeyringPairProvider
import { KeyringPairProvider } from '@phala/sdk'
 
const suri = '//Alice'
const provider = await KeyringPairProvider.createFromSURI(client.api, suri)

3. Interact with Phala Contract

To integrate Phat Contract, you'll need two things: the contractId and the ABI json. Our support extends to both @polkadot/api-contract APIs and viem-like contract actions. Feel free to use the one that suits your needs best.

Contract Instance
import * as fs from 'node:fs'
import { getContract } from '@phala/sdk'
 
const contractId = '0x...'
const abi = fs.readFileSync('path/to/your/abi.json', 'utf-8')
const contract = await getContract({
  client,
  contractId,
  abi,
  provider,
})
 
//
// Pink Query
//
const { output } = await contract.q.system.getDriver({ args: ['JsDelegate'] })
 
//
// Pink Commands / Transactions
//
const result1 = await contract.exec.someMethod({ args: ['sayHi'], waitFinalized: true })
 
// OR with constom `waitFinalized` checker.
const result2 = await contract.exec.someMethod({
  args: ['sayHi'],
  waitFinalized: async () => {
     return (await contract.q.checkMethod()).output.isOk
  }
})