Integrate with @phala/sdk
@phala/sdk
is the official SDK to integrating with Phat Contract. It build on top of @polkadot/api
and @polkadot/api-contract
, but instead declare the @polkadot/*
packages in your packages.json
file directly, we recommended skip them and let the @phala/sdk
handle that.
Compatibility
The SDK supports Node 18.x and all modern browsers (Chrome, Edge, Firefox, etc). For browser wallet extensions support, please check the Providers section.
The SDK also paritical supports for the Bun runtime with HttpProvider
.
Installation
npm install --save @phala/sdk@beta
Quick Start
1. Set up the Client
Firstly, you need setup your the Client instance (it called OnChainRegistry
in previous version).
import { getClient } from '@phala/sdk'
const client = await getClient({ transport: 'wss://api.phala.network/ws' })
2. Set up a Provider
The next step is setup a provider, it's a layer on-top of the client to handling signing and sending transactions.
The SDK supports all major polkadot browser wallet extensions. Phala blockchain also has a pallet names evm_account_mapping
, so the SDK also supports EVM wallet as well. Currently MetaMask, RobbyWallet, SubWallet are supported.
import { KeyringPairProvider } from '@phala/sdk'
const suri = '//Alice'
const provider = await KeyringPairProvider.createFromSURI(client.api, suri)
3. Interact with Phala Contract
To integrate with Phat Contract, you need to know the contractId
and provides the ABI json. Alongside with @polkadot/api-contract
compatible API, we also supports the contract actions API design like viem. You can pick one to use.
import * as fs from 'node'
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
}
})