Skip to the content
TAPEHOUSE

SDKs

TypeScript SDK

Read the band, margin accounts, shorts, baskets and gap cover and build their transactions with @tapehouse/sdk on viem.

@tapehouse/sdk is typed reads and transaction builders for Tapehouse's contracts, on viem 2. A read takes a viem client and returns plain values. A transaction function returns a viem contract call you pass to simulateContract and writeContract, so you choose the wallet, the signer and the gas settings.

Install#

Shell
pnpm add @tapehouse/sdk viem

viem is a peer dependency (^2.57.2). The package is ESM, ships its own types, and is licensed MIT OR Apache-2.0.

Read and send#

Every function takes a chain's registry as its second argument, parsed from deployments/<chainId>.json with parseDeployments. The SDK compiles in no address.

TypeScript
import { readFileSync } from 'node:fs'
import { createPublicClient, createWalletClient, http } from 'viem'
import { privateKeyToAccount } from 'viem/accounts'
import { robinhoodTestnet } from 'viem/chains'
import { accounts, band, CROSS, parseDeployments } from '@tapehouse/sdk'

const deployments = parseDeployments(JSON.parse(readFileSync('deployments/46630.json', 'utf8')))
const publicClient = createPublicClient({ chain: robinhoodTestnet, transport: http() })

const { state, low, high } = await band.quote(publicClient, deployments, 'TSLA')

const owner = '0xB986a345655097302cac8b4af6C948FfaF7f55FC'
const price = await accounts.liquidationPrice(publicClient, deployments, owner, CROSS, 'TSLA', 50_000_000n)

const wallet = createWalletClient({
  account: privateKeyToAccount(process.env.PRIVATE_KEY as `0x${string}`),
  chain: robinhoodTestnet,
  transport: http(),
})
const { request } = await publicClient.simulateContract({
  ...accounts.borrow(deployments, { position: CROSS, assets: 50_000_000n, account: owner, receiver: owner }),
  account: wallet.account,
})
const hash = await wallet.writeContract(request)

An asset is its symbol as a string ('TSLA'); the SDK turns it into the bytes32 the contracts take with toBytes32. A position is CROSS, the cross position, or an asset's symbol as bytes32 for its isolated position; accounts.positions lists them. Amounts are bigint in the token's raw units: USDG has 6 decimals, Stock Tokens 18, and the band's prices are USD with 8.

Every read ends with an optional at argument, { blockNumber?: bigint }. Reads that combine several calls (repayment, lending, holding, limits, backstop.state and others) take all of them at one block, the latest by default.

Registry#

ExportWhat it does
parseDeployments(json)Parses a registry. An address in mixed case must carry its checksum; each is returned checksummed. Returns Deployments
toBytes32(name)An asset symbol or a RedStone feed ID as its ASCII bytes, right-padded to 32
CROSSThe cross position, zeroHash
tokenPriceFeed(deployments, name), sharePriceFeed(deployments, name)A .chainlink feed typed by what it prices: the Stock Token on Robinhood Chain, the share on Arbitrum One. Each throws on the other kind
SHARE_PRICE_CHAINSThe chains whose Chainlink feeds price the share: [42161]

Modules#

Each module is a namespace import: import { band, accounts } from '@tapehouse/sdk'. A transaction function takes deployments and a named-argument object and returns { address, abi, functionName, args }. A read takes client, deployments, its arguments and at.

band#

The band's quote, session and halt, each asset's BandFeed, and Chainlink feeds. The band says what the values mean.

FunctionArgumentsReturns or does
quoteclient, deployments, asset{ state, live, mid, halfBps, low, high }; state is 0 halted, 1 degraded, 2 closed, 3 open
sessionclient, deployments{ state, nyse, nyseNext, changeMs, boundaryMs }
haltclient, deployments, asset{ signedHalt, until, issuedAt, oraclePaused }
priceclient, deployments, feedIdThe RedStone value the band stores: { value, packageTimestampMs, writtenAt }
writePricesdeployments, source, feedIdsThe band's writePrices with the payload source returns. source is a PackageSource, your own RedStone gateway client or relay; the SDK holds no API key
latestRoundclient, deployments, assetThe BandFeed's low side as a Chainlink round
latestBandclient, deployments, assetThe whole band from the BandFeed, with the market and both halt sources
sealedclient, deployments, asset, reopenMsThe band sealed before a reopen; all zero if none
sealdeployments, assetBandFeed.seal(), which anyone may call in the ten minutes before the session reopens
chainlinkRoundclient, feedThe latest round of a .chainlink feed, with what it prices

accounts#

The margin accounts. position is CROSS or an asset's bytes32.

