TypeScript SDK
The Supra L1 TypeScript SDK provides a convenient way to interact with and perform operations on Supra. It offers a set of utility functions, classes, and types to simplify the integration process and enhance developer productivity.
Install the TypeScript SDK
npm install supra-ts-sdk@devnetpnpm add supra-ts-sdk@devnet and yarn add supra-ts-sdk@devnet install the same version.
Requires Node.js 20 or later.
Each network has an npm dist-tag, devnet, testnet and mainnet, that points to the release matching that network.
The latest tag points to the same release as mainnet. npm install supra-ts-sdk installs latest. A release for a
node release candidate on Devnet is published under devnet only, as a prerelease (X.Y.Z-beta.N).
Import the Package
import { SupraAccount, SupraClient, Network, HexString } from 'supra-ts-sdk'SupraAccount, HexString, BCS, TxnBuilderTypes, and TypeTagParser are re-exported by supra-ts-sdk, so everything comes from this single entry point.
Networks
Network | Chain ID | Faucet |
|---|---|---|
Network.DEVNET | 50 | Yes |
Network.TESTNET | 6 | Yes |
Network.MAINNET | 8 | No |
const supra = new SupraClient({ network: Network.DEVNET })To use another node, pass its rpcUrl and chainId, for example
new SupraClient({ rpcUrl: 'http://localhost:27001', chainId: 255 }). Before its first signature a client reads the
chain ID of its node and throws SupraChainIdMismatchError before signing when it differs from the configured one.
Example
Initialize a new project
mkdir supra-quickstart && cd supra-quickstart
npm init -y
npm pkg set type=module
npm install --save-dev tsx
mkdir srctsx runs TypeScript files directly and needs no tsconfig.json. ts-node does not run with
TypeScript 7, so these steps do not use it. The example is an ES module, which is what npm pkg set type=module
selects, so it can use top-level await.
Install the TypeScript SDK
npm install supra-ts-sdk@devnetImport dependencies
import { SupraAccount, SupraClient, Network } from 'supra-ts-sdk'Initialize the SupraClient
The constructor is synchronous. Pass a predefined network and the chain ID and RPC URL are resolved for you:
Network.DEVNET is chain ID 50, Network.TESTNET is chain ID 6 and Network.MAINNET is chain ID 8. Create one client
and reuse it.
const supra = new SupraClient({ network: Network.DEVNET })To point at a custom node instead, pass rpcUrl and chainId directly:
const supra = new SupraClient({
rpcUrl: 'https://rpc-devnet.supra.com',
chainId: 50,
})Initialize a SupraAccount
const senderAccount = new SupraAccount()
console.log('Sender: ', senderAccount.address().toString())This generates a new account on every run and does not store its private key. To keep an account, see Create Supra Accounts.
Fund the account with the faucet
The faucet is available on Devnet and Testnet. The faucet call returns the hash of the funding transaction before the
transaction executes. waitForTransaction returns once the transaction has a final status.
const faucet = await supra.faucet.fundAccountWithFaucet({
accountAddress: senderAccount.address(),
})
await supra.transaction.waitForTransaction({ transactionHash: faucet.hash })fundAccountWithFaucet throws SupraFaucetUnavailableError when the faucet has no free account at that moment; call it
again after a short wait. The faucet limits what each account and IP address can request; see Faucet.
Create the receiver address
const receiverAddress = new SupraAccount().address()Transfer supra to the receiver address
Important: When sending to a newly generated address, see Sending Tokens to New Accounts for recipient initialization behavior.
// To Transfer Supra Coin From Sender To Receiver
const txResData = await supra.coin.transferSupraCoin({
senderAccount,
receiverAccountAddress: receiverAddress,
amount: 100000000n,
optionalTransactionArgs: {
enableTransactionWaitAndSimulationArgs: {
enableWaitForTransaction: true,
enableTransactionSimulation: true,
},
},
})
console.log('Transfer SupraCoin TxRes: ', txResData)The helper estimates the max gas, takes the sequence number from the client’s counter and checks the chain ID of the
node before it signs. With enableTransactionSimulation: true, a simulation that does not succeed throws
SupraSimulationFailedError and nothing is submitted. With enableWaitForTransaction: true, a transaction that ends
with status Fail or Invalid throws SupraTransactionFailedError.
Full quickstart code
quickstart.ts
import { SupraAccount, SupraClient, Network } from "supra-ts-sdk";
// The client is synchronous to construct.
// Network.DEVNET resolves the chain ID (50) and RPC URL for you.
const supra = new SupraClient({ network: Network.DEVNET });
// Generate a new SupraAccount.
const senderAccount = new SupraAccount();
console.log("Sender: ", senderAccount.address().toString());
// Fund the sender account with the faucet. The faucet answers before its
// transaction executes, so wait for the transaction.
const faucet = await supra.faucet.fundAccountWithFaucet({
accountAddress: senderAccount.address(),
});
await supra.transaction.waitForTransaction({ transactionHash: faucet.hash });
// Create the receiver address
const receiverAddress = new SupraAccount().address();
// To Transfer Supra Coin From Sender To Receiver
const txResData = await supra.coin.transferSupraCoin({
senderAccount,
receiverAccountAddress: receiverAddress,
amount: 100000000n,
optionalTransactionArgs: {
enableTransactionWaitAndSimulationArgs: {
enableWaitForTransaction: true,
enableTransactionSimulation: true,
},
},
});
// Output the transaction data
console.log("Transfer SupraCoin TxRes: ", txResData);Execute the code: npx tsx src/quickstart.ts
Transfer SUPRA as a fungible asset
An account holds SUPRA as a coin, in its CoinStore, as a fungible asset, in its primary fungible store, or in both.
On a chain created from the supra_node_v12.0.0 genesis (Devnet), SUPRA is in the primary fungible store, including
the SUPRA from the faucet. On Testnet and Mainnet (v11.7), SUPRA can be in either form: SUPRA that an account received
as a coin is in its CoinStore.
getAccountSupraBalance returns { total, coin, fungibleAsset } in quants: the CoinStore part, the primary store
part and their total. getAccountSupraCoinBalance returns the total. transferSupraCoin moves SUPRA held in either
form. The fungible asset transfers move only the balance of the primary store, and transferSupraFungibleAsset throws
SupraInsufficientFungibleAssetBalanceError without submitting a transaction when that balance is below amount.
migrateCoinToFungibleStore moves the balance of a coin type (SUPRA by default) from its CoinStore to the primary
store; on a chain whose SUPRA is already in primary stores, coin is 0n and there is nothing to migrate.
The code below runs on every network. It migrates only when the account holds a coin balance, so on Devnet it goes straight to the transfer.
import { SupraAccount, SupraClient, Network } from 'supra-ts-sdk'
const supra = new SupraClient({ network: Network.DEVNET })
const senderAccount = new SupraAccount()
const waitForCommit = { enableTransactionWaitAndSimulationArgs: { enableWaitForTransaction: true } }
const faucet = await supra.faucet.fundAccountWithFaucet({ accountAddress: senderAccount.address() })
await supra.transaction.waitForTransaction({ transactionHash: faucet.hash })
const { coin } = await supra.account.getAccountSupraBalance({ accountAddress: senderAccount.address() })
if (coin > 0n) {
await supra.fungibleAsset.migrateCoinToFungibleStore({
senderAccount,
optionalTransactionArgs: waitForCommit,
})
}
await supra.fungibleAsset.transferSupraFungibleAsset({
senderAccount,
receiverAccountAddress: new SupraAccount().address(),
amount: 10_000n,
optionalTransactionArgs: waitForCommit,
})Gas price
Each transaction has a max gas, a gas unit price (in quants) and an expiration time. The gas unit price of a transaction is, in this order:
- the
gasUnitPriceof the call, set inoptionalTransactionPayloadArgs; - the
gasUnitPriceof the client, set in theSupraClientconfiguration; - the node’s estimate,
max(median gas price, minimum gas price)of the node’s gas price estimate.supra.getEstimatedGasUnitPrice()returns it.
By default, then, each transaction reads the node’s estimate when it is built. A price set by the call or the client is used as given and makes no request. A setting of the call replaces the setting of the client.
import { SupraAccount, SupraClient, Network } from 'supra-ts-sdk'
// A gas unit price for every transaction of the client
const supra = new SupraClient({ network: Network.DEVNET, gasUnitPrice: 200_000n })
const senderAccount = new SupraAccount() // a funded account
// A gas unit price for one call; it replaces the client's
await supra.coin.transferSupraCoin({
senderAccount,
receiverAccountAddress: new SupraAccount().address(),
amount: 100n,
optionalTransactionArgs: {
optionalTransactionPayloadArgs: { gasUnitPrice: 300_000n },
},
})
// The estimate that a transaction carries when nothing is set
const estimate = await supra.getEstimatedGasUnitPrice()The builders that make no request (rawTxnObject, scriptRawTxnObject, automationRegistrationRawTxnObject,
multisigRawTxnObject and multisigProposalTxRawTxnObject) cannot read the estimate. Without a gas unit price on the
call or the client they throw a RangeError before building, so pass one, for example the value of
supra.getEstimatedGasUnitPrice().
When the price is below the node’s minimum, the node refuses the transaction and the SDK throws
SupraGasUnitPriceBelowMinimumError from the submission or from the simulation. It has the fields gasUnitPrice (the
price that was sent) and minimumGasUnitPrice (the node’s minimum, undefined when reading it failed), and the
original error is its cause. The SDK does not send the transaction again and does not raise the price.
Transaction hashes and unknown outcomes
The SDK derives the hash of a transaction from the signed transaction before it submits it. If the submission request
times out, fails before the node answers, or is answered with a 5xx status other than 503, the node may have accepted
the transaction. The call then throws SupraSubmissionOutcomeUnknownError, which carries hash, sender,
sequenceNumber, expirationTimestampSecs and the error of the request as cause.
Do not send the transaction again. Wait for the hash first; the transaction can commit until the chain’s time reaches
expirationTimestampSecs.
import { SupraAccount, SupraClient, Network, SupraSubmissionOutcomeUnknownError } from 'supra-ts-sdk'
const supra = new SupraClient({ network: Network.DEVNET })
const senderAccount = new SupraAccount() // a funded account
try {
await supra.coin.transferSupraCoin({
senderAccount,
receiverAccountAddress: new SupraAccount().address(),
amount: 100n,
})
} catch (error) {
if (!(error instanceof SupraSubmissionOutcomeUnknownError)) {
throw error
}
// The node may have accepted the transaction: wait for its final status.
const transaction = await supra.transaction.waitForTransaction({ transactionHash: error.hash })
console.log(`${error.hash}: ${transaction.status}`)
}With enableWaitForTransaction: true, the call waits for the derived hash itself. It returns the transaction when that
reaches a final status, and throws SupraSubmissionOutcomeUnknownError only when the wait ends without one; the wait’s
SupraTransactionTimeoutError is then its waitError. A 4xx status or 503 means that the node did not accept the
transaction; the SDK throws it as a SupraAPIError, with two exceptions. A gas unit price below the node’s minimum is
thrown as SupraGasUnitPriceBelowMinimumError. A 400 that says the node’s pool already holds the submitted transaction,
for example when the same signed transaction is submitted twice, is handled as an accepted submission when a v12 node
names the transaction (transaction <hash> is already pending). A v11.7 node answers Already scheduled: the SDK reads
the transaction by hash once, handles Success and Fail as accepted, and throws SupraSubmissionOutcomeUnknownError
for a Pending or unreadable transaction. The transaction commits at most once.
A transaction expires txExpirySecs seconds after the client’s clock, 60 by default, unless the call sets
txExpiryTime. The node refuses an expiration time more than its maximum time to live (getTransactionParameters())
after its own clock.
supra.transaction.deriveTransactionHash({ signedTransaction }) returns the same hash for a signed transaction that you
submit yourself. Sign and Submit Transactions
covers signing with an external key, sponsored and multi-agent transactions, and the sequence numbers a client holds
after an unknown outcome.
Fixed-point arguments
An entry or view function parameter of type 0x1::fixed_point32::FixedPoint32 or 0x1::fixed_point64::FixedPoint64
takes the raw value of the struct: the u64 of a FixedPoint32 (the number times 2^32) or the u128 of a
FixedPoint64 (the number times 2^64), as a bigint or a decimal string. vector<FixedPoint32> and
Option<FixedPoint64> work the same way. A view function returns such a value as { value: bigint }.
const oneAndAHalf = 3n << 31n // 1.5 as a FixedPoint32
const rawTxn = await supra.transaction.build.simple({
senderAddress: senderAccount.address(),
senderSequenceNumber: sequenceNumber,
function: `${moduleAddress}::prices::set_rate`, // set_rate(account: &signer, rate: FixedPoint32)
functionTypeArgs: [],
functionArgs: [oneAndAHalf],
})
const [rate] = await supra.methods.view<[{ value: bigint }]>({
function: `${moduleAddress}::prices::rate`,
functionArguments: [],
})
console.log(rate.value) // 6442450944nmoduleAddress and sequenceNumber stand for the address of the module that declares prices and the sender’s current
sequence number.
Automation tasks
The node runs the entry function of an automation task as automated transactions of the task’s owner, from the
automation cycle after its registration until the task expires. Build the registration with
supra.transaction.build.automationRegistrationRawTxnObject.
Without automationTaskType and automationPriority, the registration carries version 1 parameters, as in earlier
releases. With either of them it carries version 2 parameters: automationTaskType is 'User' or 'System', and
automationPriority is a u64 bigint. Nodes that run v11.7 and v12 accept both. A task registered without a
priority gets its task index as its priority. automationPriority is for 'System' tasks only: the automation registry
aborts a user task that carries a priority (EUSER_TASK_PRIORITY_NOT_SUPPORTED), so the builder throws a RangeError
when automationPriority is given with automationTaskType: 'User' or with no task type. Only accounts that the Supra
framework has authorised can register 'System' tasks, with or without a priority.
import { BCS, Network, SupraAccount, SupraClient } from 'supra-ts-sdk'
const supra = new SupraClient({ network: Network.DEVNET })
const owner = new SupraAccount() // a funded account
const receiver = new SupraAccount().address()
const gasUnitPrice = await supra.getEstimatedGasUnitPrice()
const registration = supra.transaction.build.automationRegistrationRawTxnObject({
senderAddress: owner.address(),
senderSequenceNumber: (await supra.getAccountInfo({ accountAddress: owner.address() })).sequence_number,
function: '0x1::supra_account::transfer',
functionTypeArgs: [],
functionArgs: [receiver.toUint8Array(), BCS.bcsSerializeUint64(1_000n)],
automationMaxGasAmount: 500n,
automationGasPriceCap: 2n * gasUnitPrice,
automationFeeCapForEpoch: 1_000_000_000n,
automationExpirationTimestampSecs: BigInt(Math.floor(Date.now() / 1000) + 60 * 60),
automationAuxData: [],
automationTaskType: 'User',
optionalTransactionPayloadArgs: { gasUnitPrice },
})
const registered = await registration.submitTransaction({
senderAccount: owner,
enableTransactionWaitAndSimulationArgs: { enableWaitForTransaction: true },
})The registration emits a 0x1::automation_registry::AutomationTaskMetaData event whose task_index identifies the
task. To register with version 1 parameters, leave out automationTaskType and automationPriority.
automation.cancelAutomationTask calls 0x1::automation_registry::cancel_task: a task that has not run yet is removed,
and an active task runs until the end of the current automation cycle. automation.stopAutomationTasks calls
0x1::automation_registry::stop_tasks and removes tasks at once. Both act on the sender’s user automation tasks, take
the sequence number from the client’s counter and estimate the max gas like the transfer helpers. Refunds follow the
rules of the automation registry.
await supra.automation.cancelAutomationTask({ senderAccount: owner, taskIndex: 42n })
await supra.automation.stopAutomationTasks({ senderAccount: owner, taskIndexes: [43n, 44n] })For the automation service itself, see Automation.
Read methods of v12 nodes
Nodes from supra_node_v12.0.0 serve routes that v11.7 nodes do not. Devnet runs v12.0.0-rc7 today; Testnet and
Mainnet run v11.7.2. The methods marked “v12” in the table are previews: the node API they call runs on Devnet as release
candidates and can change between them, so a 2.x release of the SDK can change or remove these methods until
supra_node_v12.0.0 reaches Testnet. getNodeVersion and getPrimaryStoreAddress work on every node.
getAccountFaTransactions is served by every node, and returns an empty page for SUPRA held in a primary store when it
is given an account address instead of the store’s address.
| Method | Node | Returns | On a v11.7 node |
|---|---|---|---|
supra.getNodeVersion() | any | { version, release, branch, commit_hash, build_time, build_env } | release is undefined |
supra.account.getPrimaryStoreAddress | any | The address of an account’s primary fungible store (SUPRA by default) | Works |
supra.account.getAccountFaTransactions | any | One page of the transactions that withdrew from or deposited to one fungible store | Works |
supra.account.getAccountHistory | v12 | One page of every finalized transaction that concerns an account, with the categories it matched | SupraRouteUnsupportedError |
supra.transaction.getSettlements, getSettlement | v12 | The cross-VM crossings of native SUPRA that an address is party to; every stage of one crossing | SupraRouteUnsupportedError |
supra.fungibleAsset.getNativeSupply | v12 | The accounting of native SUPRA across the two VMs as of one height | SupraRouteUnsupportedError |
supra.transaction.getTransactionsByHashes | v12 | The transactions of up to 100 hashes, in request order, with transaction: null for unknown ones | SupraRouteUnsupportedError |
supra.methods.viewBatch | v12 | The results of several view functions executed against one snapshot of Move state | SupraRouteUnsupportedError |
SupraRouteUnsupportedError extends SupraNotFoundError. The history of an account also lists SUPRA transfers between
primary fungible stores and SUPRA held in a CoinStore, once per transaction, but omits automated transactions. Paginated
methods return { response, cursor }; pass cursor back unchanged until it is undefined, since a page can be empty
and still carry a cursor. Track an Account’s Transactions
compares the feeds of an account and reads one to its end.
import { Network, SupraAccount, SupraClient, SupraRouteUnsupportedError } from 'supra-ts-sdk'
const supra = new SupraClient({ network: Network.DEVNET })
const account = new SupraAccount()
const faucet = await supra.faucet.fundAccountWithFaucet({ accountAddress: account.address() })
await supra.transaction.waitForTransaction({ transactionHash: faucet.hash })
// `release` is undefined on a v11.7 node.
const { release } = await supra.getNodeVersion()
console.log(release)
try {
const page = await supra.account.getAccountHistory({
accountAddress: account.address(),
options: { categories: ['sent', 'fa'], count: 50 },
})
for (const { categories, transaction } of page.response) {
console.log(transaction.hash, categories)
}
// Pass page.cursor as options.start to read the next page; it is undefined after the last one.
const supply = await supra.fungibleAsset.getNativeSupply()
// The `*_quants` figures are bigint, which JSON.stringify cannot serialize without a replacer.
console.log(JSON.stringify(supply, (_key, v) => (typeof v === 'bigint' ? v.toString() : v), 2))
} catch (error) {
if (!(error instanceof SupraRouteUnsupportedError)) {
throw error
}
console.log(`${error.method} needs a node from ${error.minimumNodeRelease}`)
}Blocks that a v12 node returns (execution_statistics.evm_base_fee_per_gas), settlement amounts, the burn_amount of
settlement transactions and the *_quants figures of getNativeSupply are bigint. JSON.stringify throws
TypeError: Do not know how to serialize a BigInt for an object that holds one, so display or store such an object with
the replacer above.
The API reference documents the arguments and results of each method, and the SDK README has examples of the others.
API reference
The API reference documents every exported class, function and type of the SDK.
Handle errors
Every error the SDK raises on its own behalf extends SupraError. The classes are listed in the
SDK README ; the node’s answers
extend SupraAPIError, whose status is the HTTP status and whose major_status names the Move VM status the message
reports.
import {
SupraAPIError,
SupraAccount,
SupraClient,
Network,
SupraRateLimitError,
SupraTimeoutError,
SupraTransactionFailedError,
} from 'supra-ts-sdk'
const supra = new SupraClient({ network: Network.DEVNET })
const senderAccount = new SupraAccount() // a funded account
try {
await supra.coin.transferSupraCoin({
senderAccount,
receiverAccountAddress: new SupraAccount().address(),
amount: 100n,
optionalTransactionArgs: { enableTransactionWaitAndSimulationArgs: { enableWaitForTransaction: true } },
})
} catch (error) {
if (error instanceof SupraTransactionFailedError) {
console.log(`${error.hash} ended with ${error.status}: ${error.vm_status}`)
} else if (error instanceof SupraRateLimitError) {
console.log(`Try again in ${error.retryAfterSeconds} seconds`)
} else if (error instanceof SupraTimeoutError) {
console.log(`No answer within ${error.timeoutMs} ms`)
} else if (error instanceof SupraAPIError) {
console.log(error.status, error.message, error.major_status)
} else {
throw error
}
}