@asentum/sdk 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/client.ts","../src/wallet.ts","../src/contract.ts"],"sourcesContent":["// Copyright 2026 The AsentumChain Contributors\n// SPDX-License-Identifier: Apache-2.0\n\n/**\n * AsentumClient — read-only interface to an Asentum node's RPC.\n *\n * Wraps the node's HTTP endpoints in a typed, Promise-based API.\n * No private keys, no signing — just reads. For sending transactions,\n * use {@link AsentumWallet} which extends the client with a keypair.\n *\n * Works in Node.js (20+) and browsers — only depends on `fetch`.\n */\n\nexport interface ChainInfo {\n chainId: string;\n height: number;\n mempoolSize: number;\n latestHeader: BlockHeader;\n}\n\nexport interface BlockHeader {\n parentHash: string;\n stateRoot: string;\n transactionsRoot: string;\n receiptsRoot: string;\n number: string;\n timestamp: string;\n gasLimit: string;\n gasUsed: string;\n baseFeePerGas: string;\n proposer: string;\n}\n\nexport interface Block {\n header: BlockHeader;\n hash?: string;\n transactions: Transaction[];\n receipts: Receipt[];\n}\n\nexport interface Transaction {\n kind: 'transfer' | 'deploy' | 'call';\n body: {\n chainId: string;\n nonce: string;\n maxPriorityFeePerGas: string;\n maxFeePerGas: string;\n gasLimit: string;\n to: string;\n value: string;\n dataSize: number;\n };\n call?: {\n method: string;\n args: unknown[];\n };\n}\n\nexport interface Receipt {\n txHash: string;\n blockNumber: string;\n txIndex: number;\n sender: string;\n recipient: string;\n kind: string;\n success: boolean;\n gasUsed: string;\n events: Array<{ name: string; data: unknown }>;\n returnValue?: unknown;\n}\n\nexport interface Balance {\n address: string;\n balance: string;\n nonce: string;\n}\n\nexport interface ValidatorInfo {\n address: string;\n stake: string;\n bondedAt: string;\n pubKeySize: number;\n}\n\nexport interface ViewCallResult {\n ok: boolean;\n reason?: string;\n returnValue?: unknown;\n gasUsed?: string;\n events?: Array<{ name: string; data: unknown }>;\n}\n\nexport interface TxResult {\n accepted: boolean;\n reason?: string;\n txHash?: string;\n}\n\nexport interface Metadata {\n chainId: string;\n chainName: string;\n chainIdDecimal: string;\n currentBlock: string;\n nativeCurrency: { name: string; symbol: string; decimals: number };\n rpcUrls: string[];\n blockExplorerUrls: string[];\n faucetUrl: string;\n}\n\nexport class AsentumClient {\n readonly rpcUrl: string;\n\n constructor(rpcUrl: string) {\n this.rpcUrl = rpcUrl.replace(/\\/$/, '');\n }\n\n // ---------------------------------------------------------------------------\n // Chain reads\n // ---------------------------------------------------------------------------\n\n /** Get chain info including the latest block header. */\n async getChainInfo(): Promise<ChainInfo> {\n const raw = await this.get<ChainInfo & { height: string }>('/chain');\n return { ...raw, height: Number(BigInt(raw.height)) };\n }\n\n /** Get the current block height. */\n async getBlockNumber(): Promise<number> {\n const info = await this.getChainInfo();\n return info.height;\n }\n\n /** Get the chain ID as a bigint. */\n async getChainId(): Promise<bigint> {\n const info = await this.getChainInfo();\n return BigInt(info.chainId);\n }\n\n /** Get a block by number, including transactions and receipts. */\n async getBlock(number: number | bigint): Promise<Block | null> {\n try {\n return await this.get<Block>(`/block/${number}`);\n } catch {\n return null;\n }\n }\n\n /** Get the balance and nonce for an address. */\n async getBalance(address: string): Promise<Balance> {\n return this.get<Balance>(`/balance/${address}`);\n }\n\n /** Get the nonce for an address (shorthand for getBalance().nonce). */\n async getNonce(address: string): Promise<bigint> {\n const bal = await this.getBalance(address);\n return BigInt(bal.nonce);\n }\n\n /** Get the receipt for a transaction by hash. */\n async getReceipt(txHash: string): Promise<Receipt | null> {\n try {\n const r = await this.get<Receipt | { error: string; txHash: string }>(`/receipts/${txHash}`);\n // The chain returns 200 OK with { error: \"receipt not found\", txHash }\n // when a tx isn't yet mined. Treat that as \"not found\" so callers\n // (notably tx.wait's polling loop) can keep waiting.\n if (r && typeof r === 'object' && 'error' in r) return null;\n return r as Receipt;\n } catch {\n return null;\n }\n }\n\n /** Get the source code of a deployed contract (hex-encoded). */\n async getCode(address: string): Promise<string> {\n const res = await this.jsonRpc<string>('eth_getCode', [address, 'latest']);\n return res;\n }\n\n /** Get the source code of a deployed contract as a UTF-8 string. */\n async getContractSource(address: string): Promise<string | null> {\n const hex = await this.getCode(address);\n if (!hex || hex === '0x' || hex.length <= 2) return null;\n const raw = hex.startsWith('0x') ? hex.slice(2) : hex;\n const bytes = new Uint8Array(raw.length / 2);\n for (let i = 0; i < bytes.length; i++) {\n bytes[i] = parseInt(raw.substr(i * 2, 2), 16);\n }\n return new TextDecoder().decode(bytes);\n }\n\n /** Call a contract view function (read-only, no transaction). */\n async viewCall(contract: string, method: string, args: unknown[] = []): Promise<ViewCallResult> {\n return this.post<ViewCallResult>('/view', { contract, method, args });\n }\n\n /** Get the current active validator set. */\n async getValidators(): Promise<{ count: number; validators: ValidatorInfo[] }> {\n return this.get('/validators');\n }\n\n /** Get the chain metadata (EIP-3085 shape). */\n async getMetadata(): Promise<Metadata> {\n return this.get<Metadata>('/metadata');\n }\n\n /** Health check. */\n async isHealthy(): Promise<boolean> {\n try {\n const res = await this.get<{ status: string }>('/health');\n return res.status === 'ok';\n } catch {\n return false;\n }\n }\n\n /** Readiness check (chain advancing). */\n async isReady(): Promise<boolean> {\n try {\n await fetch(`${this.rpcUrl}/ready`);\n return true;\n } catch {\n return false;\n }\n }\n\n /** Request test ASE from the faucet. */\n async faucet(to: string, amount: string = '100000000000000000000'): Promise<TxResult> {\n return this.post<TxResult>('/dev/faucet', { to, amount });\n }\n\n /** Submit a raw signed transaction (hex-encoded SSZ bytes). */\n async submitRawTx(rawTxHex: string): Promise<TxResult> {\n return this.post<TxResult>('/tx', { rawTx: rawTxHex });\n }\n\n // ---------------------------------------------------------------------------\n // Ethereum JSON-RPC (subset)\n // ---------------------------------------------------------------------------\n\n /** Send a raw JSON-RPC request. */\n async jsonRpc<T>(method: string, params: unknown[] = []): Promise<T> {\n const res = await fetch(`${this.rpcUrl}/`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }),\n });\n if (!res.ok) throw new Error(`JSON-RPC ${method} failed: ${res.status}`);\n const body = (await res.json()) as { result?: T; error?: { message: string } };\n if (body.error) throw new Error(`JSON-RPC error: ${body.error.message}`);\n return body.result as T;\n }\n\n // ---------------------------------------------------------------------------\n // Internal HTTP helpers\n // ---------------------------------------------------------------------------\n\n private async get<T>(path: string): Promise<T> {\n const res = await fetch(`${this.rpcUrl}${path}`);\n if (!res.ok) throw new Error(`GET ${path} failed: ${res.status} ${res.statusText}`);\n return (await res.json()) as T;\n }\n\n private async post<T>(path: string, body: unknown): Promise<T> {\n const res = await fetch(`${this.rpcUrl}${path}`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(body),\n });\n if (!res.ok) throw new Error(`POST ${path} failed: ${res.status} ${res.statusText}`);\n return (await res.json()) as T;\n }\n}\n","// Copyright 2026 The AsentumChain Contributors\n// SPDX-License-Identifier: Apache-2.0\n\n/**\n * AsentumWallet — a keypair-backed client that can sign and submit\n * transactions. Extends AsentumClient with signing capabilities.\n *\n * Usage:\n *\n * // Create a random wallet\n * const wallet = AsentumWallet.create(client);\n *\n * // Or from an existing private key (hex)\n * const wallet = AsentumWallet.fromSecretKey(client, '0x...');\n *\n * // Or from a 32-byte seed\n * const wallet = AsentumWallet.fromSeed(client, seed);\n *\n * // Send ASE\n * const tx = await wallet.sendTransfer({ to: '0x...', amount: '1.5' });\n *\n * // Deploy a contract\n * const contract = await wallet.deploy('function init() { ... }');\n *\n * // Call a contract method (write)\n * const tx2 = await wallet.sendCall({\n * to: contract.address,\n * method: 'transfer',\n * args: ['0xbob...', '100'],\n * });\n */\n\nimport {\n generateKeypair,\n addressFromPublicKey,\n type Dilithium3Keypair,\n} from '@asentum/crypto';\nimport {\n SignedTransactionSchema,\n TransactionBodySchema,\n} from '@asentum/types';\nimport { blake3, sign } from '@asentum/crypto';\nimport { AsentumClient, type TxResult } from './client.js';\nimport { AsentumContract } from './contract.js';\n\n// ---------------------------------------------------------------------------\n// Hex helpers\n// ---------------------------------------------------------------------------\n\nfunction bytesToHex(bytes: Uint8Array): string {\n let hex = '0x';\n for (let i = 0; i < bytes.length; i++) {\n hex += (bytes[i] ?? 0).toString(16).padStart(2, '0');\n }\n return hex;\n}\n\nfunction hexToBytes(hex: string): Uint8Array {\n let h = hex.startsWith('0x') || hex.startsWith('0X') ? hex.slice(2) : hex;\n if (h.length % 2 !== 0) h = '0' + h;\n const out = new Uint8Array(h.length / 2);\n for (let i = 0; i < out.length; i++) {\n out[i] = parseInt(h.slice(i * 2, i * 2 + 2), 16);\n }\n return out;\n}\n\nfunction hexToAddress20(hex: string): Uint8Array {\n const bytes = hexToBytes(hex);\n if (bytes.length !== 20) throw new Error(`expected 20-byte address, got ${bytes.length}`);\n return bytes;\n}\n\n// ---------------------------------------------------------------------------\n// Amount parsing\n// ---------------------------------------------------------------------------\n\n/**\n * Parse an ASE amount string into wei (bigint).\n * Accepts: \"1\", \"1.5\", \"0.001\", or a raw wei integer string.\n */\nexport function parseAse(amount: string | number | bigint): bigint {\n if (typeof amount === 'bigint') return amount;\n if (typeof amount === 'number') return BigInt(Math.floor(amount * 1e18));\n const s = amount.trim();\n if (/^\\d+$/.test(s)) {\n // If it's a very large integer, treat as wei. Otherwise ASE.\n if (s.length > 18) return BigInt(s); // likely wei\n return BigInt(s) * 1000000000000000000n; // ASE → wei\n }\n if (/^\\d+\\.\\d{1,18}$/.test(s)) {\n const [whole, frac = ''] = s.split('.');\n const padded = frac.padEnd(18, '0').slice(0, 18);\n return BigInt(whole + padded);\n }\n throw new Error(`invalid amount: \"${amount}\" — use \"1\", \"1.5\", or a wei integer`);\n}\n\n/**\n * Format a wei bigint as a human-readable ASE string.\n */\nexport function formatAse(wei: bigint | string): string {\n const w = typeof wei === 'bigint' ? wei : BigInt(wei);\n const whole = w / 1000000000000000000n;\n const frac = w % 1000000000000000000n;\n if (frac === 0n) return whole.toString();\n const fracStr = frac.toString().padStart(18, '0').replace(/0+$/, '');\n return `${whole}.${fracStr}`;\n}\n\n// ---------------------------------------------------------------------------\n// Transaction building\n// ---------------------------------------------------------------------------\n\nexport interface SendTransferOpts {\n /** Recipient address (0x-prefixed, 40 hex chars). */\n to: string;\n /** Amount in ASE (e.g. \"1.5\") or wei (bigint). */\n amount: string | number | bigint;\n /** Override the gas limit. Default: 21,000. */\n gasLimit?: bigint;\n /** Override the nonce. Default: auto-fetched from the chain. */\n nonce?: bigint;\n}\n\nexport interface SendCallOpts {\n /** Contract address (0x-prefixed, 40 hex chars). */\n to: string;\n /** Method name to call on the contract. */\n method: string;\n /** Method arguments (passed as JSON to the contract). */\n args?: unknown[];\n /** ASE to attach to the call (default: 0). */\n value?: string | number | bigint;\n /** Override the gas limit. Default: 2,000,000. */\n gasLimit?: bigint;\n /** Override the nonce. Default: auto-fetched. */\n nonce?: bigint;\n}\n\nexport interface DeployOpts {\n /** The JavaScript source code of the contract. */\n source: string;\n /** ASE to attach to the deploy (default: 0). */\n value?: string | number | bigint;\n /** Override the gas limit. Default: based on source length. */\n gasLimit?: bigint;\n /** Override the nonce. Default: auto-fetched. */\n nonce?: bigint;\n}\n\nexport interface SentTx {\n /** The transaction hash (0x-prefixed). */\n hash: string;\n /** Wait for the transaction to be included in a block. */\n wait(timeoutMs?: number): Promise<import('./client.js').Receipt>;\n}\n\n// ---------------------------------------------------------------------------\n// AsentumWallet\n// ---------------------------------------------------------------------------\n\nexport class AsentumWallet {\n readonly client: AsentumClient;\n readonly keypair: Dilithium3Keypair;\n readonly address: string;\n\n private constructor(client: AsentumClient, keypair: Dilithium3Keypair) {\n this.client = client;\n this.keypair = keypair;\n this.address = addressFromPublicKey(keypair.publicKey);\n }\n\n /** Create a wallet with a random Dilithium3 keypair. */\n static create(client: AsentumClient): AsentumWallet {\n const seed = new Uint8Array(32);\n crypto.getRandomValues(seed);\n const keypair = generateKeypair(seed);\n return new AsentumWallet(client, keypair);\n }\n\n /** Create a wallet from a 32-byte seed. */\n static fromSeed(client: AsentumClient, seed: Uint8Array): AsentumWallet {\n if (seed.length < 32) throw new Error('seed must be at least 32 bytes');\n const keypair = generateKeypair(seed.slice(0, 32));\n return new AsentumWallet(client, keypair);\n }\n\n /** Create a wallet from a hex-encoded secret key. */\n static fromSecretKey(client: AsentumClient, secretKeyHex: string, publicKeyHex: string): AsentumWallet {\n return new AsentumWallet(client, {\n secretKey: hexToBytes(secretKeyHex),\n publicKey: hexToBytes(publicKeyHex),\n });\n }\n\n /** Get the secret key as a hex string (for export/backup). */\n get secretKeyHex(): string {\n return bytesToHex(this.keypair.secretKey);\n }\n\n /** Get the public key as a hex string. */\n get publicKeyHex(): string {\n return bytesToHex(this.keypair.publicKey);\n }\n\n /** Get the current balance in wei. */\n async getBalance(): Promise<bigint> {\n const bal = await this.client.getBalance(this.address);\n return BigInt(bal.balance);\n }\n\n /** Get the current nonce. */\n async getNonce(): Promise<bigint> {\n return this.client.getNonce(this.address);\n }\n\n /** Request test ASE from the faucet. */\n async requestFaucet(amount: string = '100000000000000000000'): Promise<TxResult> {\n return this.client.faucet(this.address, amount);\n }\n\n // ---------------------------------------------------------------------------\n // Sending transactions\n // ---------------------------------------------------------------------------\n\n /** Send ASE to another address. */\n async sendTransfer(opts: SendTransferOpts): Promise<SentTx> {\n const chainId = await this.client.getChainId();\n const nonce = opts.nonce ?? await this.getNonce();\n const value = parseAse(opts.amount);\n\n const body = {\n chainId,\n nonce,\n maxPriorityFeePerGas: 0n,\n maxFeePerGas: 1n,\n gasLimit: opts.gasLimit ?? 21_000n,\n to: hexToAddress20(opts.to),\n value,\n data: new Uint8Array(0),\n };\n\n return this.signAndSubmit(body);\n }\n\n /** Call a method on a deployed contract (state-changing). */\n async sendCall(opts: SendCallOpts): Promise<SentTx> {\n const chainId = await this.client.getChainId();\n const nonce = opts.nonce ?? await this.getNonce();\n const data = new TextEncoder().encode(\n JSON.stringify({ method: opts.method, args: opts.args ?? [] }),\n );\n\n const body = {\n chainId,\n nonce,\n maxPriorityFeePerGas: 0n,\n maxFeePerGas: 1n,\n gasLimit: opts.gasLimit ?? 2_000_000n,\n to: hexToAddress20(opts.to),\n value: opts.value ? parseAse(opts.value) : 0n,\n data,\n };\n\n return this.signAndSubmit(body);\n }\n\n /** Deploy a new smart contract. Returns an AsentumContract instance. */\n async deploy(sourceOrOpts: string | DeployOpts): Promise<AsentumContract> {\n const opts: DeployOpts = typeof sourceOrOpts === 'string'\n ? { source: sourceOrOpts }\n : sourceOrOpts;\n\n const chainId = await this.client.getChainId();\n const nonce = opts.nonce ?? await this.getNonce();\n const data = new TextEncoder().encode(opts.source);\n const gasLimit = opts.gasLimit ?? BigInt(Math.max(2_000_000, 1000 * opts.source.length));\n\n const body = {\n chainId,\n nonce,\n maxPriorityFeePerGas: 0n,\n maxFeePerGas: 1n,\n gasLimit,\n to: new Uint8Array(20), // zero address = deploy\n value: opts.value ? parseAse(opts.value) : 0n,\n data,\n };\n\n const sentTx = await this.signAndSubmit(body);\n\n // Derive the contract address: blake3(sender || nonce), take first 20 bytes.\n const senderBytes = hexToAddress20(this.address);\n const nonceBytes = new Uint8Array(8);\n new DataView(nonceBytes.buffer).setBigUint64(0, nonce, true);\n const combined = new Uint8Array(20 + 8);\n combined.set(senderBytes);\n combined.set(nonceBytes, 20);\n const hash = blake3(combined);\n const contractAddress = bytesToHex(hash.slice(0, 20));\n\n return new AsentumContract(this.client, contractAddress, sentTx, this);\n }\n\n // ---------------------------------------------------------------------------\n // Internal: sign + submit\n // ---------------------------------------------------------------------------\n\n private async signAndSubmit(body: {\n chainId: bigint;\n nonce: bigint;\n maxPriorityFeePerGas: bigint;\n maxFeePerGas: bigint;\n gasLimit: bigint;\n to: Uint8Array;\n value: bigint;\n data: Uint8Array;\n }): Promise<SentTx> {\n // Serialize → hash → sign → encode → submit\n const bodyBytes = TransactionBodySchema.serialize(body);\n const digest = blake3(bodyBytes);\n const signature = sign(digest, this.keypair.secretKey);\n const signedTx = {\n body,\n publicKey: this.keypair.publicKey,\n signature,\n };\n const rawTxHex = bytesToHex(SignedTransactionSchema.serialize(signedTx));\n const result = await this.client.submitRawTx(rawTxHex);\n\n if (!result.accepted) {\n throw new Error(`transaction rejected: ${result.reason || 'unknown reason'}`);\n }\n\n const txHash = result.txHash ?? '(unknown)';\n const client = this.client;\n\n return {\n hash: txHash,\n async wait(timeoutMs = 15_000): Promise<import('./client.js').Receipt> {\n const start = Date.now();\n while (Date.now() - start < timeoutMs) {\n const receipt = await client.getReceipt(txHash);\n if (receipt) return receipt;\n await new Promise((r) => setTimeout(r, 1000));\n }\n throw new Error(`transaction ${txHash} not confirmed within ${timeoutMs}ms`);\n },\n };\n }\n}\n","// Copyright 2026 The AsentumChain Contributors\n// SPDX-License-Identifier: Apache-2.0\n\n/**\n * AsentumContract — a deployed contract instance that wraps view calls\n * and write transactions.\n *\n * Usage:\n *\n * // Deploy via a wallet\n * const contract = await wallet.deploy(source);\n * console.log(contract.address);\n *\n * // Or wrap an existing deployed contract\n * const contract = new AsentumContract(client, '0xabc...');\n *\n * // Read (free, no signature)\n * const name = await contract.view('name');\n * const balance = await contract.view('balanceOf', ['0x...']);\n *\n * // Write (requires a wallet)\n * const tx = await contract.send('transfer', ['0x...', '1000']);\n * const receipt = await tx.wait();\n */\n\nimport { AsentumClient, type Receipt, type ViewCallResult } from './client.js';\nimport type { AsentumWallet, SentTx } from './wallet.js';\n\nexport class AsentumContract {\n readonly client: AsentumClient;\n readonly address: string;\n /** The deploy tx, if this contract was deployed in this session. */\n readonly deployTx?: SentTx;\n /** The wallet used to deploy this contract, if any. Used as default signer for send(). */\n private wallet?: AsentumWallet;\n\n constructor(\n client: AsentumClient,\n address: string,\n deployTx?: SentTx,\n wallet?: AsentumWallet,\n ) {\n this.client = client;\n this.address = address;\n this.deployTx = deployTx;\n this.wallet = wallet;\n }\n\n /**\n * Call a view function (read-only, free, no transaction).\n *\n * @param method - The function name to call.\n * @param args - Arguments to pass to the function.\n * @returns The return value of the function.\n */\n async view(method: string, args: unknown[] = []): Promise<unknown> {\n const result = await this.client.viewCall(this.address, method, args);\n if (!result.ok) {\n throw new Error(`view call ${method}() failed: ${result.reason || 'unknown'}`);\n }\n return result.returnValue;\n }\n\n /**\n * Call a view function and return the full result including gas + events.\n */\n async viewFull(method: string, args: unknown[] = []): Promise<ViewCallResult> {\n return this.client.viewCall(this.address, method, args);\n }\n\n /**\n * Send a state-changing transaction to the contract.\n *\n * @param method - The function name to call.\n * @param args - Arguments to pass.\n * @param opts - Optional: value to attach, gas limit, nonce, wallet override.\n * @returns A SentTx with `.hash` and `.wait()`.\n */\n async send(\n method: string,\n args: unknown[] = [],\n opts: {\n value?: string | number | bigint;\n gasLimit?: bigint;\n nonce?: bigint;\n wallet?: AsentumWallet;\n } = {},\n ): Promise<SentTx> {\n const signer = opts.wallet ?? this.wallet;\n if (!signer) {\n throw new Error(\n 'no wallet available — pass a wallet in opts or create the contract via wallet.deploy()',\n );\n }\n return signer.sendCall({\n to: this.address,\n method,\n args,\n value: opts.value,\n gasLimit: opts.gasLimit,\n nonce: opts.nonce,\n });\n }\n\n /**\n * Attach a wallet to this contract for future send() calls.\n */\n connect(wallet: AsentumWallet): AsentumContract {\n return new AsentumContract(this.client, this.address, this.deployTx, wallet);\n }\n\n /**\n * Get the source code of this contract as a UTF-8 string.\n * Returns null if the address has no deployed code.\n */\n async getSource(): Promise<string | null> {\n return this.client.getContractSource(this.address);\n }\n\n /**\n * Get the ASE balance of this contract.\n */\n async getBalance(): Promise<bigint> {\n const bal = await this.client.getBalance(this.address);\n return BigInt(bal.balance);\n }\n\n /**\n * Wait for the deploy transaction to be confirmed (if this contract\n * was deployed in this session). Useful after `wallet.deploy()`.\n */\n async waitForDeploy(timeoutMs = 15_000): Promise<Receipt> {\n if (!this.deployTx) {\n throw new Error('this contract was not deployed in this session — no deploy tx to wait for');\n }\n return this.deployTx.wait(timeoutMs);\n }\n}\n"],"mappings":";AA6GO,IAAM,gBAAN,MAAoB;AAAA,EAChB;AAAA,EAET,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WAAW;AACxB,aAAS,IAAI,YAAY,EAAE;AAC3B,UAAM,OAAO,OAAO,QAAQ;AAC5B,UAAM,kBAAkB,WAAW,KAAK,MAAM,GAAG,EAAE,CAAC;AAEpD,WAAO,IAAI,gBAAgB,KAAK,QAAQ,iBAAiB,QAAQ,IAAI;AAAA,EACvE;AAAA;AAAA;AAAA;AAAA,EAMA,MAAc,cAAc,MASR;AAElB,UAAM,YAAY,sBAAsB,UAAU,IAAI;AACtD,UAAM,SAAS,OAAO,SAAS;AAC/B,UAAM,YAAY,KAAK,QAAQ,KAAK,QAAQ,SAAS;AACrD,UAAM,WAAW;AAAA,MACf;AAAA,MACA,WAAW,KAAK,QAAQ;AAAA,MACxB;AAAA,IACF;AACA,UAAM,WAAW,WAAW,wBAAwB,UAAU,QAAQ,CAAC;AACvE,UAAM,SAAS,MAAM,KAAK,OAAO,YAAY,QAAQ;AAErD,QAAI,CAAC,OAAO,UAAU;AACpB,YAAM,IAAI,MAAM,yBAAyB,OAAO,UAAU,gBAAgB,EAAE;AAAA,IAC9E;AAEA,UAAM,SAAS,OAAO,UAAU;AAChC,UAAM,SAAS,KAAK;AAEpB,WAAO;AAAA,MACL,MAAM;AAAA,MACN,MAAM,KAAK,YAAY,MAAgD;AACrE,cAAM,QAAQ,KAAK,IAAI;AACvB,eAAO,KAAK,IAAI,IAAI,QAAQ,WAAW;AACrC,gBAAM,UAAU,MAAM,OAAO,WAAW,MAAM;AAC9C,cAAI,QAAS,QAAO;AACpB,gBAAM,IAAI,QAAQ,CAAC,MAAM,WAAW,GAAG,GAAI,CAAC;AAAA,QAC9C;AACA,cAAM,IAAI,MAAM,eAAe,MAAM,yBAAyB,SAAS,IAAI;AAAA,MAC7E;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
1
+ {"version":3,"sources":["../src/internal/crypto.ts","../src/ase1.ts","../src/errors.ts","../src/http.ts","../src/client.ts","../src/contract.ts","../src/internal/tx.ts","../src/units.ts","../src/wallet.ts","../src/index.ts"],"sourcesContent":["// Copyright 2026 The AsentumChain Contributors\n// SPDX-License-Identifier: Apache-2.0\n\n/**\n * The few crypto primitives the SDK needs, kept inside the package so the\n * published SDK does not depend on unpublished versions of @asentum/crypto.\n *\n * Source of truth: AsentumChain packages/crypto (signing.ts, hashing.ts,\n * bech32.ts, address.ts). The behaviour here must match it byte for byte;\n * test/vendor-parity.test.ts checks that whenever the monorepo is present.\n */\n\nimport { ml_dsa65 } from '@noble/post-quantum/ml-dsa';\nimport { blake3 as nobleBlake3 } from '@noble/hashes/blake3';\n\nexport const DILITHIUM3_SEED_BYTES = 32;\nexport const DILITHIUM3_PUBLIC_KEY_BYTES = 1952;\nexport const DILITHIUM3_SIGNATURE_BYTES = 3309;\nexport const ADDRESS_BYTES = 20;\nexport const ASE_HRP = 'ase';\n\nexport interface Dilithium3Keypair {\n publicKey: Uint8Array;\n secretKey: Uint8Array;\n}\n\n/** ML-DSA-65 (Dilithium3) keypair from a 32-byte seed (random when omitted). */\nexport function generateKeypair(seed?: Uint8Array): Dilithium3Keypair {\n let s = seed;\n if (!s) {\n s = new Uint8Array(DILITHIUM3_SEED_BYTES);\n globalThis.crypto.getRandomValues(s);\n }\n if (s.length !== DILITHIUM3_SEED_BYTES) {\n throw new Error(`Dilithium3 seed must be ${DILITHIUM3_SEED_BYTES} bytes, got ${s.length}`);\n }\n const keys = ml_dsa65.keygen(s);\n return { publicKey: keys.publicKey, secretKey: keys.secretKey };\n}\n\nexport function sign(message: Uint8Array, secretKey: Uint8Array): Uint8Array {\n return ml_dsa65.sign(secretKey, message);\n}\n\nexport function verify(message: Uint8Array, signature: Uint8Array, publicKey: Uint8Array): boolean {\n try {\n return ml_dsa65.verify(publicKey, message, signature);\n } catch {\n return false;\n }\n}\n\nexport function blake3(data: Uint8Array, dkLen = 32): Uint8Array {\n return nobleBlake3(data, { dkLen });\n}\n\n/** The 20 address bytes of a public key: BLAKE3(publicKey)[0:20]. */\nexport function addressBytesFromPublicKey(publicKey: Uint8Array): Uint8Array {\n return blake3(publicKey).slice(0, ADDRESS_BYTES);\n}\n\n// ---------------------------------------------------------------------------\n// bech32 (BIP-173), HRP \"ase\"\n// ---------------------------------------------------------------------------\n\nconst CHARSET = 'qpzry9x8gf2tvdw0s3jn54khce6mua7l';\nconst GENERATOR = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3];\n\nfunction polymod(values: number[]): number {\n let chk = 1;\n for (const v of values) {\n const top = chk >> 25;\n chk = ((chk & 0x1ffffff) << 5) ^ v;\n for (let i = 0; i < 5; i++) if ((top >> i) & 1) chk ^= GENERATOR[i]!;\n }\n return chk;\n}\n\nfunction hrpExpand(hrp: string): number[] {\n const ret: number[] = [];\n for (let i = 0; i < hrp.length; i++) ret.push(hrp.charCodeAt(i) >> 5);\n ret.push(0);\n for (let i = 0; i < hrp.length; i++) ret.push(hrp.charCodeAt(i) & 31);\n return ret;\n}\n\nfunction convertBits(data: ArrayLike<number>, fromBits: number, toBits: number, pad: boolean): number[] | null {\n let acc = 0;\n let bits = 0;\n const ret: number[] = [];\n const maxv = (1 << toBits) - 1;\n const maxAcc = (1 << (fromBits + toBits - 1)) - 1;\n for (let i = 0; i < data.length; i++) {\n const value = data[i]!;\n if (value < 0 || value >> fromBits !== 0) return null;\n acc = ((acc << fromBits) | value) & maxAcc;\n bits += fromBits;\n while (bits >= toBits) {\n bits -= toBits;\n ret.push((acc >> bits) & maxv);\n }\n }\n if (pad) {\n if (bits > 0) ret.push((acc << (toBits - bits)) & maxv);\n } else if (bits >= fromBits || ((acc << (toBits - bits)) & maxv) !== 0) {\n return null;\n }\n return ret;\n}\n\nexport function bech32Encode(hrp: string, bytes: Uint8Array): string {\n const data = convertBits(bytes, 8, 5, true);\n if (!data) throw new Error('bech32: convertBits failed on encode');\n const values = hrpExpand(hrp).concat(data).concat([0, 0, 0, 0, 0, 0]);\n const mod = polymod(values) ^ 1;\n let out = `${hrp}1`;\n for (const d of data) out += CHARSET.charAt(d);\n for (let p = 0; p < 6; p++) out += CHARSET.charAt((mod >> (5 * (5 - p))) & 31);\n return out;\n}\n\nexport function bech32Decode(input: string): { hrp: string; bytes: Uint8Array } | null {\n if (typeof input !== 'string' || input.length < 8 || input.length > 90) return null;\n const lower = input.toLowerCase();\n if (input !== lower && input !== input.toUpperCase()) return null; // mixed case\n const sep = lower.lastIndexOf('1');\n if (sep < 1 || sep + 7 > lower.length) return null;\n const hrp = lower.slice(0, sep);\n const data: number[] = [];\n for (const c of lower.slice(sep + 1)) {\n const v = CHARSET.indexOf(c);\n if (v < 0) return null;\n data.push(v);\n }\n if (polymod(hrpExpand(hrp).concat(data)) !== 1) return null;\n const payload = convertBits(data.slice(0, -6), 5, 8, false);\n if (!payload) return null;\n return { hrp, bytes: new Uint8Array(payload) };\n}\n\n// ---------------------------------------------------------------------------\n// hex\n// ---------------------------------------------------------------------------\n\nexport function bytesToHex(bytes: Uint8Array): string {\n let hex = '0x';\n for (let i = 0; i < bytes.length; i++) hex += (bytes[i] ?? 0).toString(16).padStart(2, '0');\n return hex;\n}\n\n/** Strict hex decode: optional 0x, even length, hex digits only. */\nexport function hexToBytes(hex: string): Uint8Array {\n const h = hex.startsWith('0x') || hex.startsWith('0X') ? hex.slice(2) : hex;\n if (h.length % 2 !== 0) throw new Error('invalid hex: odd number of characters');\n if (!/^[0-9a-fA-F]*$/.test(h)) throw new Error('invalid hex: non-hex character');\n const out = new Uint8Array(h.length / 2);\n for (let i = 0; i < out.length; i++) out[i] = parseInt(h.slice(i * 2, i * 2 + 2), 16);\n return out;\n}\n","// Copyright 2026 The AsentumChain Contributors\n// SPDX-License-Identifier: Apache-2.0\n\n/**\n * Address helpers. Asentum addresses are 20 bytes, shown to people as\n * `ase1...` (bech32, HRP \"ase\") and used as lowercase `0x...` hex inside\n * contracts (`msg.sender` is hex, and contracts store accounts as hex).\n *\n * The SDK accepts either form everywhere and returns ase1 for every address\n * it surfaces. Names match @asentum/connect where they overlap\n * (isAse1, ase1ToHex, hexToAse1, toAse1, shortAse1, ase1ArgsToHex).\n */\n\nimport { ADDRESS_BYTES, ASE_HRP, bech32Decode, bech32Encode, bytesToHex } from './internal/crypto.js';\n\nconst HEX_ADDR = /^0x[0-9a-fA-F]{40}$/;\n\n/**\n * If `s` is a valid ase1 address (bech32 checksum OK, HRP exactly \"ase\",\n * 20-byte payload, single case, no surrounding whitespace) return its\n * lowercase `0x` hex form. Otherwise return null.\n */\nexport function ase1ToHexOrNull(s: string): string | null {\n if (typeof s !== 'string') return null;\n if (s.length < 4 || s.slice(0, 4).toLowerCase() !== `${ASE_HRP}1`) return null;\n const decoded = bech32Decode(s);\n if (!decoded || decoded.hrp !== ASE_HRP || decoded.bytes.length !== ADDRESS_BYTES) return null;\n return bytesToHex(decoded.bytes);\n}\n\n/** ase1 to lowercase 0x hex, or null when the checksum or length is wrong. Same as ase1ToHexOrNull. */\nexport function ase1ToHex(s: string): string | null {\n return ase1ToHexOrNull(s);\n}\n\n/** True for a well-formed ase1 address with a valid checksum. */\nexport function isAse1(s: unknown): boolean {\n return typeof s === 'string' && ase1ToHexOrNull(s) !== null;\n}\n\n/** True for a 0x hex address (20 bytes, any case). */\nexport function isHexAddress(s: unknown): boolean {\n return typeof s === 'string' && HEX_ADDR.test(s);\n}\n\n/** True for either accepted address form. */\nexport function isAddress(s: unknown): boolean {\n return isAse1(s) || isHexAddress(s);\n}\n\n/** 0x hex (20 bytes) to ase1. Returns '' when the input is not a hex address (same as @asentum/connect). */\nexport function hexToAse1(hex: string): string {\n if (!isHexAddress(hex)) return '';\n return bech32Encode(ASE_HRP, addressToBytes(hex));\n}\n\n/**\n * Any address (hex or ase1) to lowercase ase1, for display. Input that is\n * not an address is returned unchanged (empty string for null/undefined).\n */\nexport function toAse1(a: string | null | undefined): string {\n if (a === null || a === undefined) return '';\n const s = String(a).trim();\n if (isHexAddress(s)) return hexToAse1(s);\n if (isAse1(s)) return s.toLowerCase();\n return s;\n}\n\n/**\n * Any address (hex or ase1) to lowercase 0x hex: the form contracts use.\n * Throws InvalidAddress-style Error on anything else.\n */\nexport function toHexAddress(a: string): string {\n return bytesToHex(addressToBytes(a));\n}\n\n/** Parse either address form into 20 raw bytes. Throws on invalid input. */\nexport function addressToBytes(a: string): Uint8Array {\n if (typeof a !== 'string' || a.trim() === '') throw new Error('invalid address: empty');\n const s = a.trim();\n if (isHexAddress(s)) {\n const out = new Uint8Array(ADDRESS_BYTES);\n for (let i = 0; i < ADDRESS_BYTES; i++) out[i] = parseInt(s.slice(2 + i * 2, 4 + i * 2), 16);\n return out;\n }\n const hex = ase1ToHexOrNull(s);\n if (hex) return addressToBytes(hex);\n throw new Error(`invalid address: \"${s.length > 14 ? s.slice(0, 14) + '...' : s}\" (expected ase1... or 0x + 40 hex)`);\n}\n\n/** 20 raw bytes to ase1. */\nexport function bytesToAse1(bytes: Uint8Array): string {\n if (bytes.length !== ADDRESS_BYTES) throw new Error(`address must be ${ADDRESS_BYTES} bytes, got ${bytes.length}`);\n return bech32Encode(ASE_HRP, bytes);\n}\n\n/** Shortened ase1 for buttons and chips, e.g. ase1qxyz12...ab34cd. */\nexport function shortAse1(a: string | null | undefined, lead = 10, tail = 6): string {\n const s = toAse1(a);\n return s.length > lead + tail ? `${s.slice(0, lead)}...${s.slice(-tail)}` : s;\n}\n\n/** Hex address to ase1, leaving anything else (null, '', non-address) as is. Internal use for node fields. */\nexport function maybeAse1<T>(v: T): T {\n return (typeof v === 'string' && isHexAddress(v) ? hexToAse1(v) : v) as T;\n}\n\nfunction isPlainObject(v: unknown): v is Record<string, unknown> {\n if (v === null || typeof v !== 'object') return false;\n const proto = Object.getPrototypeOf(v);\n return proto === Object.prototype || proto === null;\n}\n\n/**\n * Recursively walk contract call arguments (arrays and plain objects,\n * values only, never keys) and replace every string that is a valid ase1\n * address with its lowercase `0x` hex form. Everything else is returned\n * unchanged. The input is never mutated; a new structure is returned.\n * Idempotent: hex input stays hex.\n *\n * Why: contract code runs with hex. `msg.sender` is lowercase `0x...`, so an\n * ase1 string stored by a contract would never match that person's sender.\n * The SDK applies this to every call it signs and every view it sends.\n */\nexport function ase1ArgsToHex<T>(value: T): T {\n if (typeof value === 'string') {\n return (ase1ToHexOrNull(value) ?? value) as T;\n }\n if (Array.isArray(value)) {\n return value.map((v) => ase1ArgsToHex(v)) as T;\n }\n if (isPlainObject(value)) {\n const out: Record<string, unknown> = {};\n for (const k of Object.keys(value)) out[k] = ase1ArgsToHex(value[k]);\n return out as T;\n }\n return value;\n}\n","// Copyright 2026 The AsentumChain Contributors\n// SPDX-License-Identifier: Apache-2.0\n\n/**\n * Typed errors. Every error the SDK throws on purpose extends AsentumError,\n * so `err instanceof AsentumError` separates SDK errors from bugs, and the\n * `code` string is stable for switch statements.\n */\n\nimport type { Receipt } from './types.js';\n\nexport type AsentumErrorCode =\n | 'HTTP_ERROR'\n | 'RATE_LIMITED'\n | 'NETWORK_ERROR'\n | 'RPC_ERROR'\n | 'JSON_RPC_ERROR'\n | 'TX_REJECTED'\n | 'TX_FAILED'\n | 'TIMEOUT'\n | 'ABORTED'\n | 'VIEW_FAILED'\n | 'INVALID_ARGUMENT';\n\nexport class AsentumError extends Error {\n readonly code: AsentumErrorCode;\n constructor(code: AsentumErrorCode, message: string, options?: { cause?: unknown }) {\n super(message);\n this.name = 'AsentumError';\n this.code = code;\n if (options && 'cause' in options) (this as { cause?: unknown }).cause = options.cause;\n }\n}\n\n/** The node or gateway answered with a non-2xx HTTP status. */\nexport class HttpError extends AsentumError {\n readonly status: number;\n readonly url: string;\n /** Parsed JSON body when there was one, otherwise the text (the gateway sends HTML for 429). */\n readonly body: unknown;\n constructor(status: number, url: string, body: unknown, message?: string, code: AsentumErrorCode = 'HTTP_ERROR') {\n const detail = body && typeof body === 'object' && 'error' in body ? `: ${String((body as { error: unknown }).error)}` : '';\n super(code, message ?? `HTTP ${status} from ${url}${detail}`);\n this.name = 'HttpError';\n this.status = status;\n this.url = url;\n this.body = body;\n }\n}\n\n/**\n * HTTP 429. The public gateway allows about 25 requests a second per IP and\n * answers 429 with an HTML page and no Retry-After; a node's own block-read\n * budget answers JSON with Retry-After. The SDK already retried with backoff\n * before throwing this.\n */\nexport class RateLimitError extends HttpError {\n /** From the Retry-After header, when the server sent one. */\n readonly retryAfterMs?: number;\n constructor(url: string, body: unknown, retryAfterMs?: number) {\n super(429, url, body, `rate limited (HTTP 429) by ${url}${retryAfterMs ? `, retry after ${retryAfterMs} ms` : ''}`, 'RATE_LIMITED');\n this.name = 'RateLimitError';\n this.retryAfterMs = retryAfterMs;\n }\n}\n\n/** fetch itself failed (DNS, connection reset, CORS, per-request timeout). */\nexport class NetworkError extends AsentumError {\n readonly url: string;\n constructor(url: string, cause: unknown) {\n super('NETWORK_ERROR', `network error calling ${url}: ${cause instanceof Error ? cause.message : String(cause)}`, { cause });\n this.name = 'NetworkError';\n this.url = url;\n }\n}\n\n/**\n * HTTP 200 with an error body. Most node errors look like this: a bad\n * address, a bad tx hash, a governance read that failed. (A missing receipt\n * or block is NOT an error: those methods return null.)\n */\nexport class RpcError extends AsentumError {\n readonly path: string;\n readonly body: unknown;\n constructor(path: string, message: string, body: unknown) {\n super('RPC_ERROR', `${path}: ${message}`);\n this.name = 'RpcError';\n this.path = path;\n this.body = body;\n }\n}\n\n/** A JSON-RPC (POST /) error object. */\nexport class JsonRpcError extends AsentumError {\n readonly rpcCode: number;\n readonly method: string;\n readonly data?: unknown;\n constructor(method: string, rpcCode: number, message: string, data?: unknown) {\n super('JSON_RPC_ERROR', `JSON-RPC ${method} failed (${rpcCode}): ${message}`);\n this.name = 'JsonRpcError';\n this.method = method;\n this.rpcCode = rpcCode;\n this.data = data;\n }\n}\n\n/**\n * POST /tx answered `accepted: false`. The transaction never reached the\n * mempool and will not land. `reason` is the node's text, for example\n * \"stale nonce: account is at 153, tx has 152\" or \"insufficient balance\".\n */\nexport class TxRejectedError extends AsentumError {\n readonly reason: string;\n /** The locally computed hash of the rejected transaction (it is not on chain). */\n readonly txHash?: string;\n constructor(reason: string, txHash?: string) {\n super('TX_REJECTED', `transaction rejected: ${reason || 'unknown reason'}`);\n this.name = 'TxRejectedError';\n this.reason = reason || 'unknown reason';\n this.txHash = txHash;\n }\n /** True when the reason is about the nonce (stale, too far ahead, duplicate nonce). */\n get isNonceError(): boolean {\n return /nonce/i.test(this.reason);\n }\n}\n\n/** The transaction is in a block but ran and failed (`success: false`). */\nexport class TxFailedError extends AsentumError {\n readonly receipt: Receipt;\n constructor(receipt: Receipt) {\n super('TX_FAILED', receipt.error ? `transaction failed on chain: ${receipt.error}` : 'transaction failed on chain');\n this.name = 'TxFailedError';\n this.receipt = receipt;\n }\n}\n\n/**\n * Waiting ran out of time. This is NOT a failure: the transaction may still\n * land. `lastReceipt` is set when it was seen in a block but not final yet.\n */\nexport class TimeoutError extends AsentumError {\n readonly txHash: string;\n readonly lastReceipt: Receipt | null;\n constructor(txHash: string, timeoutMs: number, until: string, lastReceipt: Receipt | null) {\n super(\n 'TIMEOUT',\n lastReceipt\n ? `transaction ${txHash} is in block ${lastReceipt.blockNumber} but was not final within ${timeoutMs} ms`\n : `transaction ${txHash} not ${until === 'final' ? 'final' : 'in a block'} within ${timeoutMs} ms; it may still go through, check it on the explorer before sending again`,\n );\n this.name = 'TimeoutError';\n this.txHash = txHash;\n this.lastReceipt = lastReceipt;\n }\n}\n\n/** The caller's AbortSignal fired. `name` is \"AbortError\", as with fetch. */\nexport class AbortError extends AsentumError {\n constructor(message = 'aborted') {\n super('ABORTED', message);\n this.name = 'AbortError';\n }\n}\n\n/** POST /view answered `ok: false` (method missing, contract threw, bad blockTag). */\nexport class ViewError extends AsentumError {\n readonly method: string;\n readonly reason: string;\n constructor(method: string, reason: string) {\n super('VIEW_FAILED', `view call ${method}() failed: ${reason || 'unknown'}`);\n this.name = 'ViewError';\n this.method = method;\n this.reason = reason || 'unknown';\n }\n}\n","// Copyright 2026 The AsentumChain Contributors\n// SPDX-License-Identifier: Apache-2.0\n\n/**\n * HTTP transport: fetch with per-request timeout, AbortSignal support and\n * retries with backoff on 429 / 5xx / network errors.\n *\n * Backoff: honour Retry-After when present (the node sends it, the gateway\n * does not), otherwise 500 ms, 1 s, 2 s ... capped at 10 s, with jitter.\n */\n\nimport { AbortError, HttpError, NetworkError, RateLimitError } from './errors.js';\n\nconst IN_BROWSER = typeof (globalThis as { document?: unknown }).document !== 'undefined';\n\nexport type FetchLike = (input: string, init?: RequestInit) => Promise<Response>;\n\nexport interface TransportOptions {\n /** fetch implementation. Default: globalThis.fetch. */\n fetch?: FetchLike;\n /** Retries after the first attempt for 429 / 5xx / network errors. Default 3. */\n retries?: number;\n /** Per-request timeout in ms. Default 30,000 (the gateway gives up at 30 s too). */\n requestTimeoutMs?: number;\n /** First backoff delay in ms. Default 500. */\n backoffBaseMs?: number;\n /** Maximum backoff delay in ms. Default 10,000. */\n backoffMaxMs?: number;\n /** Extra headers on every request (for example Authorization for a private RPC). */\n headers?: Record<string, string>;\n}\n\nexport interface RequestOptions {\n method?: 'GET' | 'POST';\n body?: unknown;\n signal?: AbortSignal;\n /** Override the transport's retry count for this request. */\n retries?: number;\n /** Retry on 5xx and network errors (default true). Set false for non-idempotent posts. */\n retryOnServerError?: boolean;\n /** Statuses that return their body instead of throwing (for example 404 on /dev/faucet). */\n allowStatus?: number[];\n}\n\nexport interface HttpResult<T> {\n status: number;\n body: T;\n headers: Headers;\n}\n\nexport function sleep(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise((resolve, reject) => {\n if (signal?.aborted) return reject(new AbortError());\n const t = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort);\n resolve();\n }, ms);\n const onAbort = () => {\n clearTimeout(t);\n reject(new AbortError());\n };\n signal?.addEventListener('abort', onAbort, { once: true });\n });\n}\n\nexport function parseRetryAfter(h: string | null): number | undefined {\n if (!h) return undefined;\n const secs = Number(h);\n if (Number.isFinite(secs) && secs >= 0) return secs * 1000;\n const date = Date.parse(h);\n if (!Number.isNaN(date)) return Math.max(0, date - Date.now());\n return undefined;\n}\n\nexport class Transport {\n readonly baseUrl: string;\n private readonly fetchImpl: FetchLike;\n private readonly retries: number;\n private readonly timeoutMs: number;\n private readonly baseMs: number;\n private readonly maxMs: number;\n private readonly headers: Record<string, string>;\n\n constructor(baseUrl: string, opts: TransportOptions = {}) {\n this.baseUrl = baseUrl.replace(/\\/+$/, '');\n // Look fetch up at call time when not injected, so test doubles that\n // replace globalThis.fetch after construction still apply.\n this.fetchImpl = opts.fetch ?? ((input, init) => globalThis.fetch(input, init));\n this.retries = opts.retries ?? 3;\n this.timeoutMs = opts.requestTimeoutMs ?? 30_000;\n this.baseMs = opts.backoffBaseMs ?? 500;\n this.maxMs = opts.backoffMaxMs ?? 10_000;\n this.headers = opts.headers ?? {};\n }\n\n backoffDelay(attempt: number, retryAfterMs?: number): number {\n if (retryAfterMs !== undefined) return Math.min(this.maxMs, Math.max(retryAfterMs, 0));\n const exp = Math.min(this.maxMs, this.baseMs * 2 ** attempt);\n return Math.round(exp * (0.75 + Math.random() * 0.5));\n }\n\n async request<T>(path: string, opts: RequestOptions = {}): Promise<HttpResult<T>> {\n const url = `${this.baseUrl}${path}`;\n const method = opts.method ?? (opts.body === undefined ? 'GET' : 'POST');\n const retries = opts.retries ?? this.retries;\n const retryOnServerError = opts.retryOnServerError ?? true;\n for (let attempt = 0; ; attempt++) {\n if (opts.signal?.aborted) throw new AbortError();\n let res: Response;\n const ctrl = new AbortController();\n const timer = setTimeout(() => ctrl.abort(), this.timeoutMs);\n const onAbort = () => ctrl.abort();\n opts.signal?.addEventListener('abort', onAbort, { once: true });\n try {\n const headers: Record<string, string> = { accept: 'application/json', ...this.headers };\n if (opts.body !== undefined) headers['content-type'] = 'application/json';\n const init: RequestInit = {\n method,\n headers,\n body: opts.body === undefined ? undefined : JSON.stringify(opts.body),\n signal: ctrl.signal,\n };\n // Browsers may serve a cached receipt or head; ask for a fresh one.\n // Only there: some server runtimes reject the `cache` field.\n if (IN_BROWSER) init.cache = 'no-store';\n res = await this.fetchImpl(url, init);\n } catch (err) {\n clearTimeout(timer);\n opts.signal?.removeEventListener('abort', onAbort);\n if (opts.signal?.aborted) throw new AbortError();\n if (retryOnServerError && attempt < retries) {\n await sleep(this.backoffDelay(attempt), opts.signal);\n continue;\n }\n throw new NetworkError(url, err);\n }\n clearTimeout(timer);\n opts.signal?.removeEventListener('abort', onAbort);\n\n const body = await readBody(res);\n if (res.ok || opts.allowStatus?.includes(res.status)) {\n return { status: res.status, body: body as T, headers: res.headers };\n }\n const retryAfterMs = parseRetryAfter(res.headers?.get?.('retry-after') ?? null);\n // 500 with a JSON body is the node rejecting the request (for example\n // \"invalid JSON body\"), which a retry cannot fix; a non-JSON 500 is a\n // proxy page and worth another try.\n const serverHiccup =\n res.status === 502 || res.status === 503 || res.status === 504 || (res.status === 500 && typeof body === 'string');\n const retryable = res.status === 429 || (retryOnServerError && serverHiccup);\n if (retryable && attempt < retries) {\n await sleep(this.backoffDelay(attempt, retryAfterMs), opts.signal);\n continue;\n }\n if (res.status === 429) throw new RateLimitError(url, body, retryAfterMs);\n throw new HttpError(res.status, url, body);\n }\n }\n}\n\nasync function readBody(res: Response): Promise<unknown> {\n let text: string;\n try {\n text = await res.text();\n } catch {\n return null;\n }\n if (text === '') return null;\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n}\n","// Copyright 2026 The AsentumChain Contributors\n// SPDX-License-Identifier: Apache-2.0\n\n/**\n * AsentumClient: read-only interface to an Asentum node's HTTP API, plus\n * submission of already signed transactions and confirmation helpers.\n * No private keys. For signing, use {@link AsentumWallet}.\n *\n * Works in Node.js 18+ and browsers; it only needs `fetch`.\n *\n * Node behaviour worth knowing (node 0.8.1):\n * - Most errors are HTTP 200 with an `error` or `reason` field. The SDK\n * turns those into typed errors, and \"not found\" into null.\n * - Two heads: the tip (newest block) and finalized (a few blocks behind,\n * never changes). Receipts, /view and balances read the tip by default;\n * blocks and eth_getLogs are finalized only unless asked otherwise.\n * - Gateway limit about 25 requests a second per IP. The SDK retries 429\n * and 5xx with backoff.\n */\n\nimport { ase1ArgsToHex, hexToAse1, maybeAse1, toAse1 } from './ase1.js';\nimport { AbortError, AsentumError, HttpError, JsonRpcError, NetworkError, RateLimitError, RpcError, TimeoutError, TxFailedError, ViewError } from './errors.js';\nimport { Transport, sleep, type RequestOptions, type TransportOptions } from './http.js';\nimport { blake3, bytesToHex, hexToBytes } from './internal/crypto.js';\nimport type {\n AccountInfo,\n ApiInfo,\n Balance,\n BatchTxResult,\n Block,\n BlockReceipts,\n BlockTag,\n ChainInfo,\n Committee,\n EthTransaction,\n FinalizedStatus,\n GovernanceLocked,\n GovernanceProposal,\n GovernanceProposalDetail,\n GovernanceWithdrawable,\n Heads,\n Liveness,\n Log,\n LogFilter,\n Metadata,\n Participation,\n PublicKeyStatus,\n Receipt,\n Tombstones,\n Transaction,\n TxResult,\n ValidatorsResponse,\n ViewCallResult,\n} from './types.js';\n\n// Re-exported so `import type { Receipt } from '@asentum/sdk/client'`-style\n// code from 0.1.x keeps compiling.\nexport type {\n AccountInfo, ApiInfo, Balance, BatchTxResult, Block, BlockHeader, BlockReceipts, BlockTag, ChainInfo,\n Committee, EthTransaction, FinalizedStatus, GovernanceLocked, GovernanceProposal, GovernanceProposalDetail,\n GovernanceWithdrawable, Heads, Liveness, Log, LogFilter, Metadata, Participation, PublicKeyStatus, Receipt,\n Tombstones, Transaction, TxResult, ValidatorInfo, ValidatorsResponse, ViewCallResult,\n} from './types.js';\n\n/** The public testnet gateway. */\nexport const DEFAULT_RPC = 'https://testnet.asentum.com';\n/** Address of the governance contract (0x...0003), ase1. */\nexport const GOVERNANCE_CONTRACT: string = hexToAse1('0x0000000000000000000000000000000000000003');\n/** eth_getLogs scans at most this many blocks per call. */\nexport const MAX_LOG_RANGE = 10_000;\n\nexport interface ClientOptions extends TransportOptions {}\n\nexport interface CallOptions {\n signal?: AbortSignal;\n /** Override the retry count for this call. */\n retries?: number;\n}\n\nexport interface BlockOptions extends CallOptions {\n /** Also answer heights above the finalized head, from the pending block on the node's best chain. Default false. */\n tip?: boolean;\n}\n\nexport interface ReceiptOptions extends CallOptions {\n /** Only return a receipt once its block is final (`?tip=0`). Default false: tip receipts too, flagged finalized: false. */\n finalizedOnly?: boolean;\n}\n\nexport interface ViewOptions extends CallOptions {\n /** \"tip\" (default; \"latest\"/\"pending\" mean the same) or \"finalized\" (\"safe\"). No historical reads. */\n blockTag?: BlockTag;\n}\n\nexport type WaitUntil = 'included' | 'final';\n\n/**\n * Options for {@link AsentumClient.waitForReceipt} and `tx.wait()`.\n *\n * A transaction goes pending (accepted into a mempool) -> in a block\n * (receipt with finalized: false, about one block after sending) -> final\n * (finalized: true, a few blocks later). Rarely a block loses to a sibling\n * at the same height before it is final: the receipt disappears and the\n * transaction lands again in a later block. onReorg reports that.\n */\nexport interface WaitOptions {\n /** Resolve at the first receipt (\"included\", default) or only once final (\"final\"). */\n until?: WaitUntil;\n /** Give up after this long. Default 60,000 for \"included\", 120,000 for \"final\". */\n timeoutMs?: number;\n /** Poll interval. Default 1,000 (blocks are about 2.5 s apart). */\n pollIntervalMs?: number;\n /** The transaction is in a block (show success now). Fires again after a reorg puts it in another block. */\n onIncluded?: (receipt: Receipt) => void;\n /** The block is final. Only fires with until: \"final\". */\n onFinal?: (receipt: Receipt) => void;\n /** A block the transaction was in lost to a sibling; `previous` is the receipt that is no longer valid. */\n onReorg?: (previous: Receipt) => void;\n /** Abort waiting (rejects with AbortError). The transaction itself is not affected. */\n signal?: AbortSignal;\n /** Reject with TxFailedError when the receipt has success: false. Default false (resolve with the receipt). */\n throwOnFailure?: boolean;\n /** In a browser, do not poll while the tab is hidden. Default true. */\n pauseWhenHidden?: boolean;\n}\n\nfunction asRecord(v: unknown): Record<string, unknown> | null {\n return v !== null && typeof v === 'object' && !Array.isArray(v) ? (v as Record<string, unknown>) : null;\n}\n\nfunction errorField(body: unknown): string | null {\n const r = asRecord(body);\n if (!r || r.error === undefined || r.error === null || r.error === '') return null;\n const msg = r.message ? `${String(r.error)} (${String(r.message)})` : String(r.error);\n return msg;\n}\n\nfunction normReceipt(r: Receipt): Receipt {\n return { ...r, sender: maybeAse1(r.sender), recipient: maybeAse1(r.recipient) };\n}\n\nfunction normTx(t: Transaction): Transaction {\n const out: Transaction = { ...t, body: { ...t.body, to: maybeAse1(t.body?.to) } };\n if (t.sender) out.sender = maybeAse1(t.sender);\n return out;\n}\n\nfunction normBlock(b: Block): Block {\n return {\n ...b,\n header: { ...b.header, proposer: maybeAse1(b.header.proposer) },\n transactions: (b.transactions ?? []).map(normTx),\n receipts: (b.receipts ?? []).map(normReceipt),\n };\n}\n\nfunction toBlockParam(v: number | bigint | string | undefined): string | undefined {\n if (v === undefined) return undefined;\n if (typeof v === 'number' || typeof v === 'bigint') return '0x' + BigInt(v).toString(16);\n if (/^\\d+$/.test(v)) return '0x' + BigInt(v).toString(16);\n return v;\n}\n\nfunction hexToUtf8(hex: string): string {\n return new TextDecoder().decode(hexToBytes(hex));\n}\n\n/** topics[0] of an event: BLAKE3 of the UTF-8 event name, 0x hex. */\nexport function eventTopic(name: string): string {\n return bytesToHex(blake3(new TextEncoder().encode(name)));\n}\n\nfunction hidden(): boolean {\n const d = (globalThis as { document?: { visibilityState?: string } }).document;\n return !!d && d.visibilityState === 'hidden';\n}\n\nexport class AsentumClient {\n readonly rpcUrl: string;\n /** @internal */\n readonly transport: Transport;\n private chainIdCache?: bigint;\n\n constructor(rpcUrl: string = DEFAULT_RPC, options: ClientOptions = {}) {\n this.rpcUrl = rpcUrl.replace(/\\/+$/, '');\n this.transport = new Transport(this.rpcUrl, options);\n }\n\n // ---------------------------------------------------------------------------\n // Chain and health\n // ---------------------------------------------------------------------------\n\n /** Finalized height and tip in one small call (GET /v3/heads). */\n async getHeads(opts: CallOptions = {}): Promise<Heads> {\n const r = await this.get<{ finalized: string; tip: string }>('/v3/heads', opts);\n return { finalized: Number(r.finalized), tip: Number(r.tip) };\n }\n\n /** Newest block height on the best chain. */\n async getTipNumber(opts: CallOptions = {}): Promise<number> {\n return (await this.getHeads(opts)).tip;\n }\n\n /** Finalized height (same as eth_blockNumber and getBlockNumber). */\n async getFinalizedNumber(opts: CallOptions = {}): Promise<number> {\n return (await this.getHeads(opts)).finalized;\n }\n\n /** Chain id, finalized height, this node's mempool size and the finalized header (GET /chain, cached 1 s on the gateway). */\n async getChainInfo(opts: CallOptions = {}): Promise<ChainInfo> {\n const raw = await this.get<ChainInfo & { height: string }>('/chain', opts);\n return {\n ...raw,\n height: Number(raw.height),\n latestHeader: { ...raw.latestHeader, proposer: maybeAse1(raw.latestHeader?.proposer) },\n };\n }\n\n /** The FINALIZED height. Use getTipNumber() for the newest block. */\n async getBlockNumber(opts: CallOptions = {}): Promise<number> {\n return (await this.getChainInfo(opts)).height;\n }\n\n /** Chain id (1423 on the public testnet). Cached after the first call. */\n async getChainId(opts: CallOptions = {}): Promise<bigint> {\n if (this.chainIdCache === undefined) {\n this.chainIdCache = BigInt((await this.getChainInfo(opts)).chainId);\n }\n return this.chainIdCache;\n }\n\n /** Chain details in EIP-3085 shape (GET /metadata, cached 30 s on the gateway). */\n async getMetadata(opts: CallOptions = {}): Promise<Metadata> {\n return this.get<Metadata>('/metadata', opts);\n }\n\n /** Node identity (GET /api). `version` is a fixed placeholder, not the node release. */\n async getApiInfo(opts: CallOptions = {}): Promise<ApiInfo> {\n const r = await this.get<ApiInfo>('/api', opts);\n return { ...r, faucetAddress: r.faucetAddress ? maybeAse1(r.faucetAddress) : r.faucetAddress };\n }\n\n /** The genesis spec (GET /genesis, about 17 KB). Address fields converted to ase1. */\n async getGenesis(opts: CallOptions = {}): Promise<Record<string, unknown>> {\n const r = await this.getChecked<Record<string, unknown>>('/genesis', opts);\n const fix = (list: unknown) =>\n Array.isArray(list)\n ? list.map((e) => {\n const o = asRecord(e);\n if (!o) return e;\n const c: Record<string, unknown> = { ...o };\n for (const k of Object.keys(c)) if (/address$/i.test(k)) c[k] = maybeAse1(c[k]);\n return c;\n })\n : list;\n return { ...r, initialAccounts: fix(r.initialAccounts), initialValidators: fix(r.initialValidators), initialAseHolders: fix(r.initialAseHolders) };\n }\n\n /** Liveness probe (GET /health). True as long as the HTTP server answers. Does not check sync. */\n async isHealthy(opts: CallOptions = {}): Promise<boolean> {\n try {\n const res = await this.get<{ status: string }>('/health', { ...opts, retries: opts.retries ?? 0 });\n return res?.status === 'ok';\n } catch (err) {\n if (err instanceof AbortError) throw err;\n return false;\n }\n }\n\n /**\n * Readiness probe (GET /ready): true on 200 \"ready\", false on 503 \"stale\"\n * or no answer. Caveat: node 0.8.1 compares seconds with milliseconds\n * here, so it reports ready even on a stalled node. To detect a stall,\n * check that getHeads() keeps moving.\n */\n async isReady(opts: CallOptions = {}): Promise<boolean> {\n try {\n const r = await this.transport.request<{ status?: string }>('/ready', {\n signal: opts.signal,\n retries: opts.retries ?? 0,\n allowStatus: [503],\n });\n return r.status === 200 && r.body?.status === 'ready';\n } catch (err) {\n if (err instanceof AbortError) throw err;\n return false;\n }\n }\n\n // ---------------------------------------------------------------------------\n // Accounts\n // ---------------------------------------------------------------------------\n\n /** Balance (wei), nonce and pendingNonce at the tip (GET /balance). */\n async getBalance(address: string, opts: CallOptions = {}): Promise<Balance> {\n const r = await this.getChecked<Balance>(`/balance/${encodeURIComponent(address)}`, opts);\n return { ...r, address: maybeAse1(r.address) };\n }\n\n /**\n * The nonce to SEND with. Default: the node's mempool-aware pendingNonce,\n * so several sends in a row get n, n+1, n+2. `{ pending: false }` gives\n * the account nonce at the tip.\n */\n async getNonce(address: string, opts: CallOptions & { pending?: boolean } = {}): Promise<bigint> {\n const bal = await this.getBalance(address, opts);\n return BigInt(opts.pending === false ? bal.nonce : (bal.pendingNonce ?? bal.nonce));\n }\n\n /** Full account record: balance, nonce, codeHash, storageRoot (GET /asentum/account). */\n async getAccount(address: string, opts: CallOptions = {}): Promise<AccountInfo> {\n const r = await this.getChecked<AccountInfo>(`/asentum/account/${encodeURIComponent(address)}`, opts);\n return { ...r, address: maybeAse1(r.address) };\n }\n\n /** Whether the chain has this account's public key on record, so it may send key-less transactions (GET /public-key). */\n async getPublicKeyStatus(address: string, opts: CallOptions = {}): Promise<PublicKeyStatus> {\n const r = await this.getChecked<PublicKeyStatus>(`/public-key/${encodeURIComponent(address)}`, opts);\n return { ...r, address: maybeAse1(r.address) };\n }\n\n // ---------------------------------------------------------------------------\n // Blocks\n // ---------------------------------------------------------------------------\n\n /**\n * A block with decoded transactions and receipts, or null when this node\n * does not have it. Finalized blocks only, unless `{ tip: true }`.\n * (0.1.x returned the node's error object here instead of null.)\n */\n async getBlock(number: number | bigint, opts: BlockOptions = {}): Promise<Block | null> {\n const q = opts.tip ? '?tip=1' : '';\n const r = await this.get<Block | { error: string }>(`/block/${BigInt(number)}${q}`, opts);\n const err = errorField(r);\n if (err) {\n if (/not found/i.test(err)) return null;\n throw new RpcError(`/block/${number}`, err, r);\n }\n return normBlock(r as Block);\n }\n\n /** Only the receipts of a block (GET /block/<n>/receipts). Check `available` before trusting an empty list. */\n async getBlockReceipts(number: number | bigint, opts: BlockOptions = {}): Promise<BlockReceipts> {\n const q = opts.tip ? '?tip=1' : '';\n const r = await this.getChecked<Omit<BlockReceipts, 'available'>>(`/block/${BigInt(number)}/receipts${q}`, opts);\n return { ...r, receipts: (r.receipts ?? []).map(normReceipt), available: r.finalized !== undefined };\n }\n\n /** The block as SSZ bytes (0x hex), or null. Note: also serves pending heights without saying so. */\n async getRawBlock(number: number | bigint, opts: CallOptions = {}): Promise<string | null> {\n const r = await this.get<{ bytes?: string; error?: string }>(`/block-raw/${BigInt(number)}`, opts);\n if (errorField(r)) return null;\n return r.bytes ?? null;\n }\n\n /** Whether a height is finalized on this node, and the Aura hash finalized there (GET /v3/finalized). */\n async getFinalizedStatus(height: number | bigint, opts: CallOptions = {}): Promise<FinalizedStatus> {\n return this.getChecked<FinalizedStatus>(`/v3/finalized?height=${BigInt(height)}`, opts);\n }\n\n // ---------------------------------------------------------------------------\n // Transactions and receipts\n // ---------------------------------------------------------------------------\n\n /**\n * The receipt of a transaction, or null when it is not in a block (yet).\n * Tip receipts are included by default (finalized: false); see\n * `finalizedOnly`. Check `success`, not `status`.\n *\n * Throws RpcError for a malformed hash and HttpError / NetworkError after\n * retries (0.1.x returned null for every error).\n */\n async getReceipt(txHash: string, opts: ReceiptOptions = {}): Promise<Receipt | null> {\n const q = opts.finalizedOnly ? '?tip=0' : '';\n const r = await this.get<Receipt | { error: string }>(`/receipts/${encodeURIComponent(txHash)}${q}`, opts);\n const rec = asRecord(r);\n // A receipt exists only when the body has a blockNumber. A FAILED tx's\n // receipt also has `error` (its revert reason), so test blockNumber.\n if (rec && rec.blockNumber !== undefined && rec.blockNumber !== null) return normReceipt(r as Receipt);\n const err = errorField(r);\n if (!err || /receipt not found/i.test(err)) return null;\n throw new RpcError(`/receipts/${txHash}`, err, r);\n }\n\n /** The transaction body from eth_getTransactionByHash (in-block transactions only, tip too), or null. */\n async getTransaction(txHash: string, opts: CallOptions = {}): Promise<EthTransaction | null> {\n const t = await this.jsonRpc<EthTransaction | null>('eth_getTransactionByHash', [txHash], opts);\n if (!t) return null;\n return { ...t, from: toAse1(t.from), to: t.to ? toAse1(t.to) : null };\n }\n\n /**\n * Submit one signed transaction (POST /tx). Does not throw on rejection:\n * check `accepted`. `accepted: true` only means \"in this node's mempool\".\n */\n async submitRawTx(rawTxHex: string, opts: CallOptions = {}): Promise<TxResult> {\n // Retry only on 429 (the request never reached the node). A 5xx or a\n // dropped connection is ambiguous, so it is surfaced, not retried.\n const r = await this.transport.request<TxResult>('/tx', {\n method: 'POST',\n body: { rawTx: rawTxHex },\n signal: opts.signal,\n retries: opts.retries,\n retryOnServerError: false,\n });\n return r.body;\n }\n\n /**\n * Submit several signed transactions in one request (POST /tx/batch).\n * They are admitted in order; one rejection does not stop the rest.\n */\n async submitRawTxBatch(rawTxs: string[], opts: CallOptions = {}): Promise<BatchTxResult> {\n if (rawTxs.length === 0) return { accepted: 0, rejected: 0, total: 0, results: [] };\n const r = await this.transport.request<BatchTxResult>('/tx/batch', {\n method: 'POST',\n body: { transactions: rawTxs.map((rawTx) => ({ rawTx })) },\n signal: opts.signal,\n retries: opts.retries,\n retryOnServerError: false,\n });\n return r.body;\n }\n\n /**\n * Wait for a transaction's receipt. Polls GET /receipts about once a\n * second, backs off on 429 / 5xx, and follows the receipt through a\n * reorg (onReorg, then onIncluded again for the new block).\n *\n * Resolves with the receipt (until: \"included\", the default) or with the\n * final receipt (until: \"final\"). Rejects with TimeoutError (not a\n * failure: the tx may still land), AbortError, or TxFailedError when\n * throwOnFailure is set.\n */\n async waitForReceipt(txHash: string, opts: WaitOptions = {}): Promise<Receipt> {\n const until: WaitUntil = opts.until ?? 'included';\n const timeoutMs = opts.timeoutMs ?? (until === 'final' ? 120_000 : 60_000);\n const interval = opts.pollIntervalMs ?? 1000;\n const pause = opts.pauseWhenHidden ?? true;\n const deadline = Date.now() + timeoutMs;\n let seen: Receipt | null = null;\n let delay = interval;\n while (Date.now() < deadline) {\n if (opts.signal?.aborted) throw new AbortError();\n if (pause && hidden()) {\n await sleep(Math.min(1000, Math.max(0, deadline - Date.now())), opts.signal);\n continue;\n }\n let r: Receipt | null = null;\n let polled = false;\n try {\n r = await this.getReceipt(txHash, { signal: opts.signal, retries: 0 });\n polled = true;\n delay = interval;\n } catch (err) {\n if (err instanceof AbortError || err instanceof RpcError) throw err;\n if (err instanceof RateLimitError) {\n delay = Math.min(10_000, err.retryAfterMs ?? delay * 2);\n } else if (err instanceof NetworkError || (err instanceof HttpError && err.status >= 500)) {\n delay = Math.min(10_000, delay * 2);\n } else {\n throw err;\n }\n }\n if (polled) {\n if (r) {\n if (seen && seen.blockHash && r.blockHash && seen.blockHash !== r.blockHash) {\n opts.onReorg?.(seen);\n seen = null;\n }\n if (!seen) {\n seen = r;\n opts.onIncluded?.(r);\n } else {\n seen = r; // same block, fresher confirmations\n }\n // Nodes before 0.7.1 had no `finalized` field and only served final receipts.\n const isFinal = r.finalized !== false;\n if (until === 'included' || isFinal) {\n if (r.success === false && opts.throwOnFailure) throw new TxFailedError(r);\n if (until === 'final') opts.onFinal?.(r);\n return r;\n }\n } else if (seen) {\n // Seen in a block before, gone now: that block lost at its height.\n opts.onReorg?.(seen);\n seen = null;\n }\n }\n const left = deadline - Date.now();\n if (left <= 0) break;\n await sleep(Math.min(delay, left), opts.signal);\n }\n throw new TimeoutError(txHash, timeoutMs, until, seen);\n }\n\n // ---------------------------------------------------------------------------\n // Contracts\n // ---------------------------------------------------------------------------\n\n /**\n * Run a contract method read-only (POST /view). ase1 addresses inside\n * `args` are converted to 0x hex first (the node does not convert them,\n * and contracts store accounts as hex). Reads the tip unless\n * `{ blockTag: 'finalized' }`. Does not throw on ok: false; see view().\n */\n async viewCall(contract: string, method: string, args: unknown[] = [], opts: ViewOptions = {}): Promise<ViewCallResult> {\n const body: Record<string, unknown> = { contract, method, args: ase1ArgsToHex(args) };\n if (opts.blockTag) body.blockTag = opts.blockTag;\n const r = await this.transport.request<ViewCallResult>('/view', {\n method: 'POST',\n body,\n signal: opts.signal,\n retries: opts.retries,\n });\n return r.body;\n }\n\n /** Like viewCall, but returns the method's return value and throws ViewError on ok: false. */\n async view<T = unknown>(contract: string, method: string, args: unknown[] = [], opts: ViewOptions = {}): Promise<T> {\n const r = await this.viewCall(contract, method, args, opts);\n if (!r.ok) throw new ViewError(method, r.reason ?? 'unknown');\n return r.returnValue as T;\n }\n\n /** A contract's source, hex-encoded UTF-8 (eth_getCode). \"0x\" for an account without code. */\n async getCode(address: string, opts: CallOptions = {}): Promise<string> {\n return this.jsonRpc<string>('eth_getCode', [address, 'latest'], opts);\n }\n\n /** A contract's JavaScript source as text, or null when the address has no code. */\n async getContractSource(address: string, opts: CallOptions = {}): Promise<string | null> {\n const hex = await this.getCode(address, opts);\n if (!hex || hex === '0x') return null;\n return hexToUtf8(hex);\n }\n\n /** A contract storage value by key (a plain string such as \"self\"), as text, or null when empty (eth_getStorageAt). */\n async getStorageAt(address: string, key: string, opts: CallOptions = {}): Promise<string | null> {\n const hex = await this.jsonRpc<string>('eth_getStorageAt', [address, key, 'latest'], opts);\n if (!hex || hex === '0x') return null;\n return hexToUtf8(hex);\n }\n\n /**\n * Contract events from eth_getLogs, decoded. Finalized blocks only. A\n * range wider than 10,000 blocks is split into several calls.\n *\n * await client.getLogs({ address: 'ase1...', event: 'Transfer', fromBlock: 570000, toBlock: 571000 })\n */\n async getLogs(filter: LogFilter = {}, opts: CallOptions = {}): Promise<Log[]> {\n const topics = filter.event ? [eventTopic(filter.event)] : filter.topics;\n const address = filter.address;\n const from = filter.fromBlock;\n const to = filter.toBlock;\n const numeric = (v: unknown): v is number | bigint => typeof v === 'number' || typeof v === 'bigint' || (typeof v === 'string' && /^\\d+$/.test(v));\n const ranges: Array<[string | undefined, string | undefined]> = [];\n if (numeric(from) && numeric(to)) {\n let a = BigInt(from);\n const b = BigInt(to);\n if (a > b) return [];\n while (a <= b) {\n const end = a + BigInt(MAX_LOG_RANGE) - 1n < b ? a + BigInt(MAX_LOG_RANGE) - 1n : b;\n ranges.push([toBlockParam(a), toBlockParam(end)]);\n a = end + 1n;\n }\n } else {\n ranges.push([toBlockParam(from), toBlockParam(to)]);\n }\n const out: Log[] = [];\n for (const [fromBlock, toBlock] of ranges) {\n const params: Record<string, unknown> = {};\n if (fromBlock !== undefined) params.fromBlock = fromBlock;\n if (toBlock !== undefined) params.toBlock = toBlock;\n if (address !== undefined) params.address = address;\n if (topics !== undefined) params.topics = topics;\n const logs = await this.jsonRpc<Array<Record<string, string | string[] | boolean>>>('eth_getLogs', [params], opts);\n for (const l of logs ?? []) {\n const raw = String(l.data ?? '0x');\n let data: unknown = null;\n if (raw !== '0x') {\n const text = hexToUtf8(raw);\n try {\n data = JSON.parse(text);\n } catch {\n data = text;\n }\n }\n const ts = (l.topics as string[]) ?? [];\n out.push({\n address: toAse1(String(l.address)),\n topic: ts[0] ?? '',\n topics: ts,\n ...(filter.event ? { eventName: filter.event } : {}),\n data,\n rawData: raw,\n blockNumber: Number(l.blockNumber),\n blockHash: String(l.blockHash),\n transactionHash: String(l.transactionHash),\n transactionIndex: Number(l.transactionIndex),\n logIndex: Number(l.logIndex),\n removed: Boolean(l.removed),\n });\n }\n }\n return out;\n }\n\n // ---------------------------------------------------------------------------\n // Validators and consensus\n // ---------------------------------------------------------------------------\n\n /** Every bonded validator with stake and committee state, plus the epoch (GET /validators, about 260 KB). */\n async getValidators(opts: CallOptions = {}): Promise<ValidatorsResponse> {\n const r = await this.getChecked<ValidatorsResponse>('/validators', opts);\n return {\n ...r,\n stakingContract: r.stakingContract ? maybeAse1(r.stakingContract) : r.stakingContract,\n validators: (r.validators ?? []).map((v) => ({ ...v, address: maybeAse1(v.address) })),\n };\n }\n\n /** Who signed recent blocks (GET /participation). lookback 1 to 10,000, default 1,000. */\n async getParticipation(opts: CallOptions & { lookback?: number } = {}): Promise<Participation> {\n const q = opts.lookback !== undefined ? `?lookback=${opts.lookback}` : '';\n const r = await this.getChecked<Participation>(`/participation${q}`, opts);\n return { ...r, validators: (r.validators ?? []).map((v) => ({ ...v, address: maybeAse1(v.address) })) };\n }\n\n /** The voting committee of an epoch (default: current), ase1, in canonical order (GET /v3/committee). */\n async getCommittee(opts: CallOptions & { epoch?: number | bigint } = {}): Promise<Committee> {\n const q = opts.epoch !== undefined ? `?epoch=${BigInt(opts.epoch)}` : '';\n const r = await this.getChecked<Committee>(`/v3/committee${q}`, { ...opts, allowStatus: [404] });\n return { ...r, committee: (r.committee ?? []).map(maybeAse1), leaderBase: (r.leaderBase ?? []).map(maybeAse1) };\n }\n\n /** The node's liveness tracker (GET /consensus/liveness, about 40 KB). */\n async getLiveness(opts: CallOptions = {}): Promise<Liveness> {\n const r = await this.getChecked<Liveness>('/consensus/liveness', opts);\n return {\n ...r,\n baked: (r.baked ?? []).map(maybeAse1),\n tracked: (r.tracked ?? []).map((t) => ({ ...t, address: maybeAse1(t.address) })),\n };\n }\n\n /** Slashed and tombstoned validators (GET /slashing/tombstones). */\n async getTombstones(opts: CallOptions = {}): Promise<Tombstones> {\n const r = await this.getChecked<Tombstones>('/slashing/tombstones', opts);\n return { ...r, slashingContract: maybeAse1(r.slashingContract) };\n }\n\n // ---------------------------------------------------------------------------\n // Governance (reads; voting and proposing are contract calls)\n // ---------------------------------------------------------------------------\n\n /** The newest proposals, up to 50 (GET /governance/proposals). */\n async getProposals(opts: CallOptions = {}): Promise<GovernanceProposal[]> {\n const r = await this.getChecked<{ proposals: GovernanceProposal[] }>('/governance/proposals', opts);\n return (r.proposals ?? []).map((p) => ({ ...p, proposer: maybeAse1(p.proposer) }));\n }\n\n /** One proposal with its amendments, or null for an unknown id (GET /governance/proposal/<id>). */\n async getProposal(id: number | string, opts: CallOptions = {}): Promise<GovernanceProposalDetail | null> {\n const r = await this.getChecked<{ proposal: GovernanceProposal | null; amendments: unknown[] }>(\n `/governance/proposal/${encodeURIComponent(String(id))}`,\n opts,\n );\n if (!r.proposal) return null;\n const amendments = (r.amendments ?? []).map((a) => {\n const o = asRecord(a);\n if (!o) return a;\n const c: Record<string, unknown> = { ...o };\n for (const k of ['proposer', 'author', 'sender']) if (k in c) c[k] = maybeAse1(c[k]);\n return c;\n });\n return { proposal: { ...r.proposal, proposer: maybeAse1(r.proposal.proposer) }, amendments };\n }\n\n /** ASE (wei) an address has locked in governance votes (GET /governance/locked). */\n async getGovernanceLocked(address: string, opts: CallOptions = {}): Promise<GovernanceLocked> {\n const r = await this.getChecked<GovernanceLocked>(`/governance/locked/${encodeURIComponent(address)}`, opts);\n return { ...r, address: toAse1(r.address ?? address) };\n }\n\n /** Vote weight still locked vs ready to withdraw (GET /governance/withdrawable). */\n async getGovernanceWithdrawable(address: string, opts: CallOptions = {}): Promise<GovernanceWithdrawable> {\n const r = await this.getChecked<GovernanceWithdrawable>(`/governance/withdrawable/${encodeURIComponent(address)}`, opts);\n return { ...r, address: toAse1(r.address ?? address) };\n }\n\n /** Approved libraries (GET /governance/libraries). Library approval is disabled, so always empty today. */\n async getGovernanceLibraries(opts: CallOptions = {}): Promise<unknown[]> {\n return (await this.getChecked<{ libraries: unknown[] }>('/governance/libraries', opts)).libraries ?? [];\n }\n\n /** One approved library by name, or null (GET /governance/library/<name>). */\n async getGovernanceLibrary(name: string, opts: CallOptions = {}): Promise<unknown | null> {\n return (await this.getChecked<{ library: unknown }>(`/governance/library/${encodeURIComponent(name)}`, opts)).library ?? null;\n }\n\n // ---------------------------------------------------------------------------\n // Dev faucet (devnets only)\n // ---------------------------------------------------------------------------\n\n /**\n * @deprecated The node's POST /dev/faucet is OFF unless the operator sets\n * ASENTUM_DEV_FAUCET=1, which only makes sense on a local devnet. Every\n * public node answers `{ accepted: false, reason: \"faucet not enabled on\n * this node\" }`. For test ASE use the airdrop dashboard (see the docs page\n * \"Get Test ASE\"). Kept for local devnets; never throws on 404 / 429.\n */\n async faucet(to: string, amount: string = '100000000000000000000', opts: CallOptions = {}): Promise<TxResult> {\n const r = await this.transport.request<TxResult>('/dev/faucet', {\n method: 'POST',\n body: { to, amount },\n signal: opts.signal,\n retries: 0,\n retryOnServerError: false,\n allowStatus: [404, 410, 429],\n });\n const b = asRecord(r.body);\n if (!b || typeof b.accepted !== 'boolean') {\n return { accepted: false, reason: `faucet not available on this node (HTTP ${r.status})` };\n }\n return r.body;\n }\n\n // ---------------------------------------------------------------------------\n // JSON-RPC\n // ---------------------------------------------------------------------------\n\n /** Send one Ethereum-style JSON-RPC request to POST /. Throws JsonRpcError on an error object. */\n async jsonRpc<T>(method: string, params: unknown[] = [], opts: CallOptions = {}): Promise<T> {\n const r = await this.transport.request<{ result?: T; error?: { code: number; message: string; data?: unknown } }>('/', {\n method: 'POST',\n body: { jsonrpc: '2.0', id: 1, method, params },\n signal: opts.signal,\n retries: opts.retries,\n });\n const body = asRecord(r.body);\n if (!body) throw new AsentumError('JSON_RPC_ERROR', `JSON-RPC ${method}: unexpected response`);\n const e = asRecord(body.error);\n if (e) throw new JsonRpcError(method, Number(e.code ?? 0), String(e.message ?? 'error'), e.data);\n return body.result as T;\n }\n\n // ---------------------------------------------------------------------------\n // Internal HTTP helpers\n // ---------------------------------------------------------------------------\n\n /** GET and return the body as is. */\n protected async get<T>(path: string, opts: CallOptions & Pick<RequestOptions, 'allowStatus'> = {}): Promise<T> {\n const r = await this.transport.request<T>(path, { signal: opts.signal, retries: opts.retries, allowStatus: opts.allowStatus });\n return r.body;\n }\n\n /** GET and throw RpcError when the body carries an `error` field (the node's HTTP 200 errors). */\n protected async getChecked<T>(path: string, opts: CallOptions & Pick<RequestOptions, 'allowStatus'> = {}): Promise<T> {\n const body = await this.get<T>(path, opts);\n const err = errorField(body);\n if (err) throw new RpcError(path.split('?')[0]!, err, body);\n if (body === null || typeof body !== 'object') throw new RpcError(path, 'unexpected non-JSON response', body);\n return body;\n }\n}\n","// Copyright 2026 The AsentumChain Contributors\n// SPDX-License-Identifier: Apache-2.0\n\n/**\n * AsentumContract: a deployed contract with view, send and event helpers.\n *\n * const c = new AsentumContract(client, 'ase1...');\n * const pool = await c.view('getPool', ['3']); // free, reads the tip\n * const tx = await c.connect(wallet).send('swap', [...]); // signed tx\n * await tx.wait();\n * const swaps = await c.getEvents('Swap', { fromBlock: 570000 });\n */\n\nimport { toAse1, toHexAddress } from './ase1.js';\nimport type { AsentumClient, CallOptions, ViewOptions, WaitOptions } from './client.js';\nimport { AsentumError, ViewError } from './errors.js';\nimport type { AccountInfo, Log, Receipt, ViewCallResult } from './types.js';\nimport type { AsentumWallet, SentTx } from './wallet.js';\n\nexport interface ContractSendOpts {\n /** ASE to send with the call, parsed with parseAse (\"1.5\" = 1.5 ASE, bigint = wei). Prefer valueWei. */\n value?: string | number | bigint;\n /** Value in wei. Takes precedence over `value`. */\n valueWei?: bigint | string;\n gasLimit?: bigint;\n nonce?: bigint;\n /** Signer for this call; default the wallet attached with connect() or deploy(). */\n wallet?: AsentumWallet;\n signal?: AbortSignal;\n}\n\nexport class AsentumContract {\n readonly client: AsentumClient;\n /** ase1. (0.1.x kept whatever was passed in; a deploy gave 0x hex.) */\n readonly address: string;\n /** Lowercase 0x hex, what other contracts and msg.sender comparisons use. */\n readonly addressHex: string;\n /** The deploy transaction, when this contract was deployed in this session. */\n readonly deployTx?: SentTx;\n private wallet?: AsentumWallet;\n\n constructor(client: AsentumClient, address: string, deployTx?: SentTx, wallet?: AsentumWallet) {\n this.client = client;\n this.addressHex = toHexAddress(address);\n this.address = toAse1(this.addressHex);\n this.deployTx = deployTx;\n this.wallet = wallet;\n }\n\n /** Call a view method (free, no transaction) and return its value. Throws ViewError on ok: false. */\n async view<T = unknown>(method: string, args: unknown[] = [], opts: ViewOptions = {}): Promise<T> {\n const result = await this.client.viewCall(this.address, method, args, opts);\n if (!result.ok) throw new ViewError(method, result.reason ?? 'unknown');\n return result.returnValue as T;\n }\n\n /** Call a view method and return the full result: value, gas, events, blockNumber, finalized. */\n async viewFull(method: string, args: unknown[] = [], opts: ViewOptions = {}): Promise<ViewCallResult> {\n return this.client.viewCall(this.address, method, args, opts);\n }\n\n /** Send a state-changing call. Needs a wallet (connect() or opts.wallet). */\n async send(method: string, args: unknown[] = [], opts: ContractSendOpts = {}): Promise<SentTx> {\n const signer = opts.wallet ?? this.wallet;\n if (!signer) {\n throw new AsentumError('INVALID_ARGUMENT', 'no wallet available: pass opts.wallet or use contract.connect(wallet)');\n }\n return signer.sendCall({\n to: this.address,\n method,\n args,\n value: opts.value,\n valueWei: opts.valueWei,\n gasLimit: opts.gasLimit,\n nonce: opts.nonce,\n signal: opts.signal,\n });\n }\n\n /** A copy of this contract that signs with `wallet`. */\n connect(wallet: AsentumWallet): AsentumContract {\n return new AsentumContract(this.client, this.address, this.deployTx, wallet);\n }\n\n /** The contract's JavaScript source, or null if the address has no code. */\n async getSource(opts: CallOptions = {}): Promise<string | null> {\n return this.client.getContractSource(this.address, opts);\n }\n\n /** The contract's ASE balance in wei. */\n async getBalance(opts: CallOptions = {}): Promise<bigint> {\n return BigInt((await this.client.getBalance(this.address, opts)).balance);\n }\n\n /** The account record (codeHash = BLAKE3 of the source, storageRoot). */\n async getAccount(opts: CallOptions = {}): Promise<AccountInfo> {\n return this.client.getAccount(this.address, opts);\n }\n\n /**\n * Events this contract emitted, decoded (eth_getLogs, finalized blocks\n * only, ranges over 10,000 blocks are split). `eventName` undefined = all.\n */\n async getEvents(\n eventName?: string,\n range: { fromBlock?: number | bigint | string; toBlock?: number | bigint | string } = {},\n opts: CallOptions = {},\n ): Promise<Log[]> {\n return this.client.getLogs({ address: this.address, event: eventName, ...range }, opts);\n }\n\n /**\n * Wait for the deploy transaction (only when deployed in this session).\n * Accepts a timeout in ms (0.1.x) or WaitOptions, e.g. { until: 'final' }.\n */\n async waitForDeploy(timeoutOrOpts?: number | WaitOptions): Promise<Receipt> {\n if (!this.deployTx) {\n throw new AsentumError('INVALID_ARGUMENT', 'this contract was not deployed in this session: there is no deploy tx to wait for');\n }\n return this.deployTx.wait(timeoutOrOpts);\n }\n}\n","// Copyright 2026 The AsentumChain Contributors\n// SPDX-License-Identifier: Apache-2.0\n\n/**\n * Transaction wire format (SSZ), kept inside the package for the same reason\n * as ./crypto.ts. Source of truth: AsentumChain packages/types\n * (primitives.ts, transaction.ts).\n *\n * legacy: [u32 offset 5265][publicKey 1952][signature 3309][body]\n * signature over BLAKE3(SSZ(body))\n * key-less: [u32 offset 3333][sender 20][signature 3309][body]\n * signature over BLAKE3(domain(32) || sender || SSZ(body))\n *\n * The tx hash is BLAKE3 of the serialized signed transaction, for both forms.\n */\n\nimport { ByteListType, ByteVectorType, ContainerType, UintBigintType } from '@chainsafe/ssz';\nimport {\n ADDRESS_BYTES,\n DILITHIUM3_PUBLIC_KEY_BYTES,\n DILITHIUM3_SIGNATURE_BYTES,\n blake3,\n bytesToHex,\n sign,\n} from './crypto.js';\n\nconst MAX_TX_DATA_BYTES = 1_048_576;\nconst Uint64 = new UintBigintType(8);\nconst Uint256 = new UintBigintType(32);\nconst AddressBytes = new ByteVectorType(ADDRESS_BYTES);\n\nexport const TransactionBodySchema = new ContainerType({\n chainId: Uint64,\n nonce: Uint64,\n maxPriorityFeePerGas: Uint256,\n maxFeePerGas: Uint256,\n gasLimit: Uint64,\n to: AddressBytes,\n value: Uint256,\n data: new ByteListType(MAX_TX_DATA_BYTES),\n});\n\nexport const LegacySignedTransactionSchema = new ContainerType({\n body: TransactionBodySchema,\n publicKey: new ByteVectorType(DILITHIUM3_PUBLIC_KEY_BYTES),\n signature: new ByteVectorType(DILITHIUM3_SIGNATURE_BYTES),\n});\n\nexport const KeylessSignedTransactionSchema = new ContainerType({\n body: TransactionBodySchema,\n sender: AddressBytes,\n signature: new ByteVectorType(DILITHIUM3_SIGNATURE_BYTES),\n});\n\nexport const KEYLESS_TX_SIGNING_DOMAIN: Uint8Array = (() => {\n const tag = new TextEncoder().encode('asentum/tx/keyless/v1');\n const out = new Uint8Array(32);\n out.set(tag, 0);\n return out;\n})();\n\nexport interface TransactionBody {\n chainId: bigint;\n nonce: bigint;\n maxPriorityFeePerGas: bigint;\n maxFeePerGas: bigint;\n gasLimit: bigint;\n to: Uint8Array;\n value: bigint;\n data: Uint8Array;\n}\n\nexport function keylessSigningPreimage(body: TransactionBody, sender: Uint8Array): Uint8Array {\n if (sender.length !== ADDRESS_BYTES) throw new Error(`key-less sender must be ${ADDRESS_BYTES} bytes`);\n const bodyBytes = TransactionBodySchema.serialize(body);\n const out = new Uint8Array(32 + ADDRESS_BYTES + bodyBytes.length);\n out.set(KEYLESS_TX_SIGNING_DOMAIN, 0);\n out.set(sender, 32);\n out.set(bodyBytes, 32 + ADDRESS_BYTES);\n return out;\n}\n\nexport interface SignedTxBytes {\n /** Serialized signed transaction, 0x hex: what POST /tx takes as rawTx. */\n rawTx: string;\n /** BLAKE3 of the serialized bytes, 0x hex: the transaction hash. */\n hash: string;\n}\n\n/** Sign a body with the legacy envelope (public key included). */\nexport function signLegacy(body: TransactionBody, publicKey: Uint8Array, secretKey: Uint8Array): SignedTxBytes {\n const digest = blake3(TransactionBodySchema.serialize(body));\n const signature = sign(digest, secretKey);\n const bytes = LegacySignedTransactionSchema.serialize({ body, publicKey, signature });\n return { rawTx: bytesToHex(bytes), hash: bytesToHex(blake3(bytes)) };\n}\n\n/** Sign a body with the key-less envelope (sender named, no public key). */\nexport function signKeyless(body: TransactionBody, sender: Uint8Array, secretKey: Uint8Array): SignedTxBytes {\n const digest = blake3(keylessSigningPreimage(body, sender));\n const signature = sign(digest, secretKey);\n const bytes = KeylessSignedTransactionSchema.serialize({ body, sender, signature });\n return { rawTx: bytesToHex(bytes), hash: bytesToHex(blake3(bytes)) };\n}\n\n/** Contract address of a deploy: BLAKE3(sender(20) || nonce as u64 big-endian)[0:20]. */\nexport function contractAddressBytes(sender: Uint8Array, nonce: bigint): Uint8Array {\n const buf = new Uint8Array(ADDRESS_BYTES + 8);\n buf.set(sender, 0);\n new DataView(buf.buffer).setBigUint64(ADDRESS_BYTES, nonce, false);\n return blake3(buf).slice(0, ADDRESS_BYTES);\n}\n","// Copyright 2026 The AsentumChain Contributors\n// SPDX-License-Identifier: Apache-2.0\n\n/** Amount helpers. 1 ASE = 10^18 wei. */\n\nimport { AsentumError } from './errors.js';\n\nconst WEI_PER_ASE = 1_000_000_000_000_000_000n;\n\nfunction numberToDecimalString(n: number): string {\n if (!Number.isFinite(n) || n < 0) throw new AsentumError('INVALID_ARGUMENT', `invalid amount: ${n}`);\n // Shortest round-trip decimal text, without exponent notation. Avoids the\n // float error of n * 1e18 (1.1 * 1e18 is 1100000000000000128).\n return n.toLocaleString('en-US', { useGrouping: false, maximumFractionDigits: 20 });\n}\n\n/**\n * Strict ASE to wei: the input is ALWAYS read as ASE.\n * \"1\" -> 10^18, \"0.5\" -> 5 * 10^17, 2 -> 2 * 10^18. At most 18 decimals.\n */\nexport function aseToWei(amount: string | number): bigint {\n const s = typeof amount === 'number' ? numberToDecimalString(amount) : String(amount).trim();\n const m = /^(\\d+)(?:\\.(\\d*))?$/.exec(s);\n if (!m) throw new AsentumError('INVALID_ARGUMENT', `invalid ASE amount: \"${amount}\" (use \"1\" or \"1.5\")`);\n const whole = m[1]!;\n const frac = (m[2] ?? '').replace(/0+$/, '');\n if (frac.length > 18) throw new AsentumError('INVALID_ARGUMENT', `invalid ASE amount: \"${amount}\" has more than 18 decimals`);\n return BigInt(whole) * WEI_PER_ASE + BigInt(frac.padEnd(18, '0') || '0');\n}\n\n/**\n * Parse an amount into wei, the way 0.1.x did. Kept for compatibility; it\n * has one trap, so prefer {@link aseToWei} (always ASE) or pass wei as a\n * bigint:\n *\n * - bigint: already wei, returned as is.\n * - number or decimal string (\"1\", \"1.5\"): ASE.\n * - an integer string with MORE than 18 digits: treated as wei.\n * (\"1000000000000000000000\" is 1,000 ASE in wei; \"100\" is 100 ASE.)\n */\nexport function parseAse(amount: string | number | bigint): bigint {\n if (typeof amount === 'bigint') return amount;\n if (typeof amount === 'number') return aseToWei(amount);\n const s = amount.trim();\n if (/^\\d+$/.test(s) && s.length > 18) return BigInt(s); // wei\n if (/^\\d+(\\.\\d{1,18})?$/.test(s)) return aseToWei(s);\n throw new AsentumError('INVALID_ARGUMENT', `invalid amount: \"${amount}\" (use \"1\", \"1.5\", or a bigint in wei)`);\n}\n\n/** Format wei as an ASE decimal string without trailing zeros: 1500000000000000000n -> \"1.5\". */\nexport function formatAse(wei: bigint | string | number): string {\n const w = typeof wei === 'bigint' ? wei : BigInt(wei);\n const neg = w < 0n;\n const abs = neg ? -w : w;\n const whole = abs / WEI_PER_ASE;\n const frac = abs % WEI_PER_ASE;\n const out = frac === 0n ? whole.toString() : `${whole}.${frac.toString().padStart(18, '0').replace(/0+$/, '')}`;\n return neg ? `-${out}` : out;\n}\n\n/** Wei from a bigint, a decimal integer string or a safe integer number. Throws on anything else. */\nexport function toWei(v: bigint | string | number): bigint {\n if (typeof v === 'bigint') return v;\n if (typeof v === 'number') {\n if (!Number.isSafeInteger(v) || v < 0) throw new AsentumError('INVALID_ARGUMENT', `wei must be a non-negative integer, got ${v}`);\n return BigInt(v);\n }\n if (!/^\\d+$/.test(v.trim())) throw new AsentumError('INVALID_ARGUMENT', `wei must be a decimal integer string, got \"${v}\"`);\n return BigInt(v.trim());\n}\n","// Copyright 2026 The AsentumChain Contributors\n// SPDX-License-Identifier: Apache-2.0\n\n/**\n * AsentumWallet: a Dilithium3 (ML-DSA-65) keypair that signs and submits\n * transactions through an {@link AsentumClient}. Signing runs locally;\n * private keys never leave the process.\n *\n * const wallet = AsentumWallet.create(client); // random key\n * const tx = await wallet.sendTransfer({ to: 'ase1...', amountWei: 10n ** 18n });\n * const receipt = await tx.wait(); // in a block\n * await tx.wait({ until: 'final' }); // final\n */\n\nimport { addressToBytes, ase1ArgsToHex, bytesToAse1 } from './ase1.js';\nimport { AsentumClient, type WaitOptions } from './client.js';\nimport { AsentumContract } from './contract.js';\nimport { AsentumError, TxRejectedError } from './errors.js';\nimport { addressBytesFromPublicKey, bytesToHex, generateKeypair, hexToBytes, type Dilithium3Keypair } from './internal/crypto.js';\nimport { contractAddressBytes, signKeyless, signLegacy, type TransactionBody } from './internal/tx.js';\nimport type { Receipt, TxResult } from './types.js';\nimport { parseAse, toWei } from './units.js';\n\nexport { parseAse, formatAse } from './units.js';\nexport type { Dilithium3Keypair } from './internal/crypto.js';\n\n/**\n * Format an address for display: ase1 by default. The env override\n * `ASENTUM_ADDR_FORMAT=hex` returns lowercase 0x hex instead.\n */\nexport function formatAddress(input: string | Uint8Array): string {\n const bytes = typeof input === 'string' ? addressToBytes(input) : input;\n const wantHex = typeof process !== 'undefined' && process?.env?.ASENTUM_ADDR_FORMAT === 'hex';\n return wantHex ? bytesToHex(bytes) : bytesToAse1(bytes);\n}\n\n// ---------------------------------------------------------------------------\n// Options\n// ---------------------------------------------------------------------------\n\n/**\n * Key-less transactions (key-once, live since block 528,000): once the chain\n * has an account's public key on record, its transactions may name the\n * sender instead of carrying the 1,952-byte key, which makes them about a\n * third smaller.\n * \"off\" always include the key (default, works for every account)\n * \"auto\" go key-less once GET /public-key says canOmitKey\n * \"always\" always key-less (rejected if the key is not on record)\n */\nexport type KeylessMode = 'off' | 'auto' | 'always';\n\nexport interface WalletOptions {\n keyless?: KeylessMode;\n}\n\ninterface CommonTxOpts {\n /** Override the nonce. Default: allocated by the wallet (see getNonce / resetNonce). */\n nonce?: bigint;\n /** Override the gas limit. */\n gasLimit?: bigint;\n /** Max fee per gas in wei. Default 1 (the base fee is 1 wei per gas). */\n maxFeePerGas?: bigint;\n /** Override the wallet's key-less mode for this transaction. */\n keyless?: KeylessMode;\n signal?: AbortSignal;\n}\n\nexport interface SendTransferOpts extends CommonTxOpts {\n /** Recipient, ase1 or 0x hex. */\n to: string;\n /**\n * Amount, parsed with parseAse: a number or decimal string is ASE\n * (\"1.5\" = 1.5 ASE), a bigint is wei. Careful: an integer STRING longer\n * than 18 digits is read as wei. Prefer `amountWei` for exact values.\n */\n amount?: string | number | bigint;\n /** Amount in wei (bigint or decimal integer string). Takes precedence over `amount`. */\n amountWei?: bigint | string;\n}\n\nexport interface SendCallOpts extends CommonTxOpts {\n /** Contract address, ase1 or 0x hex. */\n to: string;\n /** Method name. */\n method: string;\n /**\n * Arguments, sent as JSON. Every ase1 address string, at any depth, is\n * converted to lowercase 0x hex before signing (contracts compare with hex\n * msg.sender).\n */\n args?: unknown[];\n /**\n * ASE to send with the call, parsed with parseAse: \"1.5\" or 2 is ASE, a\n * bigint is wei (and an integer string over 18 digits is wei). Prefer\n * `valueWei` for exact values.\n */\n value?: string | number | bigint;\n /** Value in wei. Takes precedence over `value`. */\n valueWei?: bigint | string;\n}\n\nexport interface DeployOpts extends CommonTxOpts {\n /** The contract's JavaScript source. */\n source: string;\n /** ASE to send with the deploy, parsed like SendCallOpts.value. */\n value?: string | number | bigint;\n /** Value in wei. Takes precedence over `value`. */\n valueWei?: bigint | string;\n}\n\n/** A signed transaction that has not been submitted (see sign* and sendBatch). */\nexport interface SignedTx {\n /** 0x hex wire bytes, what POST /tx takes. */\n rawTx: string;\n /** The transaction hash (0x hex, BLAKE3 of rawTx). Hashes stay hex: there is no ase1 form. */\n hash: string;\n nonce: bigint;\n /** ase1 of the signer. */\n from: string;\n /** For a deploy: the new contract's address (ase1). */\n contractAddress?: string;\n}\n\nexport interface SentTx {\n /** The transaction hash (0x hex). */\n hash: string;\n nonce: bigint;\n /** ase1 of the signer. */\n from: string;\n /** For a deploy: the new contract's address (ase1). */\n contractAddress?: string;\n /**\n * Wait for the receipt.\n *\n * await tx.wait() // first receipt: in a block (default, as in 0.1.x)\n * await tx.wait(30_000) // same, 30 s timeout (0.1.x signature)\n * await tx.wait({ until: 'final' }) // only once its block is final\n *\n * Resolves with the receipt even when it has success: false (as in 0.1.x);\n * pass `{ throwOnFailure: true }` to reject with TxFailedError instead.\n * Default timeout: 60 s (\"included\"), 120 s (\"final\"); rejects with\n * TimeoutError, which does not mean the transaction failed.\n */\n wait(timeoutOrOpts?: number | WaitOptions): Promise<Receipt>;\n}\n\nexport interface BatchSendResult {\n accepted: number;\n rejected: number;\n total: number;\n /** Same order as the input. Rejected entries have accepted: false and a reason; they will not land. */\n results: Array<TxResult & { hash: string; nonce: bigint; wait: SentTx['wait'] }>;\n}\n\nfunction makeWait(client: AsentumClient, hash: string): SentTx['wait'] {\n return (timeoutOrOpts?: number | WaitOptions) =>\n client.waitForReceipt(hash, typeof timeoutOrOpts === 'number' ? { timeoutMs: timeoutOrOpts } : (timeoutOrOpts ?? {}));\n}\n\nfunction pickWei(wei: bigint | string | undefined, loose: string | number | bigint | undefined): bigint {\n if (wei !== undefined) return toWei(wei);\n if (loose !== undefined && loose !== null && loose !== '') return parseAse(loose);\n return 0n;\n}\n\n// ---------------------------------------------------------------------------\n// AsentumWallet\n// ---------------------------------------------------------------------------\n\nexport class AsentumWallet {\n readonly client: AsentumClient;\n readonly keypair: Dilithium3Keypair;\n /**\n * The wallet's address as ase1. (0.1.x returned checksummed 0x hex here;\n * use `addressHex` for the hex form.)\n */\n readonly address: string;\n /** The same address as lowercase 0x hex: what contracts see as msg.sender. */\n readonly addressHex: string;\n /** Key-less mode for transactions from this wallet. */\n keyless: KeylessMode;\n\n private readonly addressBytes: Uint8Array;\n private nextNonce?: bigint;\n private queue: Promise<unknown> = Promise.resolve();\n private keyOnRecord = false;\n private keyCheckedAt = 0;\n\n private constructor(client: AsentumClient, keypair: Dilithium3Keypair, opts: WalletOptions = {}) {\n this.client = client;\n this.keypair = keypair;\n this.addressBytes = addressBytesFromPublicKey(keypair.publicKey);\n this.address = bytesToAse1(this.addressBytes);\n this.addressHex = bytesToHex(this.addressBytes);\n this.keyless = opts.keyless ?? 'off';\n }\n\n /** A wallet with a random keypair. */\n static create(client: AsentumClient, opts?: WalletOptions): AsentumWallet {\n return new AsentumWallet(client, generateKeypair(), opts);\n }\n\n /** A wallet from a seed (the first 32 bytes are used). Same seed, same keys. */\n static fromSeed(client: AsentumClient, seed: Uint8Array, opts?: WalletOptions): AsentumWallet {\n if (seed.length < 32) throw new AsentumError('INVALID_ARGUMENT', 'seed must be at least 32 bytes');\n return new AsentumWallet(client, generateKeypair(seed.slice(0, 32)), opts);\n }\n\n /** A wallet from exported hex keys (secretKeyHex / publicKeyHex). */\n static fromSecretKey(client: AsentumClient, secretKeyHex: string, publicKeyHex: string, opts?: WalletOptions): AsentumWallet {\n return new AsentumWallet(client, { secretKey: hexToBytes(secretKeyHex), publicKey: hexToBytes(publicKeyHex) }, opts);\n }\n\n /** The secret key as hex, for backup. Treat it like a password. */\n get secretKeyHex(): string {\n return bytesToHex(this.keypair.secretKey);\n }\n\n /** The public key as hex. */\n get publicKeyHex(): string {\n return bytesToHex(this.keypair.publicKey);\n }\n\n /** Balance in wei. */\n async getBalance(): Promise<bigint> {\n return BigInt((await this.client.getBalance(this.address)).balance);\n }\n\n /** The node's pendingNonce for this wallet (the nonce the next transaction would use, ignoring local allocations). */\n async getNonce(): Promise<bigint> {\n return this.client.getNonce(this.address);\n }\n\n /**\n * Forget locally allocated nonces; the next transaction asks the node\n * again. The wallet does this itself after a rejection.\n */\n resetNonce(): void {\n this.nextNonce = undefined;\n }\n\n /**\n * @deprecated POST /dev/faucet is off on every public node (see\n * AsentumClient.faucet). Use the airdrop dashboard for test ASE.\n */\n async requestFaucet(amount: string = '100000000000000000000'): Promise<TxResult> {\n return this.client.faucet(this.address, amount);\n }\n\n // ---------------------------------------------------------------------------\n // Send (sign + submit)\n // ---------------------------------------------------------------------------\n\n /** Send ASE. Throws TxRejectedError when the node does not accept it. */\n async sendTransfer(opts: SendTransferOpts): Promise<SentTx> {\n return this.serial(async () => this.submit(await this.buildTransfer(opts), opts.signal));\n }\n\n /** Call a contract method (state-changing). Throws TxRejectedError when the node does not accept it. */\n async sendCall(opts: SendCallOpts): Promise<SentTx> {\n return this.serial(async () => this.submit(await this.buildCall(opts), opts.signal));\n }\n\n /**\n * Same as sendCall, but `value` is in wei. Use this when you hold wei\n * amounts (balances, contract return values) so nothing is reinterpreted.\n */\n async sendCallWei(opts: Omit<SendCallOpts, 'value' | 'valueWei'> & { value?: bigint | string }): Promise<SentTx> {\n const { value, ...rest } = opts;\n return this.sendCall({ ...rest, valueWei: value ?? 0n });\n }\n\n /** Same as sendTransfer, but `amount` is in wei. */\n async sendTransferWei(opts: Omit<SendTransferOpts, 'amount' | 'amountWei'> & { amount: bigint | string }): Promise<SentTx> {\n const { amount, ...rest } = opts;\n return this.sendTransfer({ ...rest, amountWei: amount });\n }\n\n /**\n * Deploy a contract. Returns an AsentumContract at the derived address\n * right away; the deploy is only accepted, so `await contract.waitForDeploy()`\n * before using it.\n */\n async deploy(sourceOrOpts: string | DeployOpts): Promise<AsentumContract> {\n const opts: DeployOpts = typeof sourceOrOpts === 'string' ? { source: sourceOrOpts } : sourceOrOpts;\n const sent = await this.serial(async () => this.submit(await this.buildDeploy(opts), opts.signal));\n return new AsentumContract(this.client, sent.contractAddress!, sent, this);\n }\n\n // ---------------------------------------------------------------------------\n // Sign only, and batches\n // ---------------------------------------------------------------------------\n\n /** Sign a transfer without submitting it (allocates the next nonce unless given). */\n async signTransfer(opts: SendTransferOpts): Promise<SignedTx> {\n return this.serial(() => this.buildTransfer(opts));\n }\n\n /** Sign a contract call without submitting it. */\n async signCall(opts: SendCallOpts): Promise<SignedTx> {\n return this.serial(() => this.buildCall(opts));\n }\n\n /** Sign a deploy without submitting it. `contractAddress` is the address it will get. */\n async signDeploy(opts: DeployOpts): Promise<SignedTx> {\n return this.serial(() => this.buildDeploy(opts));\n }\n\n /**\n * Submit several signed transactions in one request (POST /tx/batch), in\n * the given order. Sign them first with signTransfer / signCall /\n * signDeploy (consecutive calls get consecutive nonces). One rejection\n * does not stop the rest, but a nonce gap leaves later ones waiting.\n * Does not throw on rejections: check each result.\n */\n async sendBatch(txs: SignedTx[], opts: { signal?: AbortSignal } = {}): Promise<BatchSendResult> {\n const r = await this.client.submitRawTxBatch(txs.map((t) => t.rawTx), { signal: opts.signal });\n if (r.rejected > 0) this.resetNonce();\n return {\n accepted: r.accepted,\n rejected: r.rejected,\n total: r.total,\n results: txs.map((t, i) => {\n const res = r.results[i] ?? { accepted: false, reason: 'no result from node' };\n const hash = res.txHash ?? t.hash;\n return { ...res, hash, nonce: t.nonce, wait: makeWait(this.client, hash) };\n }),\n };\n }\n\n // ---------------------------------------------------------------------------\n // Internal\n // ---------------------------------------------------------------------------\n\n /** Run fn after every earlier send/sign of this wallet, so nonces are handed out in order. */\n private serial<T>(fn: () => Promise<T>): Promise<T> {\n const run = this.queue.then(fn, fn);\n this.queue = run.catch(() => undefined);\n return run;\n }\n\n private async allocateNonce(explicit?: bigint): Promise<bigint> {\n if (explicit !== undefined) return explicit;\n const fromNode = await this.client.getNonce(this.address);\n const n = this.nextNonce !== undefined && this.nextNonce > fromNode ? this.nextNonce : fromNode;\n this.nextNonce = n + 1n;\n return n;\n }\n\n private async useKeyless(mode: KeylessMode | undefined): Promise<boolean> {\n const m = mode ?? this.keyless;\n if (m === 'off') return false;\n if (m === 'always') return true;\n if (this.keyOnRecord) return true;\n if (Date.now() - this.keyCheckedAt < 60_000) return false;\n this.keyCheckedAt = Date.now();\n try {\n this.keyOnRecord = (await this.client.getPublicKeyStatus(this.address)).canOmitKey === true;\n } catch {\n this.keyOnRecord = false;\n }\n return this.keyOnRecord;\n }\n\n private async build(\n fields: { to: Uint8Array; value: bigint; data: Uint8Array; gasLimit: bigint },\n common: CommonTxOpts,\n isDeploy = false,\n ): Promise<SignedTx> {\n const chainId = await this.client.getChainId();\n const keyless = await this.useKeyless(common.keyless);\n const nonce = await this.allocateNonce(common.nonce);\n const body: TransactionBody = {\n chainId,\n nonce,\n maxPriorityFeePerGas: 0n,\n maxFeePerGas: common.maxFeePerGas ?? 1n,\n gasLimit: common.gasLimit ?? fields.gasLimit,\n to: fields.to,\n value: fields.value,\n data: fields.data,\n };\n const signed = keyless\n ? signKeyless(body, this.addressBytes, this.keypair.secretKey)\n : signLegacy(body, this.keypair.publicKey, this.keypair.secretKey);\n return {\n ...signed,\n nonce,\n from: this.address,\n ...(isDeploy ? { contractAddress: bytesToAse1(contractAddressBytes(this.addressBytes, nonce)) } : {}),\n };\n }\n\n private buildTransfer(opts: SendTransferOpts): Promise<SignedTx> {\n if (opts.amountWei === undefined && opts.amount === undefined) {\n throw new AsentumError('INVALID_ARGUMENT', 'sendTransfer needs amount or amountWei');\n }\n return this.build(\n { to: addressToBytes(opts.to), value: pickWei(opts.amountWei, opts.amount), data: new Uint8Array(0), gasLimit: 21_000n },\n opts,\n );\n }\n\n private buildCall(opts: SendCallOpts): Promise<SignedTx> {\n const data = new TextEncoder().encode(JSON.stringify({ method: opts.method, args: ase1ArgsToHex(opts.args ?? []) }));\n return this.build(\n { to: addressToBytes(opts.to), value: pickWei(opts.valueWei, opts.value), data, gasLimit: 2_000_000n },\n opts,\n );\n }\n\n private buildDeploy(opts: DeployOpts): Promise<SignedTx> {\n const data = new TextEncoder().encode(opts.source);\n return this.build(\n {\n to: new Uint8Array(20), // zero address = deploy\n value: pickWei(opts.valueWei, opts.value),\n data,\n gasLimit: BigInt(Math.max(2_000_000, 1000 * opts.source.length)),\n },\n opts,\n true,\n );\n }\n\n private async submit(signed: SignedTx, signal?: AbortSignal): Promise<SentTx> {\n let result: TxResult;\n try {\n result = await this.client.submitRawTx(signed.rawTx, { signal });\n } catch (err) {\n // Unknown whether the node took it; ask the node next time.\n this.resetNonce();\n throw err;\n }\n if (!result || !result.accepted) {\n this.resetNonce();\n throw new TxRejectedError(result?.reason ?? 'unknown reason', signed.hash);\n }\n const hash = result.txHash ?? signed.hash;\n return {\n hash,\n nonce: signed.nonce,\n from: signed.from,\n ...(signed.contractAddress ? { contractAddress: signed.contractAddress } : {}),\n wait: makeWait(this.client, hash),\n };\n }\n}\n\n/** The address a deploy from `sender` with `nonce` gets (ase1). */\nexport function getContractAddress(sender: string, nonce: bigint | number): string {\n return bytesToAse1(contractAddressBytes(addressToBytes(sender), BigInt(nonce)));\n}\n","// Copyright 2026 The AsentumChain Contributors\n// SPDX-License-Identifier: Apache-2.0\n\n/**\n * @asentum/sdk: TypeScript SDK for building on Asentum.\n *\n * - {@link AsentumClient}: reads, submission of signed transactions, waitForReceipt\n * - {@link AsentumWallet}: keypair, signing, nonces, sending\n * - {@link AsentumContract}: view, send and events for one contract\n *\n * ```ts\n * import { AsentumClient, AsentumWallet } from '@asentum/sdk';\n *\n * const client = new AsentumClient('https://testnet.asentum.com');\n * const { finalized, tip } = await client.getHeads();\n *\n * const wallet = AsentumWallet.fromSecretKey(client, SECRET_HEX, PUBLIC_HEX);\n * const tx = await wallet.sendTransfer({ to: 'ase1...', amountWei: 10n ** 18n });\n * await tx.wait(); // in a block (about 2.5 s)\n * await tx.wait({ until: 'final' }); // final (a few blocks later)\n * ```\n */\n\nexport {\n AsentumClient,\n DEFAULT_RPC,\n GOVERNANCE_CONTRACT,\n MAX_LOG_RANGE,\n eventTopic,\n} from './client.js';\nexport type {\n BlockOptions,\n CallOptions,\n ClientOptions,\n ReceiptOptions,\n ViewOptions,\n WaitOptions,\n WaitUntil,\n} from './client.js';\n\nexport type {\n AccountInfo,\n ApiInfo,\n Balance,\n BatchTxResult,\n Block,\n BlockHeader,\n BlockReceipts,\n BlockTag,\n ChainInfo,\n Committee,\n CommitteeState,\n EpochInfo,\n EthTransaction,\n FinalizedStatus,\n GovernanceLocked,\n GovernanceProposal,\n GovernanceProposalDetail,\n GovernanceWithdrawable,\n Heads,\n Liveness,\n LivenessEntry,\n Log,\n LogFilter,\n Metadata,\n Participation,\n ParticipationEntry,\n PublicKeyStatus,\n Receipt,\n ReceiptEvent,\n Tombstones,\n Transaction,\n TxResult,\n ValidatorInfo,\n ValidatorsResponse,\n ViewCallResult,\n} from './types.js';\n\nexport { AsentumWallet, formatAddress, getContractAddress } from './wallet.js';\nexport type {\n BatchSendResult,\n DeployOpts,\n Dilithium3Keypair,\n KeylessMode,\n SendCallOpts,\n SendTransferOpts,\n SentTx,\n SignedTx,\n WalletOptions,\n} from './wallet.js';\n\nexport { AsentumContract } from './contract.js';\nexport type { ContractSendOpts } from './contract.js';\n\nexport { parseAse, aseToWei, formatAse, toWei } from './units.js';\n\nexport {\n addressToBytes,\n ase1ArgsToHex,\n ase1ToHex,\n ase1ToHexOrNull,\n bytesToAse1,\n hexToAse1,\n isAddress,\n isAse1,\n isHexAddress,\n shortAse1,\n toAse1,\n toHexAddress,\n} from './ase1.js';\n\nexport {\n AbortError,\n AsentumError,\n HttpError,\n JsonRpcError,\n NetworkError,\n RateLimitError,\n RpcError,\n TimeoutError,\n TxFailedError,\n TxRejectedError,\n ViewError,\n} from './errors.js';\nexport type { AsentumErrorCode } from './errors.js';\n\nexport type { FetchLike, TransportOptions } from './http.js';\n\n/** SDK version. */\nexport const VERSION = '0.2.0';\n"],"mappings":";AAYA,SAAS,gBAAgB;AACzB,SAAS,UAAU,mBAAmB;AAE/B,IAAM,wBAAwB;AAC9B,IAAM,8BAA8B;AACpC,IAAM,6BAA6B;AACnC,IAAM,gBAAgB;AACtB,IAAM,UAAU;AAQhB,SAAS,gBAAgB,MAAsC;AACpE,MAAI,IAAI;AACR,MAAI,CAAC,GAAG;AACN,QAAI,IAAI,WAAW,qBAAqB;AACxC,eAAW,OAAO,gBAAgB,CAAC;AAAA,EACrC;AACA,MAA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,KAAK;AAEZ,WAAK,WAAW;AAChB,YAAM;AAAA,IACR;AACA,QAAI,CAAC,UAAU,CAAC,OAAO,UAAU;AAC/B,WAAK,WAAW;AAChB,YAAM,IAAI,gBAAgB,QAAQ,UAAU,kBAAkB,OAAO,IAAI;AAAA,IAC3E;AACA,UAAM,OAAO,OAAO,UAAU,OAAO;AACrC,WAAO;AAAA,MACL;AAAA,MACA,OAAO,OAAO;AAAA,MACd,MAAM,OAAO;AAAA,MACb,GAAI,OAAO,kBAAkB,EAAE,iBAAiB,OAAO,gBAAgB,IAAI,CAAC;AAAA,MAC5E,MAAM,SAAS,KAAK,QAAQ,IAAI;AAAA,IAClC;AAAA,EACF;AACF;AAGO,SAAS,mBAAmB,QAAgB,OAAgC;AACjF,SAAO,YAAY,qBAAqB,eAAe,MAAM,GAAG,OAAO,KAAK,CAAC,CAAC;AAChF;;;ACnUO,IAAM,UAAU;","names":[]}
package/package.json CHANGED
@@ -1,24 +1,44 @@
1
1
  {
2
2
  "name": "@asentum/sdk",
3
- "version": "0.1.0",
4
- "description": "TypeScript SDK for building on Asentum. Chain reads, wallet management, contract deployment and interaction. Works in Node.js and browsers.",
3
+ "version": "0.2.0",
4
+ "description": "TypeScript SDK for Asentum: chain reads, ase1 addresses, Dilithium3 signing, transactions with in-block and final confirmations, contracts and events. Works in Node.js and browsers.",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
7
7
  "main": "./dist/index.js",
8
+ "module": "./dist/index.js",
8
9
  "types": "./dist/index.d.ts",
9
10
  "exports": {
10
11
  ".": {
11
12
  "types": "./dist/index.d.ts",
12
13
  "import": "./dist/index.js"
13
- }
14
+ },
15
+ "./package.json": "./package.json"
14
16
  },