FunctionArgumentsDoes
setAuthorizationdeployments, authorized, allowedLets an address borrow, withdraw, deposit and act for your shorts
setMandatedeployments, { agent, expiresAt, maxDebt, maxLeverage }Bounded authority for an agent until expiresAt; expiresAt of 0 ends it
depositdeployments, { position, token, amount, account }Deposits a token; a basket's address deposits its shares into CROSS
depositWithPermitdeployments, { position, token, amount, account, deadline, signature }The same with an EIP-2612 permit
wrapdeployments, { account, value }Ether into WETH for an account
withdrawdeployments, { position, token, amount, account, receiver }Withdraws collateral
borrowdeployments, { position, assets, account, receiver }Borrows USDG
repaydeployments, { position, assets, account }Repays debt first, then premium. Anyone may
unwrapdeployments, { account, basket, shares }Redeems basket shares in the cross position for the Stock Tokens
lend, unlend, recalldeployments, { position, token, amount, account }Lend a Stock Token through its lending vault, take it back, or queue a recall
settledeployments, { account, position, token }Takes what the vault holds for a recall. Anyone may
observedeployments, { asset }Records an asset seen halted. Anyone may
isAuthorizedclient, deployments, account, authorizedWhether an address may act for an account
mandate, mandateStatusclient, deployments, { account, agent } and, for status, positionThe mandate, and whether the agent may borrow now with reason and debtRoom
healthclient, deployments, account, position{ equity, requirement, missing, regime } in USD with 18 decimals
collateralclient, deployments, account, position, tokenWhat the position holds of a token
leverageclient, deployments, account, positionGross exposure over equity in basis points
liquidationPriceclient, deployments, account, position, asset, borrowingThe price at or above which the position meets its requirement once it owes borrowing more USDG
repaymentclient, deployments, account, position{ debt, premium, assets }, what a full repayment takes
inBasketsclient, deployments, account, positionWhat the position holds of each Stock Token through its baskets
lendingclient, deployments, account, position, token{ lent, sellable, claim, recalls }
recoveryclient, deployments, assetWhen borrowing against an asset reopens after it was seen unusable
holdingclient, deployments, asset, tokenThe accounts' holding of an asset against its cap
limitsclient, deploymentsDebt, caps, weekend leverage, the guardian's pause and the premium rate
issuerclient, token, holdersThe issuer's pause and its registry's blocks
stocks, positionsclient, deploymentsThe engine's assets and tokens, and every position an account may hold

engine#

The margin engine's requirement for any portfolio. A Portfolio is { quantities, prices }: signed amounts with 18 decimals and USD prices with 8, in the engine's order.

FunctionArgumentsReturns
requirementclient, deployments, portfolio, { horizon?, spansClosure }{ margin, missing } over horizon seconds, two days (HORIZON) by default
currentRequirementclient, deployments, portfolio{ margin, missing, regime } for the session now

supply#

The vault USDG lenders deposit into.

FunctionArgumentsDoes
depositdeployments, { assets, receiver }Deposits USDG for shares
depositWithPermitdeployments, { assets, receiver, deadline, signature }The same with a USDG permit
withdrawdeployments, { assets, receiver, owner }Withdraws USDG, at most what the vault holds and has not lent
redeemdeployments, { shares, receiver, owner }Redeems shares
marketclient, deploymentsRates, utilisation, what it holds and lent, and open
lenderclient, deployments, ownerA lender's shares, what they are worth and what may leave now

backstop#

The gap backstop that absorbs a closure's losses.

FunctionArgumentsDoes
depositdeployments, { assets, receiver }Deposits USDG
startCooldowndeploymentsStarts the cooldown of all the caller's shares
withdraw, redeemdeployments, { assets or shares, receiver, owner }Takes USDG out within the cooldown's window
claimGainsdeployments, tokenClaims a Stock Token gained from the auction
claimdeploymentsClaims the premium set aside for the backstop. Anyone may
stateclient, deploymentsHoldings, exposure limits per position, premium and terms
depositorclient, deployments, owner, tokensA depositor's shares, cooldown and gains

auction#

The reopening auction. A bid is committed under a hash, then revealed. commitment computes the hash and clearingPrice the one price the contract accepts.

FunctionArgumentsDoes
commitment{ bidder, asset, openMs, quantity, price, salt }The hash a bid is committed under
clearingPricebids, supply, floorA round's only clearing price, or undefined if none clears
commitdeployments, { asset, commitment, deposit }Commits a hidden bid
revealdeployments, { asset, openMs, quantity, price, salt }Reveals it
claimdeployments, { asset, openMs, index }Sends the bidder its tokens and the rest of its escrow
forfeitdeployments, { asset, openMs, commitment }Forfeits an unrevealed commitment. Anyone may
cleardeployments, { asset, openMs, price }Clears a round. Anyone may
enrolldeployments, { account, position, asset }Enrolls a position short at its bands' low edges. Anyone may
constants, phase, lastOpenMsclient, deploymentsThe bond, windows and phase
round, previewFloor, commitmentOfclient, deployments, { asset, openMs } (and commitment)A round's lots and bids, the floor it will open with, and a commitment

stockLending#

FunctionArgumentsReturns
termsclient, deployments, assetUtilisation, rates, what the vault holds for recalls, what may still be borrowed, maxUtilization, notice, feeShare
ticketclient, deployments, asset, idA recall ticket and the ticket next in turn

sponsorship#

The ERC-4337 side. The sponsor is the service that pays.

