Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -208,6 +208,7 @@ All generated or modified code **must** include JSDoc comments (`/** ... */`), c
- protoc-gen packages have `postinstall` scripts that trigger `pnpm dist` — this can be slow on first install
- The `fix-hybrid-output.mjs` script must run after every build of hybrid packages or ESM imports will break in Node
- `packages/sdk-core/src/contracts/sysio/authex` owns `sysio.authex` action builders, link table reads, and create-link proof helpers. Consumers should not duplicate the `createlink` message/signature rules locally.
- `packages/sdk-core/src/contracts/sysio/chains` owns `sysio.chains` registry reads, chain-code normalization, lifecycle filtering, and privileged action construction. Treat registry rows as protocol identity/activation data; RPCs, explorers, icons, wallets, and application capability metadata remain consumer concerns.
- AuthEx `links` reads use wire-sysio KV `index_name` queries with JSON-encoded bounds. Preserve KV row unwrapping, generated enum-name normalization, and compressed/uncompressed EM key equivalence.
- `packages/sdk-core/src/contracts/sysio/Client.ts` is the generic transport facade for every generated system contract. Keep action/table names sourced from `SysioContractDefinitions`; keep workflow behavior in the `authex`, `msig`, and `reserv` domain clients.
- `packages/sdk-core/src/contracts/sysio/Codecs.ts` is the only hand-written system-action codec registry. Add entries only when synchronous action construction is required; generated actions without a codec must retain the `AnyAction` fallback.
Expand Down
59 changes: 59 additions & 0 deletions packages/sdk-core/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,25 @@ const links = await authex.getLinks("alice")

Current wire-sysio nodes expose `links` as a KV table. `AuthexClient` uses the deployed named indexes and JSON bounds, unwraps KV rows through `ChainAPI`, normalizes generated enum-name responses, and treats compressed/uncompressed EM public-key renderings as the same external key.

## Chain registry

`contracts.sysio.chains` exposes the active Wire chain registry through the
same typed proxy used by the other system-contract facades. `ChainsClient`
normalizes packed chain codes, enum-name responses, lifecycle timestamps, and
depot state while preserving the generated row for lower-level consumers.

```ts
const chains = new contracts.sysio.chains.ChainsClient({ client: api })
const activeOutposts = await chains.listChains({
activeOnly: true,
includeDepot: false
})
```

The on-chain registry is authoritative for protocol identity and activation.
RPC URLs, explorers, icons, wallet adapters, and application capabilities stay
in the consuming application's runtime configuration.

## Reserves

`contracts.sysio.reserv` provides normalized reserve registry reads,
Expand All @@ -102,6 +121,46 @@ await reserves.pushMatchReserve({
})
```

## Reserve swaps

Reserve swap integrations compose three on-chain sources instead of carrying a
parallel token or route catalog:

- `contracts.sysio.tokens.TokenRegistryClient` reads canonical token metadata
and active chain deployments.
- `contracts.sysio.reserv.ReserveClient` discovers active liquidity and returns
live `swapquote` output for external or WIRE endpoints.
- `contracts.sysio.uwrit.UnderwritingClient` reads swap lifecycle state and
submits WIRE-origin swaps into the next-epoch queue.

```ts
const tokens = new contracts.sysio.tokens.TokenRegistryClient({ client: api })
const reserves = new contracts.sysio.reserv.ReserveClient({ client: api })
const underwriting = new contracts.sysio.uwrit.UnderwritingClient({ client: api })

const assets = await tokens.listAssets()
const quote = await reserves.getSwapQuote({
from: contracts.sysio.uwrit.WIRE_SWAP_ENDPOINT,
fromAmount: 10_000_000_000n,
to: { chainCode: "SOLANA", tokenCode: "SOL", reserveCode: "PRIMARY" }
})

await underwriting.pushSwapFromWire({
user: "alice",
wireAmount: 10_000_000_000n,
destination: { chainCode: "SOLANA", tokenCode: "SOL", reserveCode: "PRIMARY" },
targetAmount: quote,
targetToleranceBps: 500,
recipientKind: SysioUwritChainkind.CHAIN_KIND_SVM,
recipientAddress: "<solana-public-key-bytes>"
})
```

External-origin swap submission remains in the chain SDK that owns the deployed
outpost ABI or IDL. A mined source transaction means the swap was submitted;
`uwreqs` remains the source of truth for relay, underwriting, settlement, and
revert status.

## Install

```sh
Expand Down
64 changes: 64 additions & 0 deletions packages/sdk-core/src/contracts/sysio/chains/Actions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import type { Action } from "../../../chain/Action.js"
import type * as SysioContracts from "../../../types/SysioContractTypes.js"
import { buildContractAction } from "../../Contract.js"

import { DEFAULT_CHAINS_CONTRACT, MAX_EXTERNAL_CHAIN_ID } from "./Constants.js"
import { descriptor } from "./Descriptor.js"
import { chainSlugData } from "./Slug.js"
import type {
ChainRegistration,
CreateActivateChainActionOptions,
CreateRegisterChainActionOptions
} from "./Types.js"