15
- "files": ["dist", "src", "README.md", "LICENSE"],
16
- "keywords": ["asentum", "blockchain", "sdk", "dilithium", "post-quantum", "wallet", "ethereum-rpc"],
17
+ "files": [
18
+ "dist",
19
+ "README.md",
20
+ "CHANGELOG.md",
21
+ "LICENSE"
22
+ ],
23
+ "sideEffects": false,
24
+ "engines": {
25
+ "node": ">=18"
26
+ },
27
+ "keywords": [
28
+ "asentum",
29
+ "blockchain",
30
+ "sdk",
31
+ "dilithium",
32
+ "ml-dsa",
33
+ "post-quantum",
34
+ "wallet",
35
+ "ase1"
36
+ ],
17
37
  "repository": {
18
38
  "type": "git",
19
39
  "url": "git+https://github.com/asentum-network/sdk.git"
20
40
  },
21
- "homepage": "https://asentum.com",
41
+ "homepage": "https://asentum.com/docs/reference/sdk",
22
42
  "bugs": {
23
43
  "url": "https://github.com/asentum-network/sdk/issues"
24
44
  },
@@ -29,14 +49,15 @@
29
49
  "build": "tsup",
30
50
  "dev": "tsup --watch",
31
51
  "test": "vitest run",
52
+ "test:live": "ASENTUM_SDK_LIVE=1 vitest run test/live.test.ts",
32
53
  "test:watch": "vitest",
33
- "typecheck": "tsc --noEmit",
34
- "prepublishOnly": "npm run build"
54
+ "typecheck": "tsc --noEmit -p tsconfig.json && tsc --noEmit -p tsconfig.test.json",
55
+ "prepublishOnly": "npm run typecheck && npm test && npm run build"
35
56
  },
36
57
  "dependencies": {
37
- "@asentum/crypto": "^0.1.0",
38
- "@asentum/types": "^0.1.0",
39
- "@chainsafe/ssz": "^0.15.0"
58
+ "@chainsafe/ssz": "^0.15.0",
59
+ "@noble/hashes": "^1.4.0",
60
+ "@noble/post-quantum": "~0.2.1"
40
61
  },
41
62
  "devDependencies": {
42
63
  "@types/node": "^20.10.0",