Integrate
Read Ported markets, mint and redeem pTokens from a script or another contract, and handle pTokens as the ordinary ERC-20s they are. Everything here runs against the Issuer on Elysium.
Chain and addresses
- Network
- Elysium, chain id
99901, gas paid in HYPE. Kinetiq's RPC:https://rpc.elysium.kinetiq.xyz. - USDC
- 0xb47c4C…3F0B650xb47c4C8F73F009CC0C0d3f92B388d13E293F0B65 6 decimals. This is USDC bridged from HyperEVM through Elysium's canonical bridge.
- pGOLD
- 0x6a27c2…13a5750x6a27c2AfE7DB657cABAf82981C125E220313a575 perp index
10003(Hyperliquidxyz:GOLD), 18 decimals. - Multicall3
- 0xcA11bd…76CA110xcA11bde05977b3631167028862bE2a173976CA11 batch reads through it instead of one call per value.
- Quote API
https://ported-keeper-production.up.railway.app, described on Quote API.
Configure only the Issuer address. Read everything else from it: usdc(), priceSource(), and each market's token from market(perpIndex).token. That way your integration follows a change of price source or a new market without a code change. The full list of deployed contracts is on Contracts.
// ported.ts: chain, addresses, ABIs and clients shared by the examples below
import { createPublicClient, createWalletClient, defineChain, http, parseAbi, type Hex } from "viem"
import { privateKeyToAccount } from "viem/accounts"
export const elysium = defineChain({
id: 99901,
name: "Elysium",
nativeCurrency: { name: "HYPE", symbol: "HYPE", decimals: 18 },
rpcUrls: { default: { http: ["https://rpc.elysium.kinetiq.xyz"] } },
contracts: { multicall3: { address: "0xcA11bde05977b3631167028862bE2a173976CA11" } },
})
export const ISSUER = "0xAD6FF5B33F815EFCd3181e8Acbc210c38Ee2a268"
export const USDC = "0xb47c4C8F73F009CC0C0d3f92B388d13E293F0B65"
export const QUOTE_API = "https://ported-keeper-production.up.railway.app"
export const issuerAbi = parseAbi([
"struct MarketParams { bool mintEnabled; uint16 mintFeeBps; uint16 redeemFeeBps; uint16 maxMoveBps; uint16 maxMoveBpsPerMinute; uint256 maxDebt; uint256 maxMintPerHour; uint256 maxRedeemPerHour; }",
"struct Market { address token; uint64 launchedAt; MarketParams params; uint256 maxDebtNow; uint256 maxMintPerHourNow; uint128 refPrice; uint64 refAt; uint256 settlementPrice; }",
"function market(uint32 perpIndex) view returns (Market)",
"function marketCount() view returns (uint256)",
"function perpIndexes(uint256 i) view returns (uint32)",
"function priceSource() view returns (address)",
"function mintBudget() view returns (uint256)",
"function availableLiquidity() view returns (uint256)",
"function mintedLastHour(uint32 perpIndex) view returns (uint256)",
"function redeemedLastHour(uint32 perpIndex) view returns (uint256)",
"function allowedMoveBps(uint32 perpIndex) view returns (uint256)",
"function mintsPaused() view returns (bool)",
"function redeemsPaused() view returns (bool)",
"function mint(uint32 perpIndex, uint256 usdcIn, uint256 minTokensOut, address recipient, bytes priceData) returns (uint256 tokensOut)",
"function redeem(uint32 perpIndex, uint256 tokensIn, uint256 minUsdcOut, address recipient, bytes priceData) returns (uint256 usdcOut)",
"function payClaims(uint256 maxCount) returns (uint256 paid)",
"event Minted(uint32 indexed perpIndex, address indexed payer, address indexed recipient, uint256 usdcIn, uint256 fee, uint256 tokensOut, uint256 ask)",
"event Redeemed(uint32 indexed perpIndex, address indexed holder, address indexed recipient, uint256 tokensIn, uint256 fee, uint256 usdcOut, uint256 bid)",
"event RedeemQueued(uint256 indexed claimId, uint32 indexed perpIndex, address indexed recipient, uint256 amount)",
"event ClaimPaid(uint256 indexed claimId, address indexed recipient, uint256 amount)",
"error Slippage(uint256 out, uint256 minOut)",
"error FlowCapExceeded(uint256 usedAfter, uint256 cap)",
"error DebtCapExceeded(uint256 debtAfter, uint256 maxDebt)",
"error MintBudgetExceeded(uint256 amount, uint256 budget)",
"error PriceOutOfBand(uint256 price, uint256 refPrice, uint256 allowedBps)",
"error MintsArePaused()",
"error RedeemsArePaused()",
"error MintDisabled(uint32 perpIndex)",
"error QuoteTooOld(uint64 issuedAt)",
"error QuoteFromFuture(uint64 issuedAt)",
"error NotEnoughSignatures(uint256 valid, uint8 threshold)",
"error UnknownSigner(address signer)",
])
export const publicClient = createPublicClient({ chain: elysium, transport: http() })
export const walletClient = createWalletClient({
account: privateKeyToAccount(process.env.PRIVATE_KEY as Hex),
chain: elysium,
transport: http(),
})Units and formulas
| Quantity | Scale | Examples |
|---|---|---|
| USDC amounts | 6 decimals | usdcIn, usdcOut, maxDebt, maxMintPerHour, mintBudget, availableLiquidity() |
| pToken amounts | 18 decimals | tokensIn, tokensOut, totalSupply() |
| Prices | 18-decimal USDC per whole token | bid, ask, refPrice, settlementPrice |
| Rates | basis points (1 bp = 0.01%) | mintFeeBps, redeemFeeBps, maxMoveBps, allowedMoveBps() |
| Perp index | integer | Hyperliquid's index; for HIP-3 markets dex × 10000 + index, so 10003 is dex 1, market 3 |
The Issuer does the arithmetic below with integer division (rounding down). Reproduce it exactly and your minimum amounts will match what the contract computes for the same quote.
A worked example with the first market's fees of 10 bps on each side. Mint 1,000 USDC at an ask of 3,700: the fee is 1 USDC, and 999 / 3,700 = 0.27 pGOLD. Redeem those 0.27 pGOLD at a bid of 3,690: gross 996.30 USDC, fee 0.9963, paid 995.3037 USDC.
Reading a market
market(perpIndex) returns the whole state of a market in one struct. Markets are listed in perpIndexes(i) for i below marketCount().
| Field | Meaning |
|---|---|
token | The pToken's address. Minted and burnt only by the Issuer. |
launchedAt | When the market was created. Exposure per token starts at exactly one unit here and moves with funding after it. |
params.mintEnabled | Whether minting is open. A market starts closed until the owner configures it. |
params.mintFeeBps | Fee on mints, taken from the USDC paid in. At most 200 (2%, MAX_FEE_BPS). |
params.redeemFeeBps | Fee on redemptions, taken from the USDC paid out. At most 200. |
params.maxMoveBps | Width of the price band right after a price is accepted. At most 2,000 (20%). |
params.maxMoveBpsPerMinute | How much the band widens for every minute without an accepted price. At most 500. |
params.maxDebt | The owner's ceiling on the market's debt to holders (supply valued at the ask), in USDC. |
params.maxMintPerHour | The owner's ceiling on USDC paid in per hour. |
params.maxRedeemPerHour | USDC that can be paid out per hour. Set by the owner only. |
maxDebtNow | Debt limit in force, at most maxDebt. Adjusted by the risk manager to the market's liquidity on Hyperliquid. |
maxMintPerHourNow | Hourly mint limit in force, at most maxMintPerHour. |
refPrice | The anchor of the price band: the last accepted bid, 18 decimals. Zero means trading has not opened. |
refAt | When the anchor last moved. The band widens from this moment. |
settlementPrice | Zero while the market is live. Non-zero once it is wound down: the price every remaining token redeems at. |
The Issuer also exposes the counters that decide whether a trade fits right now:
- mintedLastHour(perp)
- USDC paid in that still counts toward the hourly cap. The counter decays linearly to zero over an hour (a leaky bucket), so there is no boundary where twice the cap gets through.
- redeemedLastHour(perp)
- The same for USDC paid out.
- mintBudget()
- USDC that may still be paid in across all markets. Every mint spends it and Ported tops it up as margin becomes ready on Hyperliquid. It fails closed: zero means no mint goes through anywhere.
- availableLiquidity()
- USDC the Issuer holds that can pay new redemptions at once: its balance minus accrued fees and minus what queued redemptions are owed.
- allowedMoveBps(perp)
- The band, in bps around refPrice, a price must fall in right now.
- mintsPaused(), redeemsPaused()
- The two emergency switches.
- claims(id), nextClaim(), claimCount()
- The redemption queue: each claim's recipient, amount and market; the oldest unpaid id; and the number ever queued.
import { ISSUER, issuerAbi, publicClient } from "./ported"
// Every listed market, then one market's state in a single Multicall3 request.
const count = await publicClient.readContract({ address: ISSUER, abi: issuerAbi, functionName: "marketCount" })
const perps = await publicClient.multicall({
allowFailure: false,
contracts: Array.from({ length: Number(count) }, (_, i) => ({
address: ISSUER, abi: issuerAbi, functionName: "perpIndexes", args: [BigInt(i)],
} as const)),
})
const perp = perps[0] // 10003, pGOLD
const [market, minted, redeemed, band, budget, liquidity, mintsPaused, redeemsPaused] =
await publicClient.multicall({
allowFailure: false,
contracts: [
{ address: ISSUER, abi: issuerAbi, functionName: "market", args: [perp] },
{ address: ISSUER, abi: issuerAbi, functionName: "mintedLastHour", args: [perp] },
{ address: ISSUER, abi: issuerAbi, functionName: "redeemedLastHour", args: [perp] },
{ address: ISSUER, abi: issuerAbi, functionName: "allowedMoveBps", args: [perp] },
{ address: ISSUER, abi: issuerAbi, functionName: "mintBudget" },
{ address: ISSUER, abi: issuerAbi, functionName: "availableLiquidity" },
{ address: ISSUER, abi: issuerAbi, functionName: "mintsPaused" },
{ address: ISSUER, abi: issuerAbi, functionName: "redeemsPaused" },
],
})
const live = market.settlementPrice === 0n
const canMint = live && market.params.mintEnabled && !mintsPaused
// USDC that can still go in this hour on this market, and across all markets
const mintRoomThisHour = market.maxMintPerHourNow - minted
const mintRoom = mintRoomThisHour < budget ? mintRoomThisHour : budgetWhat a trade must pass
The Issuer checks in this order. Each check maps to a named error, listed with what to do about it on Events and errors.
- 1Switches and marketMints revert while
mintsPaused, redeems whileredeemsPaused. The perp index must be a listed market; a mint also needsmintEnabledand no settlement price. - 2Hourly flowA mint's USDC is added to
mintedLastHourand must stay withinmaxMintPerHourNow. A redemption's USDC out must stay withinmaxRedeemPerHour. - 3Global budgetA mint must fit in
mintBudgetand spends it. - 4PriceThe quote must be signed, fresh and for this token. Its bid, and for a mint also its ask, must lie within
allowedMoveBpsofrefPrice. A settled market uses its settlement price instead and skips this step. - 5Your minimumThe computed amount must be at least
minTokensOutorminUsdcOut. The Issuer never fills you worse than the minimum you sign. - 6Debt cap (mints)
(supply + tokensOut) × max(ask, refPrice)must stay withinmaxDebtNow. Using the higher of the two prices stops a low ask from making a large supply look small. - 7PaymentA mint pulls
usdcInwithtransferFrom. A redemption burns your tokens and pays at once if the gross amount fits inavailableLiquidity(), otherwise it queues.
Simulating the call (eth_call, or viem's simulateContract) runs all of these against the current state and returns the first failure by name, before anything is signed.
Getting a signed price
Every live-market trade carries priceData: a quote signed by Ported's price service, encoded the way the price source expects. Ask for it right before you send the transaction. A quote is valid for maxQuoteAge() seconds (at most 30) counted from when the price was read, not from when you received it.
The helper below fetches a quote, checks that it prices the right token and that a registered attester signed it, and encodes it. The Quote API page covers the response fields, the modes and gathering several signatures.
import { encodeAbiParameters, getAddress, parseAbi, recoverTypedDataAddress, type Address, type Hex } from "viem"
import { elysium, ISSUER, issuerAbi, publicClient, QUOTE_API } from "./ported"
const priceSourceAbi = parseAbi([
"function threshold() view returns (uint8)",
"function isAttester(address) view returns (bool)",
])
const QUOTE_TYPES = {
Quote: [
{ name: "token", type: "address" },
{ name: "bid", type: "uint256" },
{ name: "ask", type: "uint256" },
{ name: "issuedAt", type: "uint64" },
{ name: "hlBlock", type: "uint64" },
],
} as const
/** A fresh signed quote for one market, checked, and the Issuer's priceData. */
export async function getPriceData(perp: number, token: Address) {
const priceSource = await publicClient.readContract({ address: ISSUER, abi: issuerAbi, functionName: "priceSource" })
const res = await fetch(QUOTE_API + "/quote?perp=" + perp, { cache: "no-store" })
if (!res.ok) throw new Error(res.status === 503 ? "no fresh price for this market, retry shortly" : "HTTP " + res.status)
const body = await res.json()
const quote = {
token: getAddress(body.quote.token),
bid: BigInt(body.quote.bid),
ask: BigInt(body.quote.ask),
issuedAt: BigInt(body.quote.issuedAt),
hlBlock: BigInt(body.quote.hlBlock),
}
if (quote.token !== getAddress(token)) throw new Error("quote for another token")
const domain = { name: "Ported Price", version: "2", chainId: elysium.id, verifyingContract: priceSource } as const
const signer = await recoverTypedDataAddress({
domain, types: QUOTE_TYPES, primaryType: "Quote", message: quote, signature: body.signature as Hex,
})
const [threshold, registered] = await publicClient.multicall({
allowFailure: false,
contracts: [
{ address: priceSource, abi: priceSourceAbi, functionName: "threshold" },
{ address: priceSource, abi: priceSourceAbi, functionName: "isAttester", args: [signer] },
],
})
if (!registered) throw new Error("not signed by a registered attester")
// One signature is enough only when threshold() is 1; otherwise gather co-signatures
// (see the Quote API page) and pass them all, sorted by signer address.
if (threshold > 1) throw new Error("this price source needs " + threshold + " signatures")
const priceData = encodeAbiParameters(
[{ type: "tuple", components: QUOTE_TYPES.Quote }, { type: "bytes[]" }],
[quote, [body.signature as Hex]],
)
return { quote, mode: body.mode as "normal" | "redeemOnly", priceData }
}Minting from a script
- 1Approve the IssuerFor the exact USDC amount of the mint. An unlimited approval works too, but the exact one leaves nothing behind.
- 2Fetch the quote lastAfter the approval is mined, so the quote's seconds are not spent waiting for it. Skip the mint if the mode is
redeemOnly. - 3Set the minimum from the quoteThe same formula as the contract. With the quote fixed, the output is deterministic, so the minimum can be exactly the expected amount.
- 4Simulate, then sendSend the simulated request unchanged, naming the chain.
import { erc20Abi, parseUnits } from "viem"
import { elysium, ISSUER, issuerAbi, publicClient, USDC, walletClient } from "./ported"
import { getPriceData } from "./quote"
const perp = 10003 // pGOLD
const usdcIn = parseUnits("100", 6) // 100 USDC
const me = walletClient.account.address
const market = await publicClient.readContract({ address: ISSUER, abi: issuerAbi, functionName: "market", args: [perp] })
// 1. Approve exactly what this mint spends. Name the chain on every write.
const approval = await walletClient.writeContract({
address: USDC, abi: erc20Abi, functionName: "approve", args: [ISSUER, usdcIn], chain: elysium,
})
await publicClient.waitForTransactionReceipt({ hash: approval })
// 2. Take the quote last: it is valid for maxQuoteAge seconds from the moment the price was read.
const { quote, mode, priceData } = await getPriceData(perp, market.token)
if (mode !== "normal") throw new Error("this market is redeem-only right now")
// 3. The same arithmetic as the Issuer, so the minimum is exactly what this quote gives.
const fee = (usdcIn * BigInt(market.params.mintFeeBps)) / 10_000n
const minTokensOut = ((usdcIn - fee) * 10n ** 30n) / quote.ask
// 4. Simulate first: a revert comes back as a named error before any gas is spent.
const { request, result } = await publicClient.simulateContract({
account: walletClient.account,
address: ISSUER,
abi: issuerAbi,
functionName: "mint",
args: [perp, usdcIn, minTokensOut, me, priceData],
})
const hash = await walletClient.writeContract({ ...request, chain: elysium })
const receipt = await publicClient.waitForTransactionReceipt({ hash })
console.log(receipt.status, "minted", result, "token units (18 decimals)")Redeeming, and the queue
redeem burns the caller's tokens at the quote's bid. It needs no approval: only the Issuer can burn pTokens, and it burns from msg.sender. Redeem-only quotes work, since a redemption uses only the bid.
If the Issuer holds enough free USDC, the recipient is paid in the same transaction. If it does not, the redemption is still final at that price: the tokens are burnt, and a claim for the USDC joins a first-in, first-out queue. Ported brings USDC over from HyperEVM and pays the queue, usually within minutes; anyone may also call payClaims(maxCount), which pays the oldest claims while the balance covers the next one in full.
- The return value of
redeemis the USDC paid or owed. Do not treat it as received. - A paid redemption emits
Redeemedand a USDCTransferto the recipient. A queued one emitsRedeemedthenRedeemQueued(claimId, perpIndex, recipient, amount), and laterClaimPaid(claimId, recipient, amount). - A claim is paid by a plain USDC transfer to its recipient, with no callback. A contract that redeems must not wait for the USDC inside the same call.
- The guardian can void an unpaid claim (
ClaimVoided): the burnt tokens are minted back to the holder, who is where they were before redeeming and can redeem again. This exists for a claim priced by a faulty quote, or one whose recipient cannot receive USDC and would hold up the queue.
import { parseEventLogs, parseUnits, type Hex } from "viem"
import { elysium, ISSUER, issuerAbi, publicClient, walletClient } from "./ported"
import { getPriceData } from "./quote"
const perp = 10003
const tokensIn = parseUnits("0.05", 18) // pTokens have 18 decimals
const me = walletClient.account.address
const market = await publicClient.readContract({ address: ISSUER, abi: issuerAbi, functionName: "market", args: [perp] })
// A wound-down market pays its settlement price and ignores priceData.
let bid = market.settlementPrice
let priceData: Hex = "0x"
if (bid === 0n) {
const q = await getPriceData(perp, market.token) // redeem-only quotes are fine here
bid = q.quote.bid
priceData = q.priceData
}
const gross = (tokensIn * bid) / 10n ** 30n
const minUsdcOut = gross - (gross * BigInt(market.params.redeemFeeBps)) / 10_000n
// No approval: the Issuer burns the caller's tokens directly.
const { request } = await publicClient.simulateContract({
account: walletClient.account,
address: ISSUER,
abi: issuerAbi,
functionName: "redeem",
args: [perp, tokensIn, minUsdcOut, me, priceData],
})
const hash = await walletClient.writeContract({ ...request, chain: elysium })
const receipt = await publicClient.waitForTransactionReceipt({ hash })
// The return value is what is paid OR owed. The events say which.
const logs = parseEventLogs({ abi: issuerAbi, logs: receipt.logs })
const queued = logs.find((l) => l.eventName === "RedeemQueued")
if (!queued) {
console.log("paid now")
} else {
const claimId = queued.args.claimId
console.log("queued as claim", claimId, "owed", queued.args.amount)
// Wait for ClaimPaid(claimId). The keeper pays the queue as USDC arrives;
// anyone may also call payClaims(maxCount) once the Issuer holds enough.
const unwatch = publicClient.watchContractEvent({
address: ISSUER,
abi: issuerAbi,
eventName: "ClaimPaid",
args: { claimId },
onLogs: (paid) => {
console.log("paid", paid[0].args.amount, "in", paid[0].transactionHash)
unwatch()
},
})
}The Redemption queue page explains the queue's ordering and guarantees in full.
Calling from a contract
A contract can mint and redeem like any account. The price still comes from off-chain, so the contract takes priceData from its caller and passes it through untouched; the Issuer verifies it.
msg.senderpays the USDC on a mint and must have approved the Issuer. Therecipientcan be anyone, so a router can mint straight to its user.- On a redemption, the tokens are burnt from
msg.sender: the contract must hold them. If the redemption queues, the USDC reachesrecipientlater; prefer the end user as recipient over the contract itself. - Pass the user's minimum through as well. A router that sets its own minimum to zero takes the user's price protection away.
- Read
settlementPricebefore redeeming: on a wound-down market,priceDatais ignored and can be empty.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
/// The parts of Ported's Issuer this contract calls.
interface IPortedIssuer {
function mint(uint32 perpIndex, uint256 usdcIn, uint256 minTokensOut, address recipient, bytes calldata priceData)
external returns (uint256 tokensOut);
function redeem(uint32 perpIndex, uint256 tokensIn, uint256 minUsdcOut, address recipient, bytes calldata priceData)
external returns (uint256 usdcOut);
}
contract BuysPGold {
using SafeERC20 for IERC20;
IPortedIssuer public constant ISSUER = IPortedIssuer(0xAD6FF5B33F815EFCd3181e8Acbc210c38Ee2a268);
IERC20 public constant USDC = IERC20(0xb47c4C8F73F009CC0C0d3f92B388d13E293F0B65);
uint32 public constant PGOLD = 10003;
/// priceData comes from the caller, who fetched a signed quote off-chain moments ago.
function buyFor(address user, uint256 usdcIn, uint256 minTokensOut, bytes calldata priceData)
external returns (uint256 tokensOut)
{
USDC.safeTransferFrom(msg.sender, address(this), usdcIn);
USDC.forceApprove(address(ISSUER), usdcIn);
// This contract pays, the user receives the pTokens.
tokensOut = ISSUER.mint(PGOLD, usdcIn, minTokensOut, user, priceData);
}
}pTokens as ERC-20s
A pToken is OpenZeppelin's ERC-20 with EIP-2612 permit (ERC20Permit), 18 decimals, and nothing else: no transfer fee, no hooks, no blocklist, no pause, no rebasing. Pools, vaults, lending markets and bridges that accept a plain ERC-20 accept it as it is.
- Name and symbol
- Set at listing, for example
Ported Gold/pGOLD. - Extra views
perpIndex()(the Hyperliquid market it tracks) andissuer()(the only address that mints and burns).- Permit
- EIP-712 domain: the token's name, version
"1", chain id 99901, the token address. - Supply
- Changes only through the Issuer: mints, redemptions, and a voided claim minting tokens back to their holder.
- Pauses
- The Issuer's switches stop minting and redeeming, never transfers. A pToken always moves freely.
Always name the chain
Every write must say which chain it is for: chain: elysium in viem, chainId: 99901 in wagmi's writeContract and sendTransaction. viem checks the wallet's chain before signing by default; wagmi turns that check off unless chainId is passed. A transaction signed on the wrong network does not necessarily fail: sent to an address with no code there, it succeeds as a plain transfer to an account nobody controls.
In a user interface, add a second layer: do not render the mint or redeem action at all while the wallet is on another chain, and put a button that switches to Elysium in its place.
Common mistakes
| Mistake | What happens | Instead |
|---|---|---|
| Fetching the quote before the approval | The quote ages while the approval confirms; the mint reverts with QuoteTooOld. | Approve first, quote last. |
| Minting on a redeem-only quote | The ask is 100 times the bid: the mint would buy about 1% of what it pays for. A minimum computed from a normal price makes it revert with Slippage. | Check mode and skip mints unless it is normal. |
| Mixing decimals | USDC has 6 decimals, pTokens 18, prices 18. Off by 1e12 is the usual symptom. | Use the formulas above, with 1e30. |
| Treating redeem's return as paid | The USDC may be queued and arrive minutes later. | Look for RedeemQueued in the receipt. |
| Polling the quote API | Requests are rate limited per IP, and an unused quote is worth nothing. | One quote per transaction, fetched just before it. |
| Hardcoding the price source | A new price source would break signature checks. | Read priceSource() from the Issuer. |