function assertExternalChainId(value: number): number {
if (!Number.isInteger(value) || value < 0 || value > MAX_EXTERNAL_CHAIN_ID) {
throw new Error("External chain ID must be an unsigned 32-bit integer.")
}

return value
}

/** Creates generated action data for `sysio.chains::regchain`. */
export function createRegisterChainActionData(
registration: ChainRegistration
): SysioContracts.SysioChainsRegchainAction {
return {
kind: registration.kind,
code: chainSlugData(registration.code),
external_chain_id: assertExternalChainId(registration.externalChainId),
name: registration.name,
description: registration.description
}
}

/** Creates an unsigned privileged `sysio.chains::regchain` action. */
export function createRegisterChainAction(
options: CreateRegisterChainActionOptions
): Action {
return buildContractAction({
contract: options.contract || DEFAULT_CHAINS_CONTRACT,
descriptor: descriptor.actions.regchain,
authorization: options.authorization,
data: createRegisterChainActionData(options.registration)
})
}

/** Creates generated action data for `sysio.chains::activchain`. */
export function createActivateChainActionData(
code: CreateActivateChainActionOptions["code"]
): SysioContracts.SysioChainsActivchainAction {
return { code: chainSlugData(code) }
}

/** Creates an unsigned privileged `sysio.chains::activchain` action. */
export function createActivateChainAction(
options: CreateActivateChainActionOptions
): Action {
return buildContractAction({
contract: options.contract || DEFAULT_CHAINS_CONTRACT,
descriptor: descriptor.actions.activchain,
authorization: options.authorization,
data: createActivateChainActionData(options.code)
})
}
157 changes: 157 additions & 0 deletions packages/sdk-core/src/contracts/sysio/chains/Client.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
import type { APIClient } from "../../../api/Client.js"
import type { Action } from "../../../chain/Action.js"
import type { NameType } from "../../../chain/Name.js"
import {
SysioChainsChainkind,
SysioContractName
} from "../../../types/SysioContractTypes.js"
import type * as SysioContracts from "../../../types/SysioContractTypes.js"
import type { ContractTableRowsOptions } from "../../Contract.js"
import { getSysioContract, type SysioContractClient } from "../Client.js"

import {
createActivateChainAction,
createRegisterChainAction
} from "./Actions.js"
import {
DEFAULT_CHAINS_CONTRACT,
DEFAULT_CHAIN_QUERY_LIMIT
} from "./Constants.js"
import { chainSlugString, chainSlugValue } from "./Slug.js"
import type {
ChainRecord,
ChainSlugName,
ChainsClientOptions,
CreateActivateChainActionOptions,
CreateRegisterChainActionOptions,
ListChainsOptions
} from "./Types.js"

function chainKindValue(
value: SysioContracts.SysioChainsChainRowType["kind"]
): SysioContracts.SysioChainsChainkind {
if (typeof value === "number") return value

const serialized = String(value)
if (/^[0-9]+$/.test(serialized)) {
return Number(serialized) as SysioContracts.SysioChainsChainkind
}

const mapped = SysioChainsChainkind[value]
if (mapped == null) {
throw new Error(`Unknown chain kind: ${serialized}`)
}

return Number(mapped) as SysioContracts.SysioChainsChainkind
}

function rowSlugValue(value: SysioContracts.SysioChainsSlugNameType): number {
return chainSlugValue(value.value)
}

/** Normalizes a generated chain registry row into application-friendly values. */
export function normalizeChainRow(
row: SysioContracts.SysioChainsChainRowType
): ChainRecord {
const codeValue = rowSlugValue(row.code)

return {
code: chainSlugString(codeValue),
codeValue,
kind: chainKindValue(row.kind),
externalChainId: row.external_chain_id,
name: row.name,
description: row.description,
isDepot: row.is_depot,
active: row.active,
registeredAtMs: BigInt(row.registered_at_ms.toString()),
activatedAtMs: BigInt(row.activated_at_ms.toString()),
raw: row
}
}

