Skip to content

Deploy a Contract

To deploy a Phat Contract using our SDK, follow these steps:

  1. Check if the codeHash is in the cluster and upload the code if it’s not there.
  2. Create an instance of the Phat Contract.

Once deployed, take note of the contract address. You'll use it for all future interactions with the contract.

Upload Code

import * as fs from 'node:fs'
import { getClient, PinkCodePromise, KeyringPairProvider } from '@phala/sdk'
 
export const client = await getClient({ transport: 'wss://api.phala.network/ws' })
export const provider = await KeyringPairProvider.createFromSURI(client.api, '//Alice')
 
const source = fs.readFileSync('path/to/contract.contract', 'utf-8') 
const pinkCodePromise = new PinkCodePromise(client, source)
const isExists = await pinkCodePromise.hasExists()
if (!isExists) {
    const submittableResult = await pinkCodePromise.send({ provider })
    await submittableResult.waitFinalized()
}
const blueprint = pinkCodePromise.getBlueprint()
 
const result = await blueprint.send.new({ provider }, 'arg0', 'arg1')
await result.waitFinalized()
const contract = result.contract

Interact with a Phat Contract

Using a Phat Contract requires two key pieces of information: the contract's address and its ABI.

Below is an example of using a contract instance for interacting with a Phat Contract:

import * as fs from 'node:fs'
import { getClient, getContract, KeyringPairProvider } from '@phala/sdk'
 
const contractId = '0x...'
const abi = fs.readFileSync('path/to/your/abi.json', 'utf-8')
 
const client = await getClient({ transport: 'ws://api.phala.network/ws' })
const provider = await KeyringPairProvider.createFromSURI(client.api, '//Alice')
const contract = await getContract({
  client,
  contractId,
  abi,
  provider,
})

Or you can using the contract actions with HttpProvider:

import * as fs from 'node:fs'
import { getClient, getContract, KeyringPairProvider, sendPinkQuery, sendPinkCommand, estimateContract } from '@phala/sdk'
 
const contractId = '0x...' 
const abi = fs.readFileSync('path/to/your/abi.json', 'utf-8')
 
const client = await getClient({ transport: 'https://api.phala.network/ws' })
const provider = await KeyringPairProvider.createFromSURI(client.api, '//Alice')
 
// query
const callerAddress = await sendPinkQuery(client, {
    address: '0x...',
    provider,
    abi,
    functionName: 'getCaller',
    args: ['Hi Remark'],
})
 
// transaction
const contractKey = await client.getContractKeyOrFail(contractId)
const { request } = await estimateContract(client, {
    address: contractId,
    contractKey,
    abi,
    provider,
    functionName: 'setRemark',
    args: ['Hi Remark'],
})
await sendPinkCommand(client, request)