FunctionArgumentsDoes
entryPoint, accountFactory, paymasterdeploymentsThe registry's EntryPoint, SimpleAccount factory and sponsor paymaster
accountAddressclient, deployments, ownerThe SimpleAccount the factory makes for an owner, salt 0
freeOperationsLeftclient, deployments, accountSponsored operations left
asCallone transaction of this SDKThe same as a call of a user operation
permitclient, { token, owner, account, value, deadline }EIP-2612 typed data for signTypedData, its domain read from the chain
pull{ token, owner, account, value, deadline, signature }The permit and transfer by which the account takes the token
callGasclient, deployments, account, callDataThe cold L2 gas of the account's calls

baskets#

A basket is keyed by its name in .tapehouse.Baskets, for example 'PAIR'.

FunctionArgumentsDoes
mintdeployments, { basket, shares, receiver, maxAssets }Mints shares for at most maxAssets of each Stock Token
redeemdeployments, { basket, shares, receiver, owner }Redeems shares for the Stock Tokens
componentsclient, deployments, basket{ assets, tokens }
previewMint, previewRedeemclient, deployments, basket, sharesWhat a mint takes (rounded up) or a redemption gives (rounded down)
target, pendingTargetclient, deployments, basketUnits per share in effect, and a proposed target with its effectiveAt

shorts#

FunctionArgumentsDoes
depositdeployments, { asset, amount, account }Adds USDG to a short
withdrawdeployments, { asset, amount, account, receiver }Takes USDG out
selldeployments, { asset, amount, minProceeds, account }Borrows the asset and sells it
coverdeployments, { asset, amount, maxCost, account }Buys it back and repays
liquidatedeployments, { account, asset }Buys back a short that fell short. Anyone may
markdeployments, assetRecords the band centre for the restriction after a 10% fall. Anyone may
quoteSale, quoteCoverclient, deployments, { asset, amount, slippageBps }Uniswap QuoterV2's quote with minProceeds or maxCost; slippage is 0 to 10,000 basis points
position, healthclient, deployments, account, assetA short's USDG, debt, shares and epoch, and its equity and requirement
epoch, book, restriction, feeclient, deployments, asset (and epoch for book)The asset's current book epoch, a book's shares and USDG, whether a short sells now, and the pool's fee tier

morpho#

FunctionArgumentsReturns
priceclient, deployments, asset{ price }, or { price: undefined, noPrice, revert } with noPrice one of stale, halted, sequencerNotSettled. Never zero
haltclient, deployments, assetThe halt as the oracle reports it
oracleclient, deployments, assetThe band, symbol, tokens, scale factor and owner

gapCover#

FunctionArgumentsDoes
buydeployments, { asset, maxPremium, holder, notional, deductibleBps, limitBps }Buys cover for the coming closure
deposit, withdraw, redeemas in supplyWriter deposits and exits
recorddeploymentsRecords the session's next close, or the reopen. Anyone may
measuredeployments, assetKeeps the week's realised move on sale. Anyone may
observedeployments, { asset, closesMs }Records the band in this minute's slot after a closure. Anyone may
settledeployments, { asset, closesMs, referenceRound, lastRound }Settles an asset's series. Anyone may
releasedeployments, idCredits a cover's payout or refund to its holder. Anyone may
claimdeployments, receiverSends the caller its credited USDG
quoteclient, deployments, asset, layerThe premium and the USDG it reserves
minDeductible, pricingGap, capacity, lastCloseMs, salesclient, deployments (and asset)What the cover prices and sells now
series, cover, holdings, payouts, writers, writerclient, deployments, ...Series, covers, a holder's covers, payouts and writers
payoutlayer, { referencePrice, price }What a settled cover pays, computed locally

The gap cover contract has the rules behind each call.

ABIs and errors#

The contracts' ABIs are exported as const from the build: bandAbi, bandFeedAbi, marginAbi, marginAccountsAbi, liquidatorAbi, gapBackstopAbi, reopeningAuctionAbi, stockLendingVaultAbi, supplyVaultAbi, shortPositionsAbi, basketAbi, gapCoverAbi, morphoBandOracleAbi, sponsorPaymasterAbi, stockTokenAbi, usdgAbi, wethAbi, aggregatorAbi, quoterV2Abi, uniswapV3PoolAbi, morphoBlueAbi and others. decodeRevert, decodeRevertData and errorsAbi are on the errors page.

Authorization#

An account acts for itself. For anyone else to borrow, withdraw, deposit or act on its shorts, the owner calls accounts.setAuthorization(deployments, authorized, true). Until then the call reverts with Unauthorized(caller, account). For an agent that should be bounded, accounts.setMandate caps its debt and leverage and gives it an end time.

Examples#

The package has two runnable examples. examples/devnode.ts runs the band, accounts, shorts, baskets and gap cover modules against a local Nitro dev node (PRIVATE_KEY=0x… pnpm devnode RPC_URL DEPLOYMENTS_JSON PAYLOAD_FILE, with the account owner's key). examples/sponsored.ts sends a user operation through the sponsor paymaster (PRIVATE_KEY=0x… pnpm sponsored RPC_URL BUNDLER_URL SPONSOR_URL DEPLOYMENTS_JSON).

Next#