/** UI-neutral client for `sysio.chains` discovery and privileged action creation. */
export class ChainsClient {
/** Chain API client used for RPC calls. */
readonly client: APIClient

/** Chain registry contract account. */
readonly contract: NameType

/** Generic typed proxy for direct action and table access. */
readonly contractClient: SysioContractClient<SysioContractName.chains>

/** Creates a chain registry client. */
constructor(config: ChainsClientOptions) {
this.client = config.client
this.contract = config.contract || DEFAULT_CHAINS_CONTRACT
this.contractClient = getSysioContract(SysioContractName.chains, {
client: config.client,
contract: this.contract
})
}

/** Creates an unsigned privileged chain registration action. */
createRegisterChainAction(
options: Omit<CreateRegisterChainActionOptions, "contract">
): Action {
return createRegisterChainAction({ ...options, contract: this.contract })
}

/** Creates an unsigned privileged chain activation action. */
createActivateChainAction(
options: Omit<CreateActivateChainActionOptions, "contract">
): Action {
return createActivateChainAction({ ...options, contract: this.contract })
}

/** Lists raw generated chain rows, scanning additional KV pages as needed. */
async listChainRows(
options: ListChainsOptions = {}
): Promise<SysioContracts.SysioChainsChainRowType[]> {
const limit = Math.max(
Math.floor(options.limit || DEFAULT_CHAIN_QUERY_LIMIT),
1
),
rows: SysioContracts.SysioChainsChainRowType[] = []
let lowerBound: string | undefined

do {
const query: ContractTableRowsOptions<string> = {
limit: DEFAULT_CHAIN_QUERY_LIMIT,
...(lowerBound ? { lower_bound: lowerBound } : {})
},
result = await this.contractClient.tables.chains.rows<string>(query),
matches = result.rows.filter(row => {
const kindMatches =
options.kind == null || chainKindValue(row.kind) === options.kind,
activeMatches = !options.activeOnly || row.active,
depotMatches = options.includeDepot !== false || !row.is_depot

return kindMatches && activeMatches && depotMatches
})

rows.push(...matches.slice(0, limit - rows.length))

const nextKey = result.more ? result.next_key : undefined
if (!nextKey || String(nextKey) === lowerBound) break
lowerBound = String(nextKey)
} while (rows.length < limit)

return rows
}

/** Lists normalized registered chains with optional lifecycle/family filtering. */
async listChains(options: ListChainsOptions = {}): Promise<ChainRecord[]> {
return (await this.listChainRows(options)).map(normalizeChainRow)
}

/** Reads one registered chain by exact chain code, or null when absent. */
async getChain(code: ChainSlugName): Promise<ChainRecord> {
const codeValue = chainSlugValue(code),
rows = await this.listChainRows({ limit: Number.MAX_SAFE_INTEGER }),
row = rows.find(candidate => rowSlugValue(candidate.code) === codeValue)

return row ? normalizeChainRow(row) : null
}
}
8 changes: 8 additions & 0 deletions packages/sdk-core/src/contracts/sysio/chains/Constants.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
/** Default account that hosts the Wire chain registry. */
export const DEFAULT_CHAINS_CONTRACT = "sysio.chains"

/** Rows requested per page while scanning the chain registry. */
export const DEFAULT_CHAIN_QUERY_LIMIT = 500

/** Largest external chain identifier accepted by the uint32 contract field. */
export const MAX_EXTERNAL_CHAIN_ID = 0xffffffff
43 changes: 43 additions & 0 deletions packages/sdk-core/src/contracts/sysio/chains/Descriptor.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import type { ContractDescriptor } from "../../Contract.js"
import type * as SysioContracts from "../../../types/SysioContractTypes.js"

import { DEFAULT_CHAINS_CONTRACT } from "./Constants.js"
import { ChainsActivateChain, ChainsRegisterChain } from "./Structs.js"

/** Generated `sysio.chains` action data keyed by ABI action name. */
export interface SysioChainsActionData {
/** `sysio.chains::regchain` action data. */
regchain: SysioContracts.SysioChainsRegchainAction
/** `sysio.chains::activchain` action data. */
activchain: SysioContracts.SysioChainsActivchainAction
}

/** Generated `sysio.chains` table rows keyed by ABI table name. */
export interface SysioChainsTableRows {
/** `sysio.chains::chains` registry row. */
chains: SysioContracts.SysioChainsChainRowType
}

/** Runtime descriptor for the public `sysio.chains` integration surface. */
export const descriptor: ContractDescriptor<
SysioChainsActionData,
SysioChainsTableRows
> = {
account: DEFAULT_CHAINS_CONTRACT,
actions: {
regchain: {
name: "regchain",
serialize: data => ChainsRegisterChain.from(data)
},
activchain: {
name: "activchain",
serialize: data => ChainsActivateChain.from(data)
}
},
tables: {
chains: {
name: "chains",
rowType: null
}
}
}
34 changes: 34 additions & 0 deletions packages/sdk-core/src/contracts/sysio/chains/Slug.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { SlugName } from "../../../SlugName.js"
import type * as SysioContracts from "../../../types/SysioContractTypes.js"

import type { ChainSlugName } from "./Types.js"

/** Converts a friendly chain slug or packed value to its safe numeric form. */
export function chainSlugValue(value: ChainSlugName): number {
const numericString = typeof value === "string" && /^[0-9]+$/.test(value),
packed = numericString
? Number(value)
: typeof value === "string"
? SlugName.from(value)
: Number(value)

if (!Number.isSafeInteger(packed) || packed <= 0) {
throw new Error(
"Chain slug must be a non-zero safe integer or valid slug_name string."
)
}

return packed
}

/** Converts a friendly chain slug to generated `slug_name` action data. */
export function chainSlugData(
value: ChainSlugName
): SysioContracts.SysioChainsSlugNameType {
return { value: chainSlugValue(value) }
}

/** Returns the display form of a packed chain slug. */
export function chainSlugString(value: ChainSlugName): string {
return SlugName.toString(chainSlugValue(value))
}
Loading
Loading