@quaivault/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.cjs +614 -199
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +346 -28
- package/dist/index.d.ts +346 -28
- package/dist/index.js +616 -201
- package/dist/index.js.map +1 -1
- package/package.json +6 -5
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/client.ts","../src/chain/connection.ts","../src/abi/QuaiVault.json","../src/abi/QuaiVaultFactory.json","../src/abi/QuaiVaultProxy.json","../src/abi/SocialRecoveryModule.json","../src/abi/MultiSendCallOnly.json","../src/abi/index.ts","../src/errors/index.ts","../src/config/resolve.ts","../src/config/networks.ts","../src/factory.ts","../src/address.ts","../src/chain/retry.ts","../src/chain/vault-contract.ts","../src/errors/decode.ts","../src/encode/index.ts","../src/types.ts","../src/salt/mine.ts","../src/salt/predict.ts","../src/indexer/client.ts","../src/indexer/schemas.ts","../src/indexer/queries.ts","../src/vault.ts","../src/recovery.ts","../src/chain/recovery-contract.ts","../src/lifecycle/status.ts","../src/balances.ts","../src/indexer/watch.ts","../src/decode/index.ts","../src/lifecycle/affordances.ts","../src/lifecycle/outcome.ts"],"sourcesContent":["/**\n * @quaivault/sdk — TypeScript SDK for QuaiVault multisig vaults on Quai Network.\n *\n * ```ts\n * import { connect } from '@quaivault/sdk';\n *\n * const qv = connect({ network: 'mainnet' });\n * const vault = qv.vault('0x00…');\n * console.log(await vault.info());\n * ```\n */\n\n// --- client\nexport { QuaiVault, QuaiVaultClient, connect } from './client.js';\nexport { Vault, type VaultContext } from './vault.js';\nexport { Factory, type CreateProgress, type FactoryContext } from './factory.js';\nexport { RecoveryModule, type RecoveryModuleContext } from './recovery.js';\nexport {\n loadBalances,\n type BalanceOptions,\n type TokenBalance,\n type VaultBalances,\n} from './balances.js';\nexport { Connection } from './chain/connection.js';\nexport { withRetry, isTransient, type RetryOptions } from './chain/retry.js';\nexport { VaultContract, FactoryContract, type RawTransactionStruct } from './chain/vault-contract.js';\nexport {\n RecoveryContract,\n type RawRecovery,\n type RawRecoveryConfig,\n} from './chain/recovery-contract.js';\n\n// --- configuration\nexport { networks, mainnet, testnet, isNetworkName, type NetworkName } from './config/networks.js';\nexport { resolveConfig, ENV_VARS, type ResolvedConfig } from './config/resolve.js';\n\n// --- indexer\nexport { IndexerClient } from './indexer/client.js';\nexport { IndexerQueries } from './indexer/queries.js';\nexport {\n watchVault,\n type Subscription,\n type WatchEvent,\n type WatchOptions,\n type WatchTopic,\n} from './indexer/watch.js';\nexport * as indexerSchemas from './indexer/schemas.js';\n\n// --- encoding / decoding\nexport {\n selfCall,\n token as tokenCalls,\n recoveryCall,\n encodeMultiSend,\n encodeMultiSendPayload,\n minimumExpiration,\n interfaces,\n MAX_EXECUTION_DELAY,\n MAX_MODULES,\n MAX_OWNERS,\n SENTINEL_MODULES,\n type BatchCall,\n} from './encode/index.js';\nexport {\n decodeCall,\n decodeMultiSendPayload,\n type DecodeContext,\n type DecodeResult,\n type DecodedBatchCall,\n} from './decode/index.js';\n\n// --- lifecycle\nexport {\n classifyExecution,\n extractProposedTxHash,\n type ReceiptLike,\n} from './lifecycle/outcome.js';\nexport {\n deriveStatus,\n deriveRecoveryStatus,\n executableAfterOf,\n isTerminal,\n nowSeconds,\n type RawTransactionState,\n type RawRecoveryState,\n} from './lifecycle/status.js';\nexport {\n computeAffordances,\n allowedActions,\n type AffordanceContext,\n} from './lifecycle/affordances.js';\n\n// --- CREATE2 / salt mining\nexport {\n mineSalt,\n defaultStrategy,\n syncStrategy,\n workerThreadsStrategy,\n type MineSaltOptions,\n type MiningStrategy,\n} from './salt/mine.js';\nexport {\n predictVaultAddress,\n encodeInitData,\n computeBytecodeHash,\n computeFullSalt,\n shardPrefixOf,\n} from './salt/predict.js';\n\n// --- address validation\nexport {\n assertQuaiAddress,\n assertQuaiAddresses,\n inspectAddress,\n isUsableQuaiAddress,\n type AddressCheck,\n type AddressLedger,\n} from './address.js';\n\n// --- errors\nexport {\n QuaiVaultError,\n ConfigError,\n NoSignerError,\n NoIndexerError,\n IndexerQueryError,\n ValidationError,\n NotFoundError,\n PreconditionError,\n RevertError,\n SaltMiningError,\n StaleProposalError,\n type QuaiVaultErrorCode,\n} from './errors/index.js';\nexport { decodeRevert, decodeRevertFromError, knownErrorSelectors, remediationFor } from './errors/decode.js';\n\n// --- ABIs\nexport * from './abi/index.js';\n\n// --- types\nexport * from './types.js';\n","import { getAddress } from 'quais';\nimport type { Provider, Signer } from 'quais';\nimport { Connection } from './chain/connection.js';\nimport { redactConfig, resolveConfig, type PublicConfig, type ResolvedConfig } from './config/resolve.js';\nimport { Factory } from './factory.js';\nimport { IndexerClient } from './indexer/client.js';\nimport { IndexerQueries } from './indexer/queries.js';\nimport { NoIndexerError } from './errors/index.js';\nimport { Vault, type VaultContext } from './vault.js';\nimport type {\n Address,\n ClientOptions,\n IndexerHealth,\n NetworkConfig,\n Pagination,\n} from './types.js';\n\n/**\n * Entry point to the SDK.\n *\n * Construct with {@link connect}. Nothing here performs I/O until a method is\n * called, so building a client is cheap and safe at module scope.\n */\nexport class QuaiVaultClient {\n /**\n * Resolved configuration, with the private key stripped and the indexer key\n * masked — safe to log. The key itself is consumed once when building the signer.\n */\n readonly config: PublicConfig;\n readonly connection: Connection;\n readonly factory: Factory;\n readonly indexer: IndexerClient | null;\n readonly queries: IndexerQueries | null;\n\n constructor(options: ClientOptions = {}) {\n // `resolved` holds the secret and is never stored on the instance.\n const resolved: ResolvedConfig = resolveConfig(options);\n this.config = redactConfig(resolved);\n this.connection = new Connection(resolved, {\n ...(options.provider ? { provider: options.provider } : {}),\n ...(options.signer ? { signer: options.signer } : {}),\n });\n\n // Built from `resolved`, not `this.config` — the latter's indexer key is masked.\n this.indexer = resolved.indexer ? new IndexerClient(resolved.indexer) : null;\n this.queries = this.indexer ? new IndexerQueries(this.indexer) : null;\n\n this.factory = new Factory({\n connection: this.connection,\n contracts: this.config.contracts,\n });\n }\n\n get network(): NetworkConfig {\n return this.config.network;\n }\n\n get provider(): Provider {\n return this.connection.provider;\n }\n\n get signer(): Signer | null {\n return this.connection.signer;\n }\n\n /** The connected address, or null when read-only. */\n async address(): Promise<Address | null> {\n return this.connection.addressOrNull();\n }\n\n /** A handle to one vault. No I/O. */\n vault(address: Address): Vault {\n return new Vault(address, this.vaultContext());\n }\n\n private vaultContext(): VaultContext {\n return {\n connection: this.connection,\n indexer: this.indexer,\n queries: this.queries,\n contracts: this.config.contracts,\n consistency: this.config.consistency,\n maxIndexerLagBlocks: this.config.maxIndexerLagBlocks,\n };\n }\n\n /** Vault discovery. Requires the indexer — there is no on-chain reverse index. */\n readonly vaults = {\n /**\n * Vaults where `owner` is an active owner.\n *\n * Indexer-only: `factory.getWalletsByCreator` was removed from the contracts for\n * gas reasons, and the factory registry is not indexed by owner.\n */\n forOwner: async (owner: Address, options: Pagination = {}): Promise<Address[]> => {\n const queries = this.requireQueries('Looking up vaults by owner');\n const rows = await queries.vaultsForOwner(getAddress(owner), options);\n return rows.map((r) => getAddress(r.address));\n },\n\n /** Vaults where `guardian` is an active social-recovery guardian. */\n forGuardian: async (guardian: Address, options: Pagination = {}): Promise<Address[]> => {\n const queries = this.requireQueries('Looking up vaults by guardian');\n const rows = await queries.vaultsForGuardian(getAddress(guardian), options);\n return rows.map((r) => getAddress(r.address));\n },\n\n /** Whether an address is a vault this factory deployed or registered. */\n exists: async (address: Address): Promise<boolean> => {\n return this.factory.isRegistered(getAddress(address));\n },\n\n get: (address: Address): Vault => this.vault(address),\n };\n\n private requireQueries(operation: string): IndexerQueries {\n if (!this.queries) throw new NoIndexerError(operation);\n return this.queries;\n }\n\n /** Indexer liveness and lag. Reports unavailable when no indexer is configured. */\n async indexerHealth(): Promise<IndexerHealth> {\n if (!this.indexer) {\n return {\n available: false,\n lastIndexedBlock: 0,\n isSyncing: false,\n error: 'no indexer configured',\n };\n }\n return this.indexer.health();\n }\n}\n\n/**\n * Create a client.\n *\n * Configuration resolves in order of decreasing precedence: explicit options,\n * environment variables, then the network preset. With nothing supplied it targets\n * mainnet over the public RPC in read-only mode.\n *\n * ```ts\n * // read-only, from env (QUAIVAULT_NETWORK, QUAIVAULT_INDEXER_ANON_KEY, …)\n * const qv = connect();\n *\n * // read-write against testnet\n * const qv = connect({ network: 'testnet', privateKey: process.env.KEY });\n * ```\n */\nexport function connect(options: ClientOptions = {}): QuaiVaultClient {\n return new QuaiVaultClient(options);\n}\n\n/** Namespace form, for callers who prefer `QuaiVault.connect(…)`. */\nexport const QuaiVault = { connect };\n","import { Contract, JsonRpcProvider, Wallet, getZoneForAddress, isQuaiAddress } from 'quais';\nimport type { Provider, Signer } from 'quais';\nimport { QuaiVaultAbi, QuaiVaultFactoryAbi, SocialRecoveryModuleAbi } from '../abi/index.js';\nimport type { Address } from '../types.js';\nimport { ConfigError, NoSignerError, ValidationError } from '../errors/index.js';\nimport type { ResolvedConfig } from '../config/resolve.js';\nimport type { RetryOptions } from './retry.js';\n\n/**\n * Owns the provider/signer pair and hands out contract instances.\n *\n * Quai RPC endpoints are shard-pathed (`https://host/cyprus1`), which `quais`\n * handles via `usePathing: true` — the same setting the indexer uses.\n */\nexport class Connection {\n readonly provider: Provider;\n /** Retry policy for reads. Shared with every contract facade this hands out. */\n readonly retry: RetryOptions;\n private readonly _signer: Signer | null;\n\n constructor(config: ResolvedConfig, explicit: { provider?: Provider; signer?: Signer } = {}) {\n this.retry = config.retry ?? {};\n this.provider =\n explicit.provider ??\n (explicit.signer?.provider as Provider | undefined) ??\n new JsonRpcProvider(config.rpcUrl, undefined, { usePathing: true });\n\n if (explicit.signer) {\n this._signer = explicit.signer;\n } else if (config.privateKey) {\n this._signer = createPrivateKeySigner(config.privateKey, this.provider);\n } else {\n this._signer = null;\n }\n }\n\n get signer(): Signer | null {\n return this._signer;\n }\n\n hasSigner(): boolean {\n return this._signer !== null;\n }\n\n /** The signer, or a typed error naming the operation that needs one. */\n requireSigner(operation: string): Signer {\n if (!this._signer) throw new NoSignerError(operation);\n return this._signer;\n }\n\n async address(): Promise<Address> {\n return this.requireSigner('Reading the connected address').getAddress();\n }\n\n /** Connected address, or null when read-only. */\n async addressOrNull(): Promise<Address | null> {\n return this._signer ? this._signer.getAddress() : null;\n }\n\n vault(address: Address, write = false): Contract {\n return new Contract(\n address,\n QuaiVaultAbi,\n write ? this.requireSigner('This vault write') : this.provider,\n );\n }\n\n factory(address: Address, write = false): Contract {\n return new Contract(\n address,\n QuaiVaultFactoryAbi,\n write ? this.requireSigner('This factory write') : this.provider,\n );\n }\n\n socialRecovery(address: Address, write = false): Contract {\n return new Contract(\n address,\n SocialRecoveryModuleAbi,\n write ? this.requireSigner('This recovery write') : this.provider,\n );\n }\n}\n\nfunction createPrivateKeySigner(privateKey: string, provider: Provider): Signer {\n const normalized = privateKey.startsWith('0x') ? privateKey : `0x${privateKey}`;\n if (!/^0x[0-9a-fA-F]{64}$/.test(normalized)) {\n throw new ConfigError(\n 'Invalid private key: expected 32 bytes of hex (64 characters, with or without a 0x prefix).',\n 'Check QUAIVAULT_PRIVATE_KEY. Never commit a private key or pass one on the command line.',\n );\n }\n try {\n const wallet = new Wallet(normalized, provider);\n\n // A usable key must satisfy two independent constraints, and an arbitrary\n // secp256k1 key generally satisfies neither:\n //\n // 1. its address falls inside a real shard prefix (`getZoneForAddress`), and\n // 2. it is on the Quai ledger rather than Qi (`isQuaiAddress`).\n //\n // These are genuinely separate: 0x7E5F… passes `isQuaiAddress` but maps to no\n // zone. Checking only the ledger bit would let such a key through, and the\n // failure would surface much later as an opaque RPC error on the first\n // transaction. Quai HD derivation scans for keys meeting both.\n const zone = getZoneForAddress(wallet.address);\n if (!zone) {\n throw new ConfigError(\n `The supplied private key derives ${wallet.address}, which does not fall within any ` +\n 'Quai shard prefix, so it cannot hold funds or transact.',\n 'Use a key from a Quai wallet — quais HD derivation scans for shard-valid addresses. ' +\n 'An arbitrary Ethereum key will not work.',\n );\n }\n if (!isQuaiAddress(wallet.address)) {\n throw new ConfigError(\n `The supplied private key derives ${wallet.address}, which is a Qi-ledger address. ` +\n 'QuaiVault operates on the Quai ledger.',\n 'Use a Quai-ledger key.',\n );\n }\n return wallet as unknown as Signer;\n } catch (cause) {\n if (cause instanceof ConfigError) throw cause;\n throw new ConfigError(\n `Could not build a signer from the supplied private key: ${\n cause instanceof Error ? cause.message : String(cause)\n }`,\n );\n }\n}\n\n/** Assert a value is a 32-byte hex string, returning it lowercased. */\nexport function normalizeTxHash(value: unknown, label = 'transaction hash'): string {\n if (typeof value !== 'string' || !/^0x[0-9a-fA-F]{64}$/.test(value)) {\n throw new ValidationError(`Invalid ${label}: expected a 0x-prefixed 32-byte hex string.`);\n }\n return value.toLowerCase();\n}\n","{\n \"contractName\": \"QuaiVault\",\n \"abi\": [\n {\n \"inputs\": [],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"constructor\"\n },\n {\n \"inputs\": [],\n \"name\": \"AlreadyAnOwner\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"AlreadyApproved\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"CalldataTooShort\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"CannotCancelApprovedTransaction\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"CannotRemoveOwnerWouldFallBelowThreshold\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"target\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"DelegateCallNotAllowed\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"target\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"DelegatecallTargetAlreadyAllowed\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"target\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"DelegatecallTargetNotAllowed\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"DuplicateOwner\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"ExecutionDelayTooLong\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"uint256\",\n \"name\": \"minimumExpiration\",\n \"type\": \"uint256\"\n }\n ],\n \"name\": \"ExpirationTooSoon\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"ImplementationSlotTampered\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"InvalidDestinationAddress\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"InvalidInitialization\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"module\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"InvalidModule\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"InvalidOwnerAddress\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"prevModule\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"InvalidPrevModule\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"InvalidThreshold\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"MaxModulesReached\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"MaxOwnersReached\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"MessageNotSigned\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"ModuleAlreadyEnabled\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"ModuleNotEnabled\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"NotAnAuthorizedModule\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"NotAnOwner\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"NotApproved\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"NotEnoughApprovals\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"NotInitializing\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"NotProposer\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"OnlySelf\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"OwnersRequired\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"ReentrancyGuardReentrantCall\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"SelfCallCannotHaveValue\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"uint256\",\n \"name\": \"executableAfter\",\n \"type\": \"uint256\"\n }\n ],\n \"name\": \"TimelockNotElapsed\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"TooManyOwners\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"TransactionAlreadyCancelled\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"TransactionAlreadyExecuted\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"TransactionAlreadyExists\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"TransactionDoesNotExist\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"TransactionIsExpired\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"TransactionNotExpired\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"bytes4\",\n \"name\": \"selector\",\n \"type\": \"bytes4\"\n }\n ],\n \"name\": \"UnrecognizedSelfCall\",\n \"type\": \"error\"\n },\n {\n \"anonymous\": false,\n \"inputs\": [\n {\n \"indexed\": true,\n \"internalType\": \"bytes32\",\n \"name\": \"txHash\",\n \"type\": \"bytes32\"\n },\n {\n \"indexed\": true,\n \"internalType\": \"address\",\n \"name\": \"owner\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"ApprovalRevoked\",\n \"type\": \"event\"\n },\n {\n \"anonymous\": false,\n \"inputs\": [\n {\n \"indexed\": true,\n \"internalType\": \"address\",\n \"name\": \"target\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"DelegatecallTargetAdded\",\n \"type\": \"event\"\n },\n {\n \"anonymous\": false,\n \"inputs\": [\n {\n \"indexed\": true,\n \"internalType\": \"address\",\n \"name\": \"target\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"DelegatecallTargetRemoved\",\n \"type\": \"event\"\n },\n {\n \"anonymous\": false,\n \"inputs\": [\n {\n \"indexed\": true,\n \"internalType\": \"address\",\n \"name\": \"module\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"DisabledModule\",\n \"type\": \"event\"\n },\n {\n \"anonymous\": false,\n \"inputs\": [\n {\n \"indexed\": true,\n \"internalType\": \"address\",\n \"name\": \"module\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"EnabledModule\",\n \"type\": \"event\"\n },\n {\n \"anonymous\": false,\n \"inputs\": [\n {\n \"indexed\": true,\n \"internalType\": \"address\",\n \"name\": \"module\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"ExecutionFromModuleFailure\",\n \"type\": \"event\"\n },\n {\n \"anonymous\": false,\n \"inputs\": [\n {\n \"indexed\": true,\n \"internalType\": \"address\",\n \"name\": \"module\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"ExecutionFromModuleSuccess\",\n \"type\": \"event\"\n },\n {\n \"anonymous\": false,\n \"inputs\": [\n {\n \"indexed\": false,\n \"internalType\": \"uint64\",\n \"name\": \"version\",\n \"type\": \"uint64\"\n }\n ],\n \"name\": \"Initialized\",\n \"type\": \"event\"\n },\n {\n \"anonymous\": false,\n \"inputs\": [\n {\n \"indexed\": true,\n \"internalType\": \"bytes32\",\n \"name\": \"msgHash\",\n \"type\": \"bytes32\"\n },\n {\n \"indexed\": false,\n \"internalType\": \"bytes\",\n \"name\": \"data\",\n \"type\": \"bytes\"\n }\n ],\n \"name\": \"MessageSigned\",\n \"type\": \"event\"\n },\n {\n \"anonymous\": false,\n \"inputs\": [\n {\n \"indexed\": true,\n \"internalType\": \"bytes32\",\n \"name\": \"msgHash\",\n \"type\": \"bytes32\"\n },\n {\n \"indexed\": false,\n \"internalType\": \"bytes\",\n \"name\": \"data\",\n \"type\": \"bytes\"\n }\n ],\n \"name\": \"MessageUnsigned\",\n \"type\": \"event\"\n },\n {\n \"anonymous\": false,\n \"inputs\": [\n {\n \"indexed\": false,\n \"internalType\": \"uint32\",\n \"name\": \"oldDelay\",\n \"type\": \"uint32\"\n },\n {\n \"indexed\": false,\n \"internalType\": \"uint32\",\n \"name\": \"newDelay\",\n \"type\": \"uint32\"\n }\n ],\n \"name\": \"MinExecutionDelayChanged\",\n \"type\": \"event\"\n },\n {\n \"anonymous\": false,\n \"inputs\": [\n {\n \"indexed\": true,\n \"internalType\": \"address\",\n \"name\": \"owner\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"OwnerAdded\",\n \"type\": \"event\"\n },\n {\n \"anonymous\": false,\n \"inputs\": [\n {\n \"indexed\": true,\n \"internalType\": \"address\",\n \"name\": \"owner\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"OwnerRemoved\",\n \"type\": \"event\"\n },\n {\n \"anonymous\": false,\n \"inputs\": [\n {\n \"indexed\": true,\n \"internalType\": \"address\",\n \"name\": \"sender\",\n \"type\": \"address\"\n },\n {\n \"indexed\": false,\n \"internalType\": \"uint256\",\n \"name\": \"amount\",\n \"type\": \"uint256\"\n }\n ],\n \"name\": \"Received\",\n \"type\": \"event\"\n },\n {\n \"anonymous\": false,\n \"inputs\": [\n {\n \"indexed\": false,\n \"internalType\": \"uint256\",\n \"name\": \"threshold\",\n \"type\": \"uint256\"\n }\n ],\n \"name\": \"ThresholdChanged\",\n \"type\": \"event\"\n },\n {\n \"anonymous\": false,\n \"inputs\": [\n {\n \"indexed\": true,\n \"internalType\": \"bytes32\",\n \"name\": \"txHash\",\n \"type\": \"bytes32\"\n },\n {\n \"indexed\": false,\n \"internalType\": \"uint48\",\n \"name\": \"approvedAt\",\n \"type\": \"uint48\"\n },\n {\n \"indexed\": false,\n \"internalType\": \"uint256\",\n \"name\": \"executableAfter\",\n \"type\": \"uint256\"\n }\n ],\n \"name\": \"ThresholdReached\",\n \"type\": \"event\"\n },\n {\n \"anonymous\": false,\n \"inputs\": [\n {\n \"indexed\": true,\n \"internalType\": \"bytes32\",\n \"name\": \"txHash\",\n \"type\": \"bytes32\"\n },\n {\n \"indexed\": true,\n \"internalType\": \"address\",\n \"name\": \"approver\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"TransactionApproved\",\n \"type\": \"event\"\n },\n {\n \"anonymous\": false,\n \"inputs\": [\n {\n \"indexed\": true,\n \"internalType\": \"bytes32\",\n \"name\": \"txHash\",\n \"type\": \"bytes32\"\n },\n {\n \"indexed\": true,\n \"internalType\": \"address\",\n \"name\": \"canceller\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"TransactionCancelled\",\n \"type\": \"event\"\n },\n {\n \"anonymous\": false,\n \"inputs\": [\n {\n \"indexed\": true,\n \"internalType\": \"bytes32\",\n \"name\": \"txHash\",\n \"type\": \"bytes32\"\n },\n {\n \"indexed\": true,\n \"internalType\": \"address\",\n \"name\": \"executor\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"TransactionExecuted\",\n \"type\": \"event\"\n },\n {\n \"anonymous\": false,\n \"inputs\": [\n {\n \"indexed\": true,\n \"internalType\": \"bytes32\",\n \"name\": \"txHash\",\n \"type\": \"bytes32\"\n }\n ],\n \"name\": \"TransactionExpired\",\n \"type\": \"event\"\n },\n {\n \"anonymous\": false,\n \"inputs\": [\n {\n \"indexed\": true,\n \"internalType\": \"bytes32\",\n \"name\": \"txHash\",\n \"type\": \"bytes32\"\n },\n {\n \"indexed\": true,\n \"internalType\": \"address\",\n \"name\": \"executor\",\n \"type\": \"address\"\n },\n {\n \"indexed\": false,\n \"internalType\": \"bytes\",\n \"name\": \"returnData\",\n \"type\": \"bytes\"\n }\n ],\n \"name\": \"TransactionFailed\",\n \"type\": \"event\"\n },\n {\n \"anonymous\": false,\n \"inputs\": [\n {\n \"indexed\": true,\n \"internalType\": \"bytes32\",\n \"name\": \"txHash\",\n \"type\": \"bytes32\"\n },\n {\n \"indexed\": true,\n \"internalType\": \"address\",\n \"name\": \"proposer\",\n \"type\": \"address\"\n },\n {\n \"indexed\": true,\n \"internalType\": \"address\",\n \"name\": \"to\",\n \"type\": \"address\"\n },\n {\n \"indexed\": false,\n \"internalType\": \"uint256\",\n \"name\": \"value\",\n \"type\": \"uint256\"\n },\n {\n \"indexed\": false,\n \"internalType\": \"bytes\",\n \"name\": \"data\",\n \"type\": \"bytes\"\n },\n {\n \"indexed\": false,\n \"internalType\": \"uint48\",\n \"name\": \"expiration\",\n \"type\": \"uint48\"\n },\n {\n \"indexed\": false,\n \"internalType\": \"uint32\",\n \"name\": \"executionDelay\",\n \"type\": \"uint32\"\n }\n ],\n \"name\": \"TransactionProposed\",\n \"type\": \"event\"\n },\n {\n \"stateMutability\": \"payable\",\n \"type\": \"fallback\"\n },\n {\n \"inputs\": [],\n \"name\": \"MAX_EXECUTION_DELAY\",\n \"outputs\": [\n {\n \"internalType\": \"uint32\",\n \"name\": \"\",\n \"type\": \"uint32\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [],\n \"name\": \"MAX_MODULES\",\n \"outputs\": [\n {\n \"internalType\": \"uint256\",\n \"name\": \"\",\n \"type\": \"uint256\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [],\n \"name\": \"MAX_OWNERS\",\n \"outputs\": [\n {\n \"internalType\": \"uint256\",\n \"name\": \"\",\n \"type\": \"uint256\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"target\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"addDelegatecallTarget\",\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"owner\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"addOwner\",\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"bytes32\",\n \"name\": \"txHash\",\n \"type\": \"bytes32\"\n }\n ],\n \"name\": \"approveAndExecute\",\n \"outputs\": [\n {\n \"internalType\": \"bool\",\n \"name\": \"executed\",\n \"type\": \"bool\"\n }\n ],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"bytes32\",\n \"name\": \"txHash\",\n \"type\": \"bytes32\"\n }\n ],\n \"name\": \"approveTransaction\",\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"bytes32\",\n \"name\": \"txHash\",\n \"type\": \"bytes32\"\n }\n ],\n \"name\": \"cancelByConsensus\",\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"bytes32\",\n \"name\": \"txHash\",\n \"type\": \"bytes32\"\n }\n ],\n \"name\": \"cancelTransaction\",\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"uint256\",\n \"name\": \"_threshold\",\n \"type\": \"uint256\"\n }\n ],\n \"name\": \"changeThreshold\",\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"delegatecallAllowed\",\n \"outputs\": [\n {\n \"internalType\": \"bool\",\n \"name\": \"\",\n \"type\": \"bool\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"prevModule\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"address\",\n \"name\": \"module\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"disableModule\",\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [],\n \"name\": \"domainSeparator\",\n \"outputs\": [\n {\n \"internalType\": \"bytes32\",\n \"name\": \"\",\n \"type\": \"bytes32\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"module\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"enableModule\",\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"bytes\",\n \"name\": \"message\",\n \"type\": \"bytes\"\n }\n ],\n \"name\": \"encodeMessageData\",\n \"outputs\": [\n {\n \"internalType\": \"bytes\",\n \"name\": \"\",\n \"type\": \"bytes\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"to\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"value\",\n \"type\": \"uint256\"\n },\n {\n \"internalType\": \"bytes\",\n \"name\": \"data\",\n \"type\": \"bytes\"\n }\n ],\n \"name\": \"execTransactionFromModule\",\n \"outputs\": [\n {\n \"internalType\": \"bool\",\n \"name\": \"success\",\n \"type\": \"bool\"\n }\n ],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"to\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"value\",\n \"type\": \"uint256\"\n },\n {\n \"internalType\": \"bytes\",\n \"name\": \"data\",\n \"type\": \"bytes\"\n },\n {\n \"internalType\": \"enum Enum.Operation\",\n \"name\": \"operation\",\n \"type\": \"uint8\"\n }\n ],\n \"name\": \"execTransactionFromModule\",\n \"outputs\": [\n {\n \"internalType\": \"bool\",\n \"name\": \"success\",\n \"type\": \"bool\"\n }\n ],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"to\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"value\",\n \"type\": \"uint256\"\n },\n {\n \"internalType\": \"bytes\",\n \"name\": \"data\",\n \"type\": \"bytes\"\n },\n {\n \"internalType\": \"enum Enum.Operation\",\n \"name\": \"operation\",\n \"type\": \"uint8\"\n }\n ],\n \"name\": \"execTransactionFromModuleReturnData\",\n \"outputs\": [\n {\n \"internalType\": \"bool\",\n \"name\": \"success\",\n \"type\": \"bool\"\n },\n {\n \"internalType\": \"bytes\",\n \"name\": \"returnData\",\n \"type\": \"bytes\"\n }\n ],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"bytes32\",\n \"name\": \"txHash\",\n \"type\": \"bytes32\"\n }\n ],\n \"name\": \"executeTransaction\",\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"bytes32\",\n \"name\": \"txHash\",\n \"type\": \"bytes32\"\n }\n ],\n \"name\": \"expireTransaction\",\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"bytes32\",\n \"name\": \"\",\n \"type\": \"bytes32\"\n }\n ],\n \"name\": \"expiredTxs\",\n \"outputs\": [\n {\n \"internalType\": \"bool\",\n \"name\": \"\",\n \"type\": \"bool\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"bytes\",\n \"name\": \"message\",\n \"type\": \"bytes\"\n }\n ],\n \"name\": \"getMessageHash\",\n \"outputs\": [\n {\n \"internalType\": \"bytes32\",\n \"name\": \"\",\n \"type\": \"bytes32\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [],\n \"name\": \"getModules\",\n \"outputs\": [\n {\n \"internalType\": \"address[]\",\n \"name\": \"\",\n \"type\": \"address[]\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"start\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"pageSize\",\n \"type\": \"uint256\"\n }\n ],\n \"name\": \"getModulesPaginated\",\n \"outputs\": [\n {\n \"internalType\": \"address[]\",\n \"name\": \"array\",\n \"type\": \"address[]\"\n },\n {\n \"internalType\": \"address\",\n \"name\": \"next\",\n \"type\": \"address\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [],\n \"name\": \"getOwnerCount\",\n \"outputs\": [\n {\n \"internalType\": \"uint256\",\n \"name\": \"\",\n \"type\": \"uint256\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [],\n \"name\": \"getOwners\",\n \"outputs\": [\n {\n \"internalType\": \"address[]\",\n \"name\": \"\",\n \"type\": \"address[]\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"bytes32\",\n \"name\": \"txHash\",\n \"type\": \"bytes32\"\n }\n ],\n \"name\": \"getTransaction\",\n \"outputs\": [\n {\n \"components\": [\n {\n \"internalType\": \"address\",\n \"name\": \"to\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"uint48\",\n \"name\": \"timestamp\",\n \"type\": \"uint48\"\n },\n {\n \"internalType\": \"uint48\",\n \"name\": \"expiration\",\n \"type\": \"uint48\"\n },\n {\n \"internalType\": \"address\",\n \"name\": \"proposer\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"bool\",\n \"name\": \"executed\",\n \"type\": \"bool\"\n },\n {\n \"internalType\": \"bool\",\n \"name\": \"cancelled\",\n \"type\": \"bool\"\n },\n {\n \"internalType\": \"uint48\",\n \"name\": \"approvedAt\",\n \"type\": \"uint48\"\n },\n {\n \"internalType\": \"uint32\",\n \"name\": \"executionDelay\",\n \"type\": \"uint32\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"value\",\n \"type\": \"uint256\"\n },\n {\n \"internalType\": \"bytes\",\n \"name\": \"data\",\n \"type\": \"bytes\"\n }\n ],\n \"internalType\": \"struct QuaiVault.Transaction\",\n \"name\": \"\",\n \"type\": \"tuple\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"to\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"value\",\n \"type\": \"uint256\"\n },\n {\n \"internalType\": \"bytes\",\n \"name\": \"data\",\n \"type\": \"bytes\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"_nonce\",\n \"type\": \"uint256\"\n }\n ],\n \"name\": \"getTransactionHash\",\n \"outputs\": [\n {\n \"internalType\": \"bytes32\",\n \"name\": \"\",\n \"type\": \"bytes32\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"bytes32\",\n \"name\": \"txHash\",\n \"type\": \"bytes32\"\n },\n {\n \"internalType\": \"address\",\n \"name\": \"owner\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"hasApproved\",\n \"outputs\": [\n {\n \"internalType\": \"bool\",\n \"name\": \"\",\n \"type\": \"bool\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address[]\",\n \"name\": \"_owners\",\n \"type\": \"address[]\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"_threshold\",\n \"type\": \"uint256\"\n },\n {\n \"internalType\": \"uint32\",\n \"name\": \"_minExecutionDelay\",\n \"type\": \"uint32\"\n },\n {\n \"internalType\": \"address[]\",\n \"name\": \"_initialModules\",\n \"type\": \"address[]\"\n },\n {\n \"internalType\": \"address[]\",\n \"name\": \"_initialDelegatecallTargets\",\n \"type\": \"address[]\"\n }\n ],\n \"name\": \"initialize\",\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"module\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"isModuleEnabled\",\n \"outputs\": [\n {\n \"internalType\": \"bool\",\n \"name\": \"\",\n \"type\": \"bool\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"isOwner\",\n \"outputs\": [\n {\n \"internalType\": \"bool\",\n \"name\": \"\",\n \"type\": \"bool\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"bytes32\",\n \"name\": \"_dataHash\",\n \"type\": \"bytes32\"\n },\n {\n \"internalType\": \"bytes\",\n \"name\": \"\",\n \"type\": \"bytes\"\n }\n ],\n \"name\": \"isValidSignature\",\n \"outputs\": [\n {\n \"internalType\": \"bytes4\",\n \"name\": \"\",\n \"type\": \"bytes4\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [],\n \"name\": \"minExecutionDelay\",\n \"outputs\": [\n {\n \"internalType\": \"uint32\",\n \"name\": \"\",\n \"type\": \"uint32\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [],\n \"name\": \"moduleCount\",\n \"outputs\": [\n {\n \"internalType\": \"uint256\",\n \"name\": \"\",\n \"type\": \"uint256\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [],\n \"name\": \"nonce\",\n \"outputs\": [\n {\n \"internalType\": \"uint256\",\n \"name\": \"\",\n \"type\": \"uint256\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"address\",\n \"name\": \"\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"uint256[]\",\n \"name\": \"\",\n \"type\": \"uint256[]\"\n },\n {\n \"internalType\": \"uint256[]\",\n \"name\": \"\",\n \"type\": \"uint256[]\"\n },\n {\n \"internalType\": \"bytes\",\n \"name\": \"\",\n \"type\": \"bytes\"\n }\n ],\n \"name\": \"onERC1155BatchReceived\",\n \"outputs\": [\n {\n \"internalType\": \"bytes4\",\n \"name\": \"\",\n \"type\": \"bytes4\"\n }\n ],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"address\",\n \"name\": \"\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"\",\n \"type\": \"uint256\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"\",\n \"type\": \"uint256\"\n },\n {\n \"internalType\": \"bytes\",\n \"name\": \"\",\n \"type\": \"bytes\"\n }\n ],\n \"name\": \"onERC1155Received\",\n \"outputs\": [\n {\n \"internalType\": \"bytes4\",\n \"name\": \"\",\n \"type\": \"bytes4\"\n }\n ],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"address\",\n \"name\": \"\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"\",\n \"type\": \"uint256\"\n },\n {\n \"internalType\": \"bytes\",\n \"name\": \"\",\n \"type\": \"bytes\"\n }\n ],\n \"name\": \"onERC721Received\",\n \"outputs\": [\n {\n \"internalType\": \"bytes4\",\n \"name\": \"\",\n \"type\": \"bytes4\"\n }\n ],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"ownerVersions\",\n \"outputs\": [\n {\n \"internalType\": \"uint256\",\n \"name\": \"\",\n \"type\": \"uint256\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"uint256\",\n \"name\": \"\",\n \"type\": \"uint256\"\n }\n ],\n \"name\": \"owners\",\n \"outputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"\",\n \"type\": \"address\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"to\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"value\",\n \"type\": \"uint256\"\n },\n {\n \"internalType\": \"bytes\",\n \"name\": \"data\",\n \"type\": \"bytes\"\n },\n {\n \"internalType\": \"uint48\",\n \"name\": \"expiration\",\n \"type\": \"uint48\"\n }\n ],\n \"name\": \"proposeTransaction\",\n \"outputs\": [\n {\n \"internalType\": \"bytes32\",\n \"name\": \"\",\n \"type\": \"bytes32\"\n }\n ],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"to\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"value\",\n \"type\": \"uint256\"\n },\n {\n \"internalType\": \"bytes\",\n \"name\": \"data\",\n \"type\": \"bytes\"\n },\n {\n \"internalType\": \"uint48\",\n \"name\": \"expiration\",\n \"type\": \"uint48\"\n },\n {\n \"internalType\": \"uint32\",\n \"name\": \"requestedDelay\",\n \"type\": \"uint32\"\n }\n ],\n \"name\": \"proposeTransaction\",\n \"outputs\": [\n {\n \"internalType\": \"bytes32\",\n \"name\": \"\",\n \"type\": \"bytes32\"\n }\n ],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"to\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"value\",\n \"type\": \"uint256\"\n },\n {\n \"internalType\": \"bytes\",\n \"name\": \"data\",\n \"type\": \"bytes\"\n }\n ],\n \"name\": \"proposeTransaction\",\n \"outputs\": [\n {\n \"internalType\": \"bytes32\",\n \"name\": \"\",\n \"type\": \"bytes32\"\n }\n ],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"target\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"removeDelegatecallTarget\",\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"owner\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"removeOwner\",\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"bytes32\",\n \"name\": \"txHash\",\n \"type\": \"bytes32\"\n }\n ],\n \"name\": \"revokeApproval\",\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"uint32\",\n \"name\": \"delay\",\n \"type\": \"uint32\"\n }\n ],\n \"name\": \"setMinExecutionDelay\",\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"bytes\",\n \"name\": \"data\",\n \"type\": \"bytes\"\n }\n ],\n \"name\": \"signMessage\",\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"bytes32\",\n \"name\": \"\",\n \"type\": \"bytes32\"\n }\n ],\n \"name\": \"signedMessages\",\n \"outputs\": [\n {\n \"internalType\": \"bool\",\n \"name\": \"\",\n \"type\": \"bool\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"bytes4\",\n \"name\": \"interfaceId\",\n \"type\": \"bytes4\"\n }\n ],\n \"name\": \"supportsInterface\",\n \"outputs\": [\n {\n \"internalType\": \"bool\",\n \"name\": \"\",\n \"type\": \"bool\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [],\n \"name\": \"threshold\",\n \"outputs\": [\n {\n \"internalType\": \"uint256\",\n \"name\": \"\",\n \"type\": \"uint256\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"bytes32\",\n \"name\": \"\",\n \"type\": \"bytes32\"\n }\n ],\n \"name\": \"transactions\",\n \"outputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"to\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"uint48\",\n \"name\": \"timestamp\",\n \"type\": \"uint48\"\n },\n {\n \"internalType\": \"uint48\",\n \"name\": \"expiration\",\n \"type\": \"uint48\"\n },\n {\n \"internalType\": \"address\",\n \"name\": \"proposer\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"bool\",\n \"name\": \"executed\",\n \"type\": \"bool\"\n },\n {\n \"internalType\": \"bool\",\n \"name\": \"cancelled\",\n \"type\": \"bool\"\n },\n {\n \"internalType\": \"uint48\",\n \"name\": \"approvedAt\",\n \"type\": \"uint48\"\n },\n {\n \"internalType\": \"uint32\",\n \"name\": \"executionDelay\",\n \"type\": \"uint32\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"value\",\n \"type\": \"uint256\"\n },\n {\n \"internalType\": \"bytes\",\n \"name\": \"data\",\n \"type\": \"bytes\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"bytes\",\n \"name\": \"data\",\n \"type\": \"bytes\"\n }\n ],\n \"name\": \"unsignMessage\",\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"stateMutability\": \"payable\",\n \"type\": \"receive\"\n }\n ]\n}\n","{\n \"contractName\": \"QuaiVaultFactory\",\n \"abi\": [\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"_implementation\",\n \"type\": \"address\"\n }\n ],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"constructor\"\n },\n {\n \"inputs\": [],\n \"name\": \"CallerIsNotAnOwner\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"DuplicateOwner\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"ExecutionDelayTooLong\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"InvalidImplementationAddress\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"InvalidOwnerAddress\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"InvalidThreshold\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"InvalidWalletAddress\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"InvalidWalletImplementation\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"OwnersRequired\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"TooManyOwners\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"WalletAlreadyRegistered\",\n \"type\": \"error\"\n },\n {\n \"anonymous\": false,\n \"inputs\": [\n {\n \"indexed\": true,\n \"internalType\": \"address\",\n \"name\": \"wallet\",\n \"type\": \"address\"\n },\n {\n \"indexed\": false,\n \"internalType\": \"address[]\",\n \"name\": \"owners\",\n \"type\": \"address[]\"\n },\n {\n \"indexed\": false,\n \"internalType\": \"uint256\",\n \"name\": \"threshold\",\n \"type\": \"uint256\"\n },\n {\n \"indexed\": true,\n \"internalType\": \"address\",\n \"name\": \"creator\",\n \"type\": \"address\"\n },\n {\n \"indexed\": false,\n \"internalType\": \"bytes32\",\n \"name\": \"salt\",\n \"type\": \"bytes32\"\n }\n ],\n \"name\": \"WalletCreated\",\n \"type\": \"event\"\n },\n {\n \"anonymous\": false,\n \"inputs\": [\n {\n \"indexed\": true,\n \"internalType\": \"address\",\n \"name\": \"wallet\",\n \"type\": \"address\"\n },\n {\n \"indexed\": true,\n \"internalType\": \"address\",\n \"name\": \"registrar\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"WalletRegistered\",\n \"type\": \"event\"\n },\n {\n \"inputs\": [],\n \"name\": \"MAX_EXECUTION_DELAY\",\n \"outputs\": [\n {\n \"internalType\": \"uint32\",\n \"name\": \"\",\n \"type\": \"uint32\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address[]\",\n \"name\": \"owners\",\n \"type\": \"address[]\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"threshold\",\n \"type\": \"uint256\"\n },\n {\n \"internalType\": \"bytes32\",\n \"name\": \"salt\",\n \"type\": \"bytes32\"\n }\n ],\n \"name\": \"createWallet\",\n \"outputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"wallet\",\n \"type\": \"address\"\n }\n ],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address[]\",\n \"name\": \"owners\",\n \"type\": \"address[]\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"threshold\",\n \"type\": \"uint256\"\n },\n {\n \"internalType\": \"bytes32\",\n \"name\": \"salt\",\n \"type\": \"bytes32\"\n },\n {\n \"internalType\": \"uint32\",\n \"name\": \"minExecutionDelay\",\n \"type\": \"uint32\"\n },\n {\n \"internalType\": \"address[]\",\n \"name\": \"initialModules\",\n \"type\": \"address[]\"\n }\n ],\n \"name\": \"createWallet\",\n \"outputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"wallet\",\n \"type\": \"address\"\n }\n ],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address[]\",\n \"name\": \"owners\",\n \"type\": \"address[]\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"threshold\",\n \"type\": \"uint256\"\n },\n {\n \"internalType\": \"bytes32\",\n \"name\": \"salt\",\n \"type\": \"bytes32\"\n },\n {\n \"internalType\": \"uint32\",\n \"name\": \"minExecutionDelay\",\n \"type\": \"uint32\"\n },\n {\n \"internalType\": \"address[]\",\n \"name\": \"initialModules\",\n \"type\": \"address[]\"\n },\n {\n \"internalType\": \"address[]\",\n \"name\": \"initialDelegatecallTargets\",\n \"type\": \"address[]\"\n }\n ],\n \"name\": \"createWallet\",\n \"outputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"wallet\",\n \"type\": \"address\"\n }\n ],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address[]\",\n \"name\": \"owners\",\n \"type\": \"address[]\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"threshold\",\n \"type\": \"uint256\"\n },\n {\n \"internalType\": \"bytes32\",\n \"name\": \"salt\",\n \"type\": \"bytes32\"\n },\n {\n \"internalType\": \"uint32\",\n \"name\": \"minExecutionDelay\",\n \"type\": \"uint32\"\n }\n ],\n \"name\": \"createWallet\",\n \"outputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"wallet\",\n \"type\": \"address\"\n }\n ],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"uint256\",\n \"name\": \"\",\n \"type\": \"uint256\"\n }\n ],\n \"name\": \"deployedWallets\",\n \"outputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"\",\n \"type\": \"address\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [],\n \"name\": \"getWalletCount\",\n \"outputs\": [\n {\n \"internalType\": \"uint256\",\n \"name\": \"\",\n \"type\": \"uint256\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [],\n \"name\": \"implementation\",\n \"outputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"\",\n \"type\": \"address\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"isWallet\",\n \"outputs\": [\n {\n \"internalType\": \"bool\",\n \"name\": \"\",\n \"type\": \"bool\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"deployer\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"bytes32\",\n \"name\": \"salt\",\n \"type\": \"bytes32\"\n },\n {\n \"internalType\": \"address[]\",\n \"name\": \"owners\",\n \"type\": \"address[]\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"threshold\",\n \"type\": \"uint256\"\n },\n {\n \"internalType\": \"uint32\",\n \"name\": \"minExecutionDelay\",\n \"type\": \"uint32\"\n },\n {\n \"internalType\": \"address[]\",\n \"name\": \"initialModules\",\n \"type\": \"address[]\"\n },\n {\n \"internalType\": \"address[]\",\n \"name\": \"initialDelegatecallTargets\",\n \"type\": \"address[]\"\n }\n ],\n \"name\": \"predictWalletAddress\",\n \"outputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"\",\n \"type\": \"address\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [],\n \"name\": \"proxyCodeHash\",\n \"outputs\": [\n {\n \"internalType\": \"bytes32\",\n \"name\": \"\",\n \"type\": \"bytes32\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"wallet\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"registerWallet\",\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n }\n ]\n}\n","{\n \"contractName\": \"QuaiVaultProxy\",\n \"abi\": [\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"implementation\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"bytes\",\n \"name\": \"data\",\n \"type\": \"bytes\"\n }\n ],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"constructor\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"target\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"AddressEmptyCode\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"implementation\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"ERC1967InvalidImplementation\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"ERC1967NonPayable\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"FailedCall\",\n \"type\": \"error\"\n },\n {\n \"anonymous\": false,\n \"inputs\": [\n {\n \"indexed\": true,\n \"internalType\": \"address\",\n \"name\": \"sender\",\n \"type\": \"address\"\n },\n {\n \"indexed\": false,\n \"internalType\": \"uint256\",\n \"name\": \"value\",\n \"type\": \"uint256\"\n }\n ],\n \"name\": \"Received\",\n \"type\": \"event\"\n },\n {\n \"anonymous\": false,\n \"inputs\": [\n {\n \"indexed\": true,\n \"internalType\": \"address\",\n \"name\": \"implementation\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"Upgraded\",\n \"type\": \"event\"\n },\n {\n \"stateMutability\": \"payable\",\n \"type\": \"fallback\"\n },\n {\n \"inputs\": [],\n \"name\": \"getImplementation\",\n \"outputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"\",\n \"type\": \"address\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"stateMutability\": \"payable\",\n \"type\": \"receive\"\n }\n ],\n \"bytecode\": \"0x608060405234801561001057600080fd5b506040516104d23803806104d283398101604081905261002f91610278565b818161003b8282610044565b50505050610362565b61004d826100a3565b6040516001600160a01b038316907fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b90600090a280511561009757610092828261011f565b505050565b61009f610196565b5050565b806001600160a01b03163b6000036100de57604051634c9c8ce360e01b81526001600160a01b03821660048201526024015b60405180910390fd5b7f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc80546001600160a01b0319166001600160a01b0392909216919091179055565b6060600080846001600160a01b03168460405161013c9190610346565b600060405180830381855af49150503d8060008114610177576040519150601f19603f3d011682016040523d82523d6000602084013e61017c565b606091505b50909250905061018d8583836101b7565b95945050505050565b34156101b55760405163b398979f60e01b815260040160405180910390fd5b565b6060826101cc576101c782610216565b61020f565b81511580156101e357506001600160a01b0384163b155b1561020c57604051639996b31560e01b81526001600160a01b03851660048201526024016100d5565b50805b9392505050565b80511561022557805160208201fd5b60405163d6bda27560e01b815260040160405180910390fd5b634e487b7160e01b600052604160045260246000fd5b60005b8381101561026f578181015183820152602001610257565b50506000910152565b6000806040838503121561028b57600080fd5b82516001600160a01b03811681146102a257600080fd5b60208401519092506001600160401b03808211156102bf57600080fd5b818501915085601f8301126102d357600080fd5b8151818111156102e5576102e561023e565b604051601f8201601f19908116603f0116810190838211818310171561030d5761030d61023e565b8160405282815288602084870101111561032657600080fd5b610337836020830160208801610254565b80955050505050509250929050565b60008251610358818460208701610254565b9190910192915050565b610161806103716000396000f3fe6080604052600436106100225760003560e01c8063aaf10f42146100685761005e565b3661005e5760405134815233907f88a5966d370b9919b20f3e2c13ff65706f196a4e32cc2c12bf57088f885258749060200160405180910390a2005b6100666100a6565b005b34801561007457600080fd5b5061007d6100b8565b60405173ffffffffffffffffffffffffffffffffffffffff909116815260200160405180910390f35b6100b66100b16100c7565b610107565b565b60006100c26100c7565b905090565b60006100c27f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc5473ffffffffffffffffffffffffffffffffffffffff1690565b3660008037600080366000845af43d6000803e808015610126573d6000f35b3d6000fdfea264697066735822122037ca1a4579066f991b4af91a998ae015900bb0abdc8be6637c4258d053f5f1d864736f6c63430008160033\"\n}\n","{\n \"contractName\": \"SocialRecoveryModule\",\n \"abi\": [\n {\n \"inputs\": [],\n \"name\": \"AlreadyApproved\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"CannotUpdateConfigWhileRecoveriesPending\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"DuplicateGuardian\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"DuplicateNewOwner\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"GuardiansRequired\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"InvalidGuardianAddress\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"InvalidNewOwnerAddress\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"InvalidThreshold\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"ModuleNotEnabled\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"MustBeCalledByWallet\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"NewOwnersRequired\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"NotAGuardian\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"NotAnOwner\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"NotApproved\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"NotEnoughApprovals\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"RecoveryAlreadyExecuted\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"RecoveryAlreadyInitiated\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"RecoveryExceedsMaxOwners\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"RecoveryExpired\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"RecoveryNotConfigured\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"RecoveryNotExpired\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"RecoveryNotInitiated\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"RecoveryPeriodNotElapsed\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"RecoveryPeriodTooShort\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"RecoveryStepFailed\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"ReentrancyGuardReentrantCall\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"TooManyGuardians\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"TooManyNewOwners\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"TooManyPendingRecoveries\",\n \"type\": \"error\"\n },\n {\n \"anonymous\": false,\n \"inputs\": [\n {\n \"indexed\": true,\n \"internalType\": \"address\",\n \"name\": \"wallet\",\n \"type\": \"address\"\n },\n {\n \"indexed\": true,\n \"internalType\": \"bytes32\",\n \"name\": \"recoveryHash\",\n \"type\": \"bytes32\"\n },\n {\n \"indexed\": true,\n \"internalType\": \"address\",\n \"name\": \"guardian\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"RecoveryApprovalRevoked\",\n \"type\": \"event\"\n },\n {\n \"anonymous\": false,\n \"inputs\": [\n {\n \"indexed\": true,\n \"internalType\": \"address\",\n \"name\": \"wallet\",\n \"type\": \"address\"\n },\n {\n \"indexed\": true,\n \"internalType\": \"bytes32\",\n \"name\": \"recoveryHash\",\n \"type\": \"bytes32\"\n },\n {\n \"indexed\": true,\n \"internalType\": \"address\",\n \"name\": \"guardian\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"RecoveryApproved\",\n \"type\": \"event\"\n },\n {\n \"anonymous\": false,\n \"inputs\": [\n {\n \"indexed\": true,\n \"internalType\": \"address\",\n \"name\": \"wallet\",\n \"type\": \"address\"\n },\n {\n \"indexed\": true,\n \"internalType\": \"bytes32\",\n \"name\": \"recoveryHash\",\n \"type\": \"bytes32\"\n }\n ],\n \"name\": \"RecoveryCancelled\",\n \"type\": \"event\"\n },\n {\n \"anonymous\": false,\n \"inputs\": [\n {\n \"indexed\": true,\n \"internalType\": \"address\",\n \"name\": \"wallet\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"RecoveryConfigCleared\",\n \"type\": \"event\"\n },\n {\n \"anonymous\": false,\n \"inputs\": [\n {\n \"indexed\": true,\n \"internalType\": \"address\",\n \"name\": \"wallet\",\n \"type\": \"address\"\n },\n {\n \"indexed\": true,\n \"internalType\": \"bytes32\",\n \"name\": \"recoveryHash\",\n \"type\": \"bytes32\"\n }\n ],\n \"name\": \"RecoveryExecuted\",\n \"type\": \"event\"\n },\n {\n \"anonymous\": false,\n \"inputs\": [\n {\n \"indexed\": true,\n \"internalType\": \"address\",\n \"name\": \"wallet\",\n \"type\": \"address\"\n },\n {\n \"indexed\": true,\n \"internalType\": \"bytes32\",\n \"name\": \"recoveryHash\",\n \"type\": \"bytes32\"\n }\n ],\n \"name\": \"RecoveryExpiredEvent\",\n \"type\": \"event\"\n },\n {\n \"anonymous\": false,\n \"inputs\": [\n {\n \"indexed\": true,\n \"internalType\": \"address\",\n \"name\": \"wallet\",\n \"type\": \"address\"\n },\n {\n \"indexed\": true,\n \"internalType\": \"bytes32\",\n \"name\": \"recoveryHash\",\n \"type\": \"bytes32\"\n },\n {\n \"indexed\": false,\n \"internalType\": \"address[]\",\n \"name\": \"newOwners\",\n \"type\": \"address[]\"\n },\n {\n \"indexed\": false,\n \"internalType\": \"uint256\",\n \"name\": \"newThreshold\",\n \"type\": \"uint256\"\n },\n {\n \"indexed\": true,\n \"internalType\": \"address\",\n \"name\": \"initiator\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"RecoveryInitiated\",\n \"type\": \"event\"\n },\n {\n \"anonymous\": false,\n \"inputs\": [\n {\n \"indexed\": true,\n \"internalType\": \"address\",\n \"name\": \"wallet\",\n \"type\": \"address\"\n },\n {\n \"indexed\": true,\n \"internalType\": \"bytes32\",\n \"name\": \"recoveryHash\",\n \"type\": \"bytes32\"\n }\n ],\n \"name\": \"RecoveryInvalidated\",\n \"type\": \"event\"\n },\n {\n \"anonymous\": false,\n \"inputs\": [\n {\n \"indexed\": true,\n \"internalType\": \"address\",\n \"name\": \"wallet\",\n \"type\": \"address\"\n },\n {\n \"indexed\": false,\n \"internalType\": \"address[]\",\n \"name\": \"guardians\",\n \"type\": \"address[]\"\n },\n {\n \"indexed\": false,\n \"internalType\": \"uint256\",\n \"name\": \"threshold\",\n \"type\": \"uint256\"\n },\n {\n \"indexed\": false,\n \"internalType\": \"uint256\",\n \"name\": \"recoveryPeriod\",\n \"type\": \"uint256\"\n }\n ],\n \"name\": \"RecoverySetup\",\n \"type\": \"event\"\n },\n {\n \"inputs\": [],\n \"name\": \"MAX_GUARDIANS\",\n \"outputs\": [\n {\n \"internalType\": \"uint256\",\n \"name\": \"\",\n \"type\": \"uint256\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"wallet\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"bytes32\",\n \"name\": \"recoveryHash\",\n \"type\": \"bytes32\"\n }\n ],\n \"name\": \"approveRecovery\",\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"wallet\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"bytes32\",\n \"name\": \"recoveryHash\",\n \"type\": \"bytes32\"\n }\n ],\n \"name\": \"cancelRecovery\",\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"wallet\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"bytes32\",\n \"name\": \"recoveryHash\",\n \"type\": \"bytes32\"\n }\n ],\n \"name\": \"executeRecovery\",\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"wallet\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"bytes32\",\n \"name\": \"recoveryHash\",\n \"type\": \"bytes32\"\n }\n ],\n \"name\": \"expireRecovery\",\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"wallet\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"getPendingRecoveryHashes\",\n \"outputs\": [\n {\n \"internalType\": \"bytes32[]\",\n \"name\": \"\",\n \"type\": \"bytes32[]\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"wallet\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"bytes32\",\n \"name\": \"recoveryHash\",\n \"type\": \"bytes32\"\n }\n ],\n \"name\": \"getRecovery\",\n \"outputs\": [\n {\n \"components\": [\n {\n \"internalType\": \"address[]\",\n \"name\": \"newOwners\",\n \"type\": \"address[]\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"newThreshold\",\n \"type\": \"uint256\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"approvalCount\",\n \"type\": \"uint256\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"executionTime\",\n \"type\": \"uint256\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"expiration\",\n \"type\": \"uint256\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"requiredThreshold\",\n \"type\": \"uint256\"\n },\n {\n \"internalType\": \"bool\",\n \"name\": \"executed\",\n \"type\": \"bool\"\n }\n ],\n \"internalType\": \"struct SocialRecoveryModule.Recovery\",\n \"name\": \"\",\n \"type\": \"tuple\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"wallet\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"getRecoveryConfig\",\n \"outputs\": [\n {\n \"components\": [\n {\n \"internalType\": \"address[]\",\n \"name\": \"guardians\",\n \"type\": \"address[]\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"threshold\",\n \"type\": \"uint256\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"recoveryPeriod\",\n \"type\": \"uint256\"\n }\n ],\n \"internalType\": \"struct SocialRecoveryModule.RecoveryConfig\",\n \"name\": \"\",\n \"type\": \"tuple\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"wallet\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"address[]\",\n \"name\": \"newOwners\",\n \"type\": \"address[]\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"newThreshold\",\n \"type\": \"uint256\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"nonce\",\n \"type\": \"uint256\"\n }\n ],\n \"name\": \"getRecoveryHash\",\n \"outputs\": [\n {\n \"internalType\": \"bytes32\",\n \"name\": \"\",\n \"type\": \"bytes32\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"wallet\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"hasPendingRecoveries\",\n \"outputs\": [\n {\n \"internalType\": \"bool\",\n \"name\": \"\",\n \"type\": \"bool\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"wallet\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"address[]\",\n \"name\": \"newOwners\",\n \"type\": \"address[]\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"newThreshold\",\n \"type\": \"uint256\"\n }\n ],\n \"name\": \"initiateRecovery\",\n \"outputs\": [\n {\n \"internalType\": \"bytes32\",\n \"name\": \"\",\n \"type\": \"bytes32\"\n }\n ],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"wallet\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"address\",\n \"name\": \"guardian\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"isGuardian\",\n \"outputs\": [\n {\n \"internalType\": \"bool\",\n \"name\": \"\",\n \"type\": \"bool\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"\",\n \"type\": \"uint256\"\n }\n ],\n \"name\": \"pendingRecoveryHashes\",\n \"outputs\": [\n {\n \"internalType\": \"bytes32\",\n \"name\": \"\",\n \"type\": \"bytes32\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"wallet\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"address[]\",\n \"name\": \"newOwners\",\n \"type\": \"address[]\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"newThreshold\",\n \"type\": \"uint256\"\n }\n ],\n \"name\": \"predictNextRecoveryHash\",\n \"outputs\": [\n {\n \"internalType\": \"bytes32\",\n \"name\": \"\",\n \"type\": \"bytes32\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"bytes32\",\n \"name\": \"\",\n \"type\": \"bytes32\"\n }\n ],\n \"name\": \"recoveries\",\n \"outputs\": [\n {\n \"internalType\": \"uint256\",\n \"name\": \"newThreshold\",\n \"type\": \"uint256\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"approvalCount\",\n \"type\": \"uint256\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"executionTime\",\n \"type\": \"uint256\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"expiration\",\n \"type\": \"uint256\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"requiredThreshold\",\n \"type\": \"uint256\"\n },\n {\n \"internalType\": \"bool\",\n \"name\": \"executed\",\n \"type\": \"bool\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"bytes32\",\n \"name\": \"\",\n \"type\": \"bytes32\"\n },\n {\n \"internalType\": \"address\",\n \"name\": \"\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"recoveryApprovals\",\n \"outputs\": [\n {\n \"internalType\": \"bool\",\n \"name\": \"\",\n \"type\": \"bool\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"recoveryConfigs\",\n \"outputs\": [\n {\n \"internalType\": \"uint256\",\n \"name\": \"threshold\",\n \"type\": \"uint256\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"recoveryPeriod\",\n \"type\": \"uint256\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"recoveryNonces\",\n \"outputs\": [\n {\n \"internalType\": \"uint256\",\n \"name\": \"\",\n \"type\": \"uint256\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"wallet\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"bytes32\",\n \"name\": \"recoveryHash\",\n \"type\": \"bytes32\"\n }\n ],\n \"name\": \"revokeRecoveryApproval\",\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"wallet\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"address[]\",\n \"name\": \"guardians\",\n \"type\": \"address[]\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"threshold\",\n \"type\": \"uint256\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"recoveryPeriod\",\n \"type\": \"uint256\"\n }\n ],\n \"name\": \"setupRecovery\",\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n }\n ]\n}\n","{\n \"contractName\": \"MultiSendCallOnly\",\n \"abi\": [\n {\n \"inputs\": [],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"constructor\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"bytes\",\n \"name\": \"transactions\",\n \"type\": \"bytes\"\n }\n ],\n \"name\": \"multiSend\",\n \"outputs\": [],\n \"stateMutability\": \"payable\",\n \"type\": \"function\"\n }\n ]\n}\n","/**\n * QuaiVault contract ABIs.\n *\n * Generated from quaivault-contracts hardhat artifacts by `npm run sync-abis`.\n * Do not edit the JSON files by hand — CI checks them for drift.\n */\nimport QuaiVaultArtifact from './QuaiVault.json' with { type: 'json' };\nimport QuaiVaultFactoryArtifact from './QuaiVaultFactory.json' with { type: 'json' };\nimport QuaiVaultProxyArtifact from './QuaiVaultProxy.json' with { type: 'json' };\nimport SocialRecoveryModuleArtifact from './SocialRecoveryModule.json' with { type: 'json' };\nimport MultiSendCallOnlyArtifact from './MultiSendCallOnly.json' with { type: 'json' };\n\nimport type { InterfaceAbi } from 'quais';\n\nexport const QuaiVaultAbi = QuaiVaultArtifact.abi as InterfaceAbi;\nexport const QuaiVaultFactoryAbi = QuaiVaultFactoryArtifact.abi as InterfaceAbi;\nexport const QuaiVaultProxyAbi = QuaiVaultProxyArtifact.abi as InterfaceAbi;\nexport const SocialRecoveryModuleAbi = SocialRecoveryModuleArtifact.abi as InterfaceAbi;\nexport const MultiSendCallOnlyAbi = MultiSendCallOnlyArtifact.abi as InterfaceAbi;\n\n/**\n * QuaiVaultProxy creation bytecode.\n * Required to reproduce `QuaiVaultFactory.predictWalletAddress` off-chain, which\n * is what makes CREATE2 salt mining possible without an RPC round-trip per attempt.\n */\nexport const QuaiVaultProxyBytecode = QuaiVaultProxyArtifact.bytecode as string;\n\n/** Minimal ERC20 fragments used for balance reads and transfer encoding. */\nexport const Erc20Abi = [\n 'function name() view returns (string)',\n 'function symbol() view returns (string)',\n 'function decimals() view returns (uint8)',\n 'function balanceOf(address owner) view returns (uint256)',\n 'function allowance(address owner, address spender) view returns (uint256)',\n 'function transfer(address to, uint256 amount) returns (bool)',\n 'function approve(address spender, uint256 amount) returns (bool)',\n 'function transferFrom(address from, address to, uint256 amount) returns (bool)',\n] as const;\n\n/** Minimal ERC721 fragments. */\nexport const Erc721Abi = [\n 'function name() view returns (string)',\n 'function symbol() view returns (string)',\n 'function ownerOf(uint256 tokenId) view returns (address)',\n 'function balanceOf(address owner) view returns (uint256)',\n 'function tokenURI(uint256 tokenId) view returns (string)',\n 'function safeTransferFrom(address from, address to, uint256 tokenId)',\n 'function safeTransferFrom(address from, address to, uint256 tokenId, bytes data)',\n 'function setApprovalForAll(address operator, bool approved)',\n] as const;\n\n/** Minimal ERC1155 fragments. */\nexport const Erc1155Abi = [\n 'function balanceOf(address account, uint256 id) view returns (uint256)',\n 'function balanceOfBatch(address[] accounts, uint256[] ids) view returns (uint256[])',\n 'function uri(uint256 id) view returns (string)',\n 'function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes data)',\n 'function safeBatchTransferFrom(address from, address to, uint256[] ids, uint256[] amounts, bytes data)',\n 'function setApprovalForAll(address operator, bool approved)',\n] as const;\n","import type { DecodedRevert } from '../types.js';\n\n/** Machine-readable error codes. Stable across releases. */\nexport type QuaiVaultErrorCode =\n | 'CONFIG'\n | 'NOT_CONNECTED'\n | 'NO_SIGNER'\n | 'NO_INDEXER'\n | 'INDEXER_QUERY'\n | 'INDEXER_STALE'\n | 'VALIDATION'\n | 'NOT_FOUND'\n | 'PRECONDITION'\n | 'REVERT'\n | 'SALT_MINING'\n | 'STALE_PROPOSAL'\n | 'UNSUPPORTED';\n\nexport class QuaiVaultError extends Error {\n readonly code: QuaiVaultErrorCode;\n /** What the caller can do about it, in plain language. */\n readonly remediation?: string;\n /** Unix seconds after which retrying could succeed. */\n readonly retryableAt?: number;\n override readonly cause?: unknown;\n\n constructor(\n code: QuaiVaultErrorCode,\n message: string,\n options: { remediation?: string; retryableAt?: number; cause?: unknown } = {},\n ) {\n super(message);\n this.name = new.target.name;\n this.code = code;\n this.remediation = options.remediation;\n this.retryableAt = options.retryableAt;\n this.cause = options.cause;\n }\n\n /** Structured form, for logs and machine consumers. */\n toJSON(): Record<string, unknown> {\n return {\n name: this.name,\n code: this.code,\n message: this.message,\n remediation: this.remediation,\n retryableAt: this.retryableAt,\n };\n }\n}\n\nexport class ConfigError extends QuaiVaultError {\n constructor(message: string, remediation?: string) {\n super('CONFIG', message, { remediation });\n }\n}\n\nexport class NoSignerError extends QuaiVaultError {\n constructor(operation: string) {\n super('NO_SIGNER', `${operation} requires a signer.`, {\n remediation:\n 'Pass connect({ privateKey }) or connect({ signer }), or set QUAIVAULT_PRIVATE_KEY.',\n });\n }\n}\n\nexport class NoIndexerError extends QuaiVaultError {\n constructor(operation: string) {\n super('NO_INDEXER', `${operation} requires the indexer, which is not configured.`, {\n remediation:\n 'Set QUAIVAULT_INDEXER_URL, QUAIVAULT_INDEXER_ANON_KEY and QUAIVAULT_INDEXER_SCHEMA.',\n });\n }\n}\n\nexport class IndexerQueryError extends QuaiVaultError {\n constructor(message: string, cause?: unknown) {\n super('INDEXER_QUERY', message, { cause });\n }\n}\n\nexport class ValidationError extends QuaiVaultError {\n constructor(message: string, remediation?: string) {\n super('VALIDATION', message, { remediation });\n }\n}\n\nexport class NotFoundError extends QuaiVaultError {\n constructor(message: string) {\n super('NOT_FOUND', message);\n }\n}\n\n/** A precondition the contract enforces would fail — checked before signing. */\nexport class PreconditionError extends QuaiVaultError {\n constructor(message: string, options: { remediation?: string; retryableAt?: number } = {}) {\n super('PRECONDITION', message, options);\n }\n}\n\n/** A contract call reverted. Carries the decoded custom error when resolvable. */\nexport class RevertError extends QuaiVaultError {\n readonly revert?: DecodedRevert;\n\n constructor(message: string, revert?: DecodedRevert, options: { remediation?: string; cause?: unknown } = {}) {\n super('REVERT', message, options);\n this.revert = revert;\n }\n\n override toJSON(): Record<string, unknown> {\n return { ...super.toJSON(), revert: this.revert };\n }\n}\n\nexport class SaltMiningError extends QuaiVaultError {\n constructor(message: string, remediation?: string) {\n super('SALT_MINING', message, { remediation });\n }\n}\n\n/**\n * A `disableModule` proposal whose baked-in `prevModule` no longer matches the\n * live linked list. The proposal can never execute and must be replaced.\n */\nexport class StaleProposalError extends QuaiVaultError {\n constructor(message: string) {\n super('STALE_PROPOSAL', message, {\n remediation: 'Cancel this proposal and create a new one against the current module list.',\n });\n }\n}\n","import { isAddress } from 'quais';\nimport type {\n ClientOptions,\n Consistency,\n ContractAddresses,\n IndexerConfig,\n NetworkConfig,\n} from '../types.js';\nimport { ConfigError } from '../errors/index.js';\nimport type { RetryOptions } from '../chain/retry.js';\nimport { isNetworkName, networks } from './networks.js';\n\n/**\n * Environment variables read when `useEnv` is not disabled.\n *\n * Explicit `ClientOptions` always win over the environment; the environment always\n * wins over the network preset. Nothing here is read at module load — resolution\n * happens inside `connect()`, so importing the SDK never touches `process.env`.\n */\nexport const ENV_VARS = {\n network: 'QUAIVAULT_NETWORK',\n rpcUrl: 'QUAIVAULT_RPC_URL',\n privateKey: 'QUAIVAULT_PRIVATE_KEY',\n indexerUrl: 'QUAIVAULT_INDEXER_URL',\n indexerAnonKey: 'QUAIVAULT_INDEXER_ANON_KEY',\n indexerSchema: 'QUAIVAULT_INDEXER_SCHEMA',\n indexerHealthUrl: 'QUAIVAULT_INDEXER_HEALTH_URL',\n factory: 'QUAIVAULT_FACTORY',\n implementation: 'QUAIVAULT_IMPLEMENTATION',\n socialRecovery: 'QUAIVAULT_SOCIAL_RECOVERY_MODULE',\n multiSendCallOnly: 'QUAIVAULT_MULTISEND_CALL_ONLY',\n consistency: 'QUAIVAULT_CONSISTENCY',\n maxIndexerLagBlocks: 'QUAIVAULT_MAX_INDEXER_LAG_BLOCKS',\n} as const;\n\nexport interface ResolvedConfig {\n network: NetworkConfig;\n contracts: ContractAddresses;\n indexer?: IndexerConfig;\n rpcUrl: string;\n /**\n * ⚠️ Secret. Consumed once to build a signer and never retained afterwards.\n *\n * Never log or serialise a `ResolvedConfig` that still carries this — use\n * {@link redactConfig}, which is what `QuaiVaultClient.config` exposes.\n */\n privateKey?: string;\n consistency: Consistency;\n maxIndexerLagBlocks: number;\n retry: RetryOptions;\n}\n\n/** A `ResolvedConfig` with the private key removed. Safe to log. */\nexport type PublicConfig = Omit<ResolvedConfig, 'privateKey'> & { privateKey?: never };\n\n/**\n * Strip the private key so the config can be logged or serialised.\n *\n * Also masks the indexer key — it is public by design, but a full dump in logs\n * invites confusion about which credentials are sensitive.\n */\nexport function redactConfig(config: ResolvedConfig): PublicConfig {\n const { privateKey: _omitted, ...rest } = config;\n return {\n ...rest,\n ...(rest.indexer\n ? { indexer: { ...rest.indexer, anonKey: maskKey(rest.indexer.anonKey) } }\n : {}),\n // `network` carries its own copy of the indexer block; mask that one as well or\n // a config dump still prints the key in full.\n network: rest.network.indexer\n ? {\n ...rest.network,\n indexer: { ...rest.network.indexer, anonKey: maskKey(rest.network.indexer.anonKey) },\n }\n : rest.network,\n } as PublicConfig;\n}\n\nfunction maskKey(key: string): string {\n return key.length <= 12 ? '***' : `${key.slice(0, 8)}…${key.slice(-4)}`;\n}\n\ntype Env = Record<string, string | undefined>;\n\nfunction readEnv(useEnv: boolean): Env {\n if (!useEnv) return {};\n // `process` is absent in browsers and some edge runtimes — degrade to no env\n // rather than throwing, so the SDK stays isomorphic.\n const proc = (globalThis as { process?: { env?: Env } }).process;\n return proc?.env ?? {};\n}\n\nfunction pick<T>(...values: Array<T | undefined | ''>): T | undefined {\n for (const v of values) {\n if (v !== undefined && v !== '') return v as T;\n }\n return undefined;\n}\n\nfunction requireAddress(value: string | undefined, label: string, envVar: string): string {\n if (!value) {\n throw new ConfigError(\n `Missing ${label}. Set ${envVar} or pass it via connect({ contracts: { … } }).`,\n );\n }\n if (!isAddress(value)) {\n throw new ConfigError(`Invalid ${label}: \"${value}\" is not a valid address.`);\n }\n return value;\n}\n\nfunction optionalAddress(value: string | undefined, label: string): string | undefined {\n if (!value) return undefined;\n if (!isAddress(value)) {\n throw new ConfigError(`Invalid ${label}: \"${value}\" is not a valid address.`);\n }\n return value;\n}\n\nfunction parseConsistency(value: string | undefined): Consistency | undefined {\n if (value === undefined) return undefined;\n if (value === 'auto' || value === 'indexed' || value === 'chain') return value;\n throw new ConfigError(\n `Invalid consistency \"${value}\". Expected one of: auto, indexed, chain.`,\n );\n}\n\nfunction parseLag(value: string | undefined): number | undefined {\n if (value === undefined) return undefined;\n const n = Number(value);\n if (!Number.isFinite(n) || n < 0) {\n throw new ConfigError(`Invalid ${ENV_VARS.maxIndexerLagBlocks}: \"${value}\". Expected a non-negative number.`);\n }\n return n;\n}\n\n/**\n * Merge, in order of decreasing precedence: explicit options → environment →\n * network preset defaults.\n */\nexport function resolveConfig(options: ClientOptions = {}): ResolvedConfig {\n const env = readEnv(options.useEnv !== false);\n\n // --- network preset\n const networkInput = options.network ?? env[ENV_VARS.network] ?? 'mainnet';\n let base: NetworkConfig;\n if (typeof networkInput === 'string') {\n if (!isNetworkName(networkInput)) {\n throw new ConfigError(\n `Unknown network \"${networkInput}\". Built-in networks: ${Object.keys(networks).join(', ')}. ` +\n `Pass a full NetworkConfig object for a custom deployment.`,\n );\n }\n base = networks[networkInput];\n } else {\n base = networkInput;\n }\n\n // --- rpc\n const rpcUrl = pick(options.rpcUrl, env[ENV_VARS.rpcUrl], base.rpcUrl);\n if (!rpcUrl) {\n throw new ConfigError(`Missing RPC URL. Set ${ENV_VARS.rpcUrl} or pass connect({ rpcUrl }).`);\n }\n\n // --- contracts\n const contracts: ContractAddresses = {\n factory: requireAddress(\n pick(options.contracts?.factory, env[ENV_VARS.factory], base.contracts.factory),\n 'factory address',\n ENV_VARS.factory,\n ),\n implementation: requireAddress(\n pick(\n options.contracts?.implementation,\n env[ENV_VARS.implementation],\n base.contracts.implementation,\n ),\n 'implementation address',\n ENV_VARS.implementation,\n ),\n socialRecovery: optionalAddress(\n pick(options.contracts?.socialRecovery, env[ENV_VARS.socialRecovery], base.contracts.socialRecovery),\n 'social recovery module address',\n ),\n multiSendCallOnly: optionalAddress(\n pick(\n options.contracts?.multiSendCallOnly,\n env[ENV_VARS.multiSendCallOnly],\n base.contracts.multiSendCallOnly,\n ),\n 'MultiSendCallOnly address',\n ),\n };\n\n // --- indexer (optional: the SDK is fully usable chain-only)\n const indexerUrl = pick(options.indexer?.url, env[ENV_VARS.indexerUrl], base.indexer?.url);\n const anonKey = pick(options.indexer?.anonKey, env[ENV_VARS.indexerAnonKey], base.indexer?.anonKey);\n const schema = pick(options.indexer?.schema, env[ENV_VARS.indexerSchema], base.indexer?.schema);\n\n let indexer: IndexerConfig | undefined;\n if (indexerUrl && anonKey && schema) {\n indexer = {\n url: indexerUrl,\n anonKey,\n schema,\n healthUrl: pick(\n options.indexer?.healthUrl,\n env[ENV_VARS.indexerHealthUrl],\n base.indexer?.healthUrl,\n ),\n };\n }\n\n const consistency =\n options.consistency ?? parseConsistency(env[ENV_VARS.consistency]) ?? 'auto';\n\n // Without an indexer, 'auto' degrades to chain-only reads; 'indexed' is a\n // configuration error the caller should hear about now rather than at first query.\n if (!indexer && consistency === 'indexed') {\n throw new ConfigError(\n `consistency: 'indexed' requires indexer configuration. ` +\n `Set ${ENV_VARS.indexerUrl}, ${ENV_VARS.indexerAnonKey} and ${ENV_VARS.indexerSchema}.`,\n );\n }\n\n return {\n network: { ...base, rpcUrl, contracts, ...(indexer ? { indexer } : {}) },\n contracts,\n indexer,\n rpcUrl,\n privateKey: pick(options.privateKey, env[ENV_VARS.privateKey]),\n consistency,\n maxIndexerLagBlocks:\n options.maxIndexerLagBlocks ?? parseLag(env[ENV_VARS.maxIndexerLagBlocks]) ?? 50,\n retry: {\n ...(options.retry?.maxAttempts != null ? { maxAttempts: options.retry.maxAttempts } : {}),\n ...(options.retry?.baseDelayMs != null ? { baseDelayMs: options.retry.baseDelayMs } : {}),\n ...(options.retry?.maxDelayMs != null ? { maxDelayMs: options.retry.maxDelayMs } : {}),\n ...(options.retry?.onRetry ? { onRetry: options.retry.onRetry } : {}),\n },\n };\n}\n","import type { NetworkConfig } from '../types.js';\n\n/**\n * Built-in network presets.\n *\n * Contract addresses track the deployments recorded in quaivault-www/contracts.md.\n *\n * The indexer credentials ship with the SDK so it works out of the box. The\n * publishable key is a public, read-only credential: the indexer's RLS grants the\n * `anon` role `SELECT` on every table and nothing else, with all writes reserved for\n * `service_role`. It exposes only chain data that is already public.\n *\n * Override any of it with `QUAIVAULT_INDEXER_URL` / `_ANON_KEY` / `_SCHEMA`, or with\n * `connect({ indexer: { … } })` — needed if the key is ever rotated ahead of an SDK\n * release, or to point at a self-hosted indexer.\n */\n\nconst INDEXER_URL = 'https://xbftgyuxaxagptudledv.supabase.co';\n\n/** Public, read-only Supabase publishable key. Safe to distribute — see above. */\nconst INDEXER_PUBLISHABLE_KEY = 'sb_publishable_EO-sTB-jqUzlsiugOEks-Q_qRtHDaHU';\n\nexport const mainnet: NetworkConfig = {\n name: 'mainnet',\n chainId: 9,\n rpcUrl: 'https://rpc.quai.network',\n explorerUrl: 'https://quaiscan.io',\n contracts: {\n implementation: '0x0038E6d84412A10CdcE41b0f62A05350023f1fb6',\n factory: '0x003613aC5FFd45bFF7B2F0210DA2fF660908c488',\n socialRecovery: '0x000dbc29Bdd311C29a4008164052fc2E67c0D937',\n multiSendCallOnly: '0x003f62e6a7f2EB6b94345a9A41671888eC4A3ebA',\n },\n indexer: {\n url: INDEXER_URL,\n anonKey: INDEXER_PUBLISHABLE_KEY,\n schema: 'mainnet',\n healthUrl: 'https://index.quaivault.org',\n },\n};\n\nexport const testnet: NetworkConfig = {\n name: 'testnet',\n chainId: 15000,\n // Orchard moved from rpc.orchard.quai.network (now NXDOMAIN) to this hostname.\n rpcUrl: 'https://orchard.rpc.quai.network',\n explorerUrl: 'https://orchard.quaiscan.io',\n contracts: {\n implementation: '0x004E539Cf477A5Cb456A56023f083cD91Bc4934e',\n factory: '0x002d1305D597c157bB975967FA2e5337674b0E5F',\n socialRecovery: '0x003a465e661D0E44C1e78b7B256D8C37f699E61e',\n multiSendCallOnly: '0x002ae8A47C2da497fe569AfCF0486410aA1093E0',\n },\n indexer: {\n url: INDEXER_URL,\n anonKey: INDEXER_PUBLISHABLE_KEY,\n schema: 'testnet',\n healthUrl: 'https://index.devnet.quaivault.org',\n },\n};\n\nexport const networks = { mainnet, testnet } as const;\n\nexport type NetworkName = keyof typeof networks;\n\nexport function isNetworkName(value: unknown): value is NetworkName {\n return typeof value === 'string' && value in networks;\n}\n","import { Interface, getAddress } from 'quais';\nimport { assertQuaiAddress, assertQuaiAddresses } from './address.js';\nimport { QuaiVaultFactoryAbi } from './abi/index.js';\nimport type { Connection } from './chain/connection.js';\nimport { FactoryContract } from './chain/vault-contract.js';\nimport { PreconditionError, RevertError, ValidationError } from './errors/index.js';\nimport { decodeRevertFromError } from './errors/decode.js';\nimport { MAX_EXECUTION_DELAY, MAX_OWNERS } from './encode/index.js';\nimport type { ReceiptLike } from './lifecycle/outcome.js';\nimport { mineSalt, type MineSaltOptions, type MiningStrategy } from './salt/mine.js';\nimport { predictVaultAddress } from './salt/predict.js';\nimport type {\n Address,\n Bytes32,\n ContractAddresses,\n CreateVaultParams,\n CreateVaultResult,\n Hex,\n MinedSalt,\n} from './types.js';\n\nconst factoryInterface = new Interface(QuaiVaultFactoryAbi);\n\nexport interface CreateProgress {\n step: 'validating' | 'mining' | 'deploying' | 'confirming' | 'done';\n message: string;\n attempts?: number;\n predictedAddress?: Address;\n chainTxHash?: Hex;\n}\n\nexport interface FactoryContext {\n connection: Connection;\n contracts: ContractAddresses;\n}\n\n/** Deploy and look up vaults through `QuaiVaultFactory`. */\nexport class Factory {\n constructor(private readonly ctx: FactoryContext) {}\n\n get address(): Address {\n return this.ctx.contracts.factory;\n }\n\n private contract(write = false): FactoryContract {\n return new FactoryContract(this.ctx.connection.factory(this.address, write), this.ctx.connection.retry);\n }\n\n /** The implementation every proxy from this factory delegates to. */\n async implementation(): Promise<Address> {\n return getAddress(await this.contract().implementation());\n }\n\n /** Whether the factory has this vault in its registry. */\n async isRegistered(vault: Address): Promise<boolean> {\n return this.contract().isWallet(getAddress(vault));\n }\n\n async vaultCount(): Promise<number> {\n return Number(await this.contract().getWalletCount());\n }\n\n async vaultAt(index: number): Promise<Address> {\n return getAddress(await this.contract().deployedWallets(index));\n }\n\n /**\n * Verify the configured implementation address matches what the factory reports.\n *\n * A mismatch means salt mining will predict addresses the factory will not deploy\n * to, so it is worth catching before a deployment rather than after.\n */\n async verify(): Promise<{ valid: boolean; errors: string[] }> {\n const errors: string[] = [];\n try {\n const onChain = await this.implementation();\n if (onChain.toLowerCase() !== this.ctx.contracts.implementation.toLowerCase()) {\n errors.push(\n `Configured implementation ${this.ctx.contracts.implementation} does not match the ` +\n `factory's ${onChain}. Address prediction and salt mining will be wrong.`,\n );\n }\n const code = await this.ctx.connection.provider.getCode(onChain);\n if (code === '0x') errors.push(`No contract code at implementation ${onChain}.`);\n } catch (err) {\n errors.push(\n `Could not reach the factory at ${this.address}: ` +\n (err instanceof Error ? err.message : String(err)),\n );\n }\n return { valid: errors.length === 0, errors };\n }\n\n /** Off-chain CREATE2 prediction. Identical to `factory.predictWalletAddress`. */\n predictAddress(deployer: Address, salt: Bytes32, params: CreateVaultParams): Address {\n validateCreateParams(params);\n return predictVaultAddress({\n factory: this.address,\n implementation: this.ctx.contracts.implementation,\n deployer: getAddress(deployer),\n salt,\n params,\n });\n }\n\n /**\n * Mine a CREATE2 salt placing the vault on the deployer's shard.\n *\n * Quai addresses are shard-scoped, so an arbitrary salt usually produces a vault\n * the deployer cannot reach. The mined salt is only valid for these exact create\n * params — changing owners, threshold, delay, modules or delegatecall targets\n * changes the predicted address.\n */\n async mineSalt(\n params: CreateVaultParams,\n options: Partial<Omit<MineSaltOptions, 'factory' | 'implementation' | 'params'>> = {},\n strategy?: MiningStrategy,\n ): Promise<MinedSalt> {\n validateCreateParams(params);\n const deployer = options.deployer ?? (await this.ctx.connection.address());\n return mineSalt(\n {\n factory: this.address,\n implementation: this.ctx.contracts.implementation,\n deployer: getAddress(deployer),\n params,\n ...options,\n },\n strategy,\n );\n }\n\n /**\n * Deploy a vault, mining a salt first when one is not supplied.\n *\n * Always uses the 6-argument `createWallet` overload so the deployed bytecode\n * matches what mining predicted, whatever combination of modules and delegatecall\n * targets is requested.\n */\n async create(\n params: CreateVaultParams,\n options: {\n onProgress?: (progress: CreateProgress) => void;\n miningStrategy?: MiningStrategy;\n maxAttempts?: number;\n timeoutMs?: number;\n } = {},\n ): Promise<CreateVaultResult> {\n const { onProgress } = options;\n validateCreateParams(params);\n\n onProgress?.({ step: 'validating', message: 'Checking factory configuration…' });\n const verification = await this.verify();\n if (!verification.valid) {\n throw new PreconditionError(verification.errors.join(' '), {\n remediation: 'Check the configured factory and implementation addresses for this network.',\n });\n }\n\n const deployer = getAddress(await this.ctx.connection.address());\n\n let salt = params.salt;\n let predictedAddress: Address | undefined;\n\n if (salt) {\n predictedAddress = this.predictAddress(deployer, salt, params);\n } else {\n onProgress?.({ step: 'mining', message: 'Mining a salt for your shard…' });\n const mined = await this.mineSalt(\n params,\n {\n deployer,\n ...(options.maxAttempts != null ? { maxAttempts: options.maxAttempts } : {}),\n ...(options.timeoutMs != null ? { timeoutMs: options.timeoutMs } : {}),\n onProgress: (attempts) =>\n onProgress?.({ step: 'mining', message: `Mining… ${attempts} attempts`, attempts }),\n },\n options.miningStrategy,\n );\n salt = mined.salt;\n predictedAddress = mined.predictedAddress;\n onProgress?.({\n step: 'mining',\n message: `Found ${mined.predictedAddress} after ${mined.attempts} attempts`,\n attempts: mined.attempts,\n predictedAddress: mined.predictedAddress,\n });\n }\n\n onProgress?.({ step: 'deploying', message: 'Submitting the deployment…', predictedAddress });\n\n const factory = this.contract(true);\n let receipt: ReceiptLike;\n let chainTxHash: Hex;\n try {\n const sent = await factory.createWallet(\n params.owners.map((o) => getAddress(o)),\n params.threshold,\n salt,\n params.minExecutionDelay ?? 0,\n (params.initialModules ?? []).map((m) => getAddress(m)),\n (params.initialDelegatecallTargets ?? []).map((t) => getAddress(t)),\n );\n chainTxHash = sent.hash as Hex;\n onProgress?.({ step: 'confirming', message: 'Waiting for confirmation…', chainTxHash });\n receipt = (await sent.wait()) as ReceiptLike;\n } catch (err) {\n const decoded = decodeRevertFromError(err);\n throw new RevertError(\n `Vault creation failed${decoded ? `: ${decoded.message}` : ''}`,\n decoded,\n { cause: err },\n );\n }\n\n if (!receipt || receipt.status === 0) {\n throw new RevertError('The deployment transaction reverted.');\n }\n\n const address = extractCreatedVault(receipt, this.address);\n if (!address) {\n throw new RevertError(\n 'The deployment was mined but no WalletCreated event was found.',\n );\n }\n\n onProgress?.({ step: 'done', message: `Vault deployed at ${address}`, chainTxHash });\n\n return {\n address,\n chainTxHash,\n salt,\n predictionMatched:\n predictedAddress !== undefined &&\n predictedAddress.toLowerCase() === address.toLowerCase(),\n };\n }\n\n /** Register an externally deployed proxy. Callable only by one of its owners. */\n async register(vault: Address): Promise<{ chainTxHash: Hex }> {\n const factory = this.contract(true);\n try {\n const sent = await factory.registerWallet(getAddress(vault));\n const receipt = (await sent.wait()) as ReceiptLike;\n if (!receipt || receipt.status === 0) {\n throw new RevertError('Registration reverted.');\n }\n return { chainTxHash: (receipt.hash ?? receipt.transactionHash ?? '') as Hex };\n } catch (err) {\n if (err instanceof RevertError) throw err;\n const decoded = decodeRevertFromError(err);\n throw new RevertError(\n `Registering the vault failed${decoded ? `: ${decoded.message}` : ''}`,\n decoded,\n { cause: err },\n );\n }\n }\n}\n\nfunction validateCreateParams(params: CreateVaultParams): void {\n const { owners, threshold } = params;\n\n if (!Array.isArray(owners) || owners.length === 0) {\n throw new ValidationError('At least one owner is required.');\n }\n if (owners.length > MAX_OWNERS) {\n throw new ValidationError(`A vault may have at most ${MAX_OWNERS} owners (got ${owners.length}).`);\n }\n const seen = new Set<string>();\n owners.forEach((owner, i) => {\n // Rejects Qi-ledger and zone-less addresses: an owner that cannot sign is dead\n // weight against the threshold, and enough of them brick the vault. The contract\n // only guards the zero address, the vault itself and the module sentinel.\n assertQuaiAddress(owner, `owner[${i}]`);\n const key = owner.toLowerCase();\n if (key === '0x0000000000000000000000000000000000000000' ||\n key === '0x0000000000000000000000000000000000000001') {\n throw new ValidationError(\n `Owner ${owner} is reserved — the zero address and the module sentinel 0x…01 are rejected.`,\n );\n }\n if (seen.has(key)) throw new ValidationError(`Duplicate owner: ${owner}.`);\n seen.add(key);\n });\n\n if (params.initialModules?.length) {\n assertQuaiAddresses(params.initialModules, 'initialModules');\n }\n if (params.initialDelegatecallTargets?.length) {\n assertQuaiAddresses(params.initialDelegatecallTargets, 'initialDelegatecallTargets');\n }\n if (!Number.isInteger(threshold) || threshold < 1 || threshold > owners.length) {\n throw new ValidationError(\n `Invalid threshold ${threshold}: must be an integer between 1 and ${owners.length}.`,\n );\n }\n const delay = params.minExecutionDelay ?? 0;\n if (!Number.isInteger(delay) || delay < 0 || delay > MAX_EXECUTION_DELAY) {\n throw new ValidationError(\n `Invalid minExecutionDelay ${delay}: must be between 0 and ${MAX_EXECUTION_DELAY} seconds (30 days).`,\n );\n }\n}\n\n/** Pull the vault address out of the factory's `WalletCreated` event. */\nfunction extractCreatedVault(receipt: ReceiptLike, factoryAddress: string): Address | null {\n const target = factoryAddress.toLowerCase();\n for (const log of receipt.logs ?? []) {\n if (log.address && log.address.toLowerCase() !== target) continue;\n try {\n const parsed = factoryInterface.parseLog({\n topics: Array.from(log.topics),\n data: log.data,\n });\n if (parsed?.name === 'WalletCreated') {\n return getAddress(String(parsed.args[0]));\n }\n } catch {\n continue;\n }\n }\n return null;\n}\n","import { getAddress, getZoneForAddress, isAddress, isQiAddress } from 'quais';\nimport { ValidationError } from './errors/index.js';\nimport type { Address } from './types.js';\n\n/**\n * Address validation for Quai's dual-ledger, sharded address space.\n *\n * Two independent properties are encoded in a Quai address:\n *\n * - **Zone** — the first byte (`0x00`–`0x02`, `0x10`–`0x12`, `0x20`–`0x22`). An address\n * outside those ranges belongs to no shard and cannot hold state.\n * - **Ledger** — the 9th bit, i.e. the high bit of the *second* byte. Set means Qi (the\n * UTXO ledger); clear means Quai (the EVM account ledger).\n *\n * They are genuinely orthogonal: `0x008111…` sits in zone `0x00` yet is a Qi address, so\n * a zone check alone is not enough.\n *\n * **Qi addresses cannot interact with smart contracts.** A Qi owner could never sign a\n * vault transaction, a Qi guardian could never approve a recovery, and native value sent\n * to one leaves the Quai ledger. The contracts do not check for this — `_addOwner` only\n * rejects the zero address, the vault itself and the module sentinel — so admitting one\n * permanently reduces the number of addresses able to reach the threshold, and enough of\n * them bricks the vault. The SDK therefore rejects Qi addresses wherever an address is\n * committed to a role or receives value.\n */\n\nexport type AddressLedger = 'quai' | 'qi';\n\nexport interface AddressCheck {\n valid: boolean;\n checksummed?: Address;\n /** Zone prefix, e.g. `0x00`. Absent when the address belongs to no shard. */\n zone?: string;\n ledger?: AddressLedger;\n reason?: string;\n}\n\n/** Inspect an address without throwing. */\nexport function inspectAddress(value: unknown): AddressCheck {\n if (typeof value !== 'string' || !isAddress(value)) {\n return { valid: false, reason: 'not a valid address' };\n }\n const checksummed = getAddress(value);\n const zone = getZoneForAddress(checksummed);\n const ledger: AddressLedger = isQiAddress(checksummed) ? 'qi' : 'quai';\n\n if (!zone) {\n return {\n valid: false,\n checksummed,\n ledger,\n reason: 'belongs to no Quai shard (its leading byte is not a valid zone prefix)',\n };\n }\n if (ledger === 'qi') {\n return {\n valid: false,\n checksummed,\n zone,\n ledger,\n reason: 'is a Qi-ledger address, which cannot interact with smart contracts on Quai',\n };\n }\n return { valid: true, checksummed, zone, ledger };\n}\n\n/** Whether an address is shard-valid and on the Quai ledger. */\nexport function isUsableQuaiAddress(value: unknown): boolean {\n return inspectAddress(value).valid;\n}\n\n/**\n * Assert an address can participate in Quai smart-contract calls, returning it\n * checksummed.\n *\n * Use for any address being committed to a role (owner, guardian, module, delegatecall\n * target) or receiving value. Do **not** use it for addresses being *removed* — a Qi\n * address that predates this check must still be removable — nor for read-only lookups,\n * where rejecting the query is less useful than answering it.\n */\nexport function assertQuaiAddress(value: unknown, label = 'address'): Address {\n const check = inspectAddress(value);\n if (check.valid) return check.checksummed as Address;\n\n const shown = typeof value === 'string' ? value : String(value);\n const remediation =\n check.ledger === 'qi'\n ? 'Qi is the UTXO ledger and has no contract execution. Use a Quai-ledger address ' +\n '(the 9th bit of the address — the high bit of its second byte — must be clear).'\n : 'Quai addresses must begin with a valid zone prefix: 0x00–0x02, 0x10–0x12, or 0x20–0x22.';\n\n throw new ValidationError(`Invalid ${label} \"${shown}\": it ${check.reason}.`, remediation);\n}\n\n/** Assert every address in a list, reporting the offending index. */\nexport function assertQuaiAddresses(values: readonly unknown[], label: string): Address[] {\n return values.map((value, i) => assertQuaiAddress(value, `${label}[${i}]`));\n}\n","/**\n * Retry policy for transient RPC and indexer failures.\n *\n * Scoped deliberately to **reads**. Retrying a write risks broadcasting the same\n * transaction twice — a resubmit that looks like a timeout to the client may already\n * be in the mempool — so every write path in this SDK calls through unretried.\n */\n\nexport interface RetryOptions {\n /** Total attempts including the first. Default 3. */\n maxAttempts?: number;\n /** First backoff delay. Doubles each attempt. Default 250ms. */\n baseDelayMs?: number;\n /** Ceiling on any single backoff. Default 4000ms. */\n maxDelayMs?: number;\n signal?: AbortSignal;\n onRetry?: (info: { attempt: number; delayMs: number; error: unknown }) => void;\n}\n\nconst DEFAULTS = {\n maxAttempts: 3,\n baseDelayMs: 250,\n maxDelayMs: 4_000,\n} as const;\n\n/**\n * Error codes `quais` raises that reflect a deterministic outcome, not a blip.\n * Retrying these can only produce the same answer more slowly.\n */\nconst PERMANENT_CODES = new Set([\n 'CALL_EXCEPTION', // the call reverted — deterministic\n 'INVALID_ARGUMENT',\n 'MISSING_ARGUMENT',\n 'UNEXPECTED_ARGUMENT',\n 'NOT_IMPLEMENTED',\n 'UNSUPPORTED_OPERATION',\n 'ACTION_REJECTED', // the user declined in their wallet\n 'NONCE_EXPIRED',\n 'INSUFFICIENT_FUNDS',\n 'REPLACEMENT_UNDERPRICED',\n 'TRANSACTION_REPLACED',\n 'VALUE_MISMATCH',\n]);\n\n/** Codes that usually clear on their own. */\nconst TRANSIENT_CODES = new Set(['NETWORK_ERROR', 'SERVER_ERROR', 'TIMEOUT', 'BAD_DATA']);\n\n/** Substrings seen in raw transport failures that carry no structured code. */\nconst TRANSIENT_PATTERNS = [\n 'fetch failed',\n 'econnreset',\n 'econnrefused',\n 'etimedout',\n 'epipe',\n 'socket hang up',\n 'network error',\n 'timeout',\n 'timed out',\n 'rate limit',\n 'too many requests',\n 'service unavailable',\n 'bad gateway',\n 'gateway timeout',\n 'temporarily unavailable',\n 'connection terminated',\n 'server error',\n];\n\n/** HTTP statuses worth another attempt. */\nconst TRANSIENT_STATUS = new Set([408, 425, 429, 500, 502, 503, 504]);\n\nfunction statusOf(error: unknown): number | undefined {\n if (typeof error !== 'object' || error === null) return undefined;\n const e = error as Record<string, unknown>;\n for (const key of ['status', 'statusCode']) {\n const value = e[key];\n if (typeof value === 'number') return value;\n }\n // quais nests the transport response under `info`\n const info = e.info as Record<string, unknown> | undefined;\n const response = info?.response as Record<string, unknown> | undefined;\n if (typeof response?.status === 'number') return response.status;\n return undefined;\n}\n\n/**\n * Whether an error is worth retrying.\n *\n * Errs toward *not* retrying: an unrecognised error is treated as permanent, so a\n * genuine bug surfaces immediately instead of being masked by three slow attempts.\n */\nexport function isTransient(error: unknown): boolean {\n if (error === null || error === undefined) return false;\n\n const code = (error as { code?: unknown }).code;\n if (typeof code === 'string') {\n if (PERMANENT_CODES.has(code)) return false;\n if (TRANSIENT_CODES.has(code)) return true;\n }\n\n const status = statusOf(error);\n if (status !== undefined) return TRANSIENT_STATUS.has(status);\n\n const message = error instanceof Error ? error.message : String(error);\n const haystack = message.toLowerCase();\n if (TRANSIENT_PATTERNS.some((p) => haystack.includes(p))) return true;\n\n // Unwrap one level — quais commonly wraps the transport error.\n const cause = (error as { cause?: unknown }).cause;\n if (cause && cause !== error) return isTransient(cause);\n\n return false;\n}\n\nconst sleep = (ms: number, signal?: AbortSignal): Promise<void> =>\n new Promise((resolve, reject) => {\n if (signal?.aborted) {\n reject(new Error('Aborted'));\n return;\n }\n const timer = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort);\n resolve();\n }, ms);\n const onAbort = () => {\n clearTimeout(timer);\n reject(new Error('Aborted'));\n };\n signal?.addEventListener('abort', onAbort, { once: true });\n });\n\n/**\n * Run `fn`, retrying transient failures with exponential backoff and full jitter.\n *\n * Jitter matters more than usual here: several vaults refreshing on the same tick\n * would otherwise retry in lockstep and hammer a rate-limited endpoint in waves.\n */\nexport async function withRetry<T>(fn: () => Promise<T>, options: RetryOptions = {}): Promise<T> {\n const maxAttempts = options.maxAttempts ?? DEFAULTS.maxAttempts;\n const baseDelayMs = options.baseDelayMs ?? DEFAULTS.baseDelayMs;\n const maxDelayMs = options.maxDelayMs ?? DEFAULTS.maxDelayMs;\n\n let lastError: unknown;\n\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n if (options.signal?.aborted) throw new Error('Aborted');\n try {\n return await fn();\n } catch (error) {\n lastError = error;\n if (attempt === maxAttempts || !isTransient(error)) throw error;\n\n const ceiling = Math.min(baseDelayMs * 2 ** (attempt - 1), maxDelayMs);\n const delayMs = Math.round(Math.random() * ceiling);\n options.onRetry?.({ attempt, delayMs, error });\n await sleep(delayMs, options.signal);\n }\n }\n\n throw lastError;\n}\n","import type { Contract } from 'quais';\nimport { withRetry, type RetryOptions } from './retry.js';\nimport type { Address, Bytes32, Hex } from '../types.js';\n\n/**\n * Raw `Transaction` struct as returned by `QuaiVault.transactions(bytes32)`.\n * Field names match the Solidity struct.\n */\nexport interface RawTransactionStruct {\n to: string;\n timestamp: bigint;\n expiration: bigint;\n proposer: string;\n executed: boolean;\n cancelled: boolean;\n approvedAt: bigint;\n executionDelay: bigint;\n value: bigint;\n data: string;\n}\n\n/**\n * Typed facade over the generated `Contract`.\n *\n * `quais` types its dynamic method accessor as possibly-undefined and cannot\n * disambiguate overloads by arity, so every call here goes through `getFunction`\n * with an explicit signature. Keeping that in one place means callers get real\n * types and overload selection is stated once, next to the ABI it depends on.\n */\nexport class VaultContract {\n constructor(\n readonly contract: Contract,\n private readonly retry: RetryOptions = {},\n ) {}\n\n private fn(signature: string) {\n return this.contract.getFunction(signature);\n }\n\n /**\n * Reads retry transient RPC failures (see {@link withRetry}); writes never do,\n * because a resubmit that looks like a timeout may already be in the mempool.\n */\n private read<T>(signature: string, ...args: unknown[]): Promise<T> {\n return withRetry(() => this.fn(signature)(...args) as Promise<T>, this.retry);\n }\n\n get interface() {\n return this.contract.interface;\n }\n\n // ---- reads ---------------------------------------------------------------\n\n getOwners(): Promise<string[]> {\n return this.read<string[]>('getOwners()');\n }\n\n isOwner(address: Address): Promise<boolean> {\n return this.read<boolean>('isOwner(address)', address);\n }\n\n threshold(): Promise<bigint> {\n return this.read<bigint>('threshold()');\n }\n\n nonce(): Promise<bigint> {\n return this.read<bigint>('nonce()');\n }\n\n minExecutionDelay(): Promise<bigint> {\n return this.read<bigint>('minExecutionDelay()');\n }\n\n moduleCount(): Promise<bigint> {\n return this.read<bigint>('moduleCount()');\n }\n\n getModules(): Promise<string[]> {\n return this.read<string[]>('getModules()');\n }\n\n isModuleEnabled(module: Address): Promise<boolean> {\n return this.read<boolean>('isModuleEnabled(address)', module);\n }\n\n delegatecallAllowed(target: Address): Promise<boolean> {\n return this.read<boolean>('delegatecallAllowed(address)', target);\n }\n\n transactions(txHash: Bytes32): Promise<RawTransactionStruct> {\n return this.read<RawTransactionStruct>('transactions(bytes32)', txHash);\n }\n\n /**\n * Whether an owner's approval currently counts toward the threshold.\n * Accounts for approval-epoch invalidation from owner removal.\n */\n hasApproved(txHash: Bytes32, owner: Address): Promise<boolean> {\n return this.read<boolean>('hasApproved(bytes32,address)', txHash, owner);\n }\n\n /** True when the transaction was closed by `expireTransaction`, not cancelled. */\n expiredTxs(txHash: Bytes32): Promise<boolean> {\n return this.read<boolean>('expiredTxs(bytes32)', txHash);\n }\n\n getTransactionHash(to: Address, value: bigint, data: Hex, nonce: number | bigint): Promise<Bytes32> {\n return this.read<Bytes32>(\n 'getTransactionHash(address,uint256,bytes,uint256)',\n to, value, data, nonce,\n );\n }\n\n isValidSignature(hash: Bytes32, signature: Hex): Promise<string> {\n return this.read<string>('isValidSignature(bytes32,bytes)', hash, signature);\n }\n\n // ---- writes --------------------------------------------------------------\n\n /**\n * Overload with expiration and delay. The 3-argument overload is used when\n * neither is supplied, so a caller that wants no expiry never has to pass 0.\n */\n proposeTransactionFull(\n to: Address,\n value: bigint,\n data: Hex,\n expiration: number,\n executionDelay: number,\n ): Promise<ContractTransactionResponse> {\n return this.fn('proposeTransaction(address,uint256,bytes,uint48,uint32)')(\n to,\n value,\n data,\n expiration,\n executionDelay,\n ) as Promise<ContractTransactionResponse>;\n }\n\n proposeTransactionSimple(\n to: Address,\n value: bigint,\n data: Hex,\n ): Promise<ContractTransactionResponse> {\n return this.fn('proposeTransaction(address,uint256,bytes)')(\n to,\n value,\n data,\n ) as Promise<ContractTransactionResponse>;\n }\n\n approveTransaction(txHash: Bytes32): Promise<ContractTransactionResponse> {\n return this.fn('approveTransaction(bytes32)')(txHash) as Promise<ContractTransactionResponse>;\n }\n\n approveAndExecute(txHash: Bytes32): Promise<ContractTransactionResponse> {\n return this.fn('approveAndExecute(bytes32)')(txHash) as Promise<ContractTransactionResponse>;\n }\n\n executeTransaction(txHash: Bytes32): Promise<ContractTransactionResponse> {\n return this.fn('executeTransaction(bytes32)')(txHash) as Promise<ContractTransactionResponse>;\n }\n\n revokeApproval(txHash: Bytes32): Promise<ContractTransactionResponse> {\n return this.fn('revokeApproval(bytes32)')(txHash) as Promise<ContractTransactionResponse>;\n }\n\n cancelTransaction(txHash: Bytes32): Promise<ContractTransactionResponse> {\n return this.fn('cancelTransaction(bytes32)')(txHash) as Promise<ContractTransactionResponse>;\n }\n\n expireTransaction(txHash: Bytes32): Promise<ContractTransactionResponse> {\n return this.fn('expireTransaction(bytes32)')(txHash) as Promise<ContractTransactionResponse>;\n }\n\n encode(signature: string, args: unknown[]): Hex {\n return this.contract.interface.encodeFunctionData(signature, args) as Hex;\n }\n}\n\n/** Minimal shape of a sent transaction — enough to await a receipt. */\nexport interface ContractTransactionResponse {\n hash: string;\n wait(confirmations?: number): Promise<unknown>;\n}\n\n/** Typed facade over `QuaiVaultFactory`. */\nexport class FactoryContract {\n constructor(\n readonly contract: Contract,\n private readonly retry: RetryOptions = {},\n ) {}\n\n private fn(signature: string) {\n return this.contract.getFunction(signature);\n }\n\n /**\n * Reads retry transient RPC failures (see {@link withRetry}); writes never do,\n * because a resubmit that looks like a timeout may already be in the mempool.\n */\n private read<T>(signature: string, ...args: unknown[]): Promise<T> {\n return withRetry(() => this.fn(signature)(...args) as Promise<T>, this.retry);\n }\n\n get interface() {\n return this.contract.interface;\n }\n\n implementation(): Promise<string> {\n return this.read<string>('implementation()');\n }\n\n isWallet(address: Address): Promise<boolean> {\n return this.read<boolean>('isWallet(address)', address);\n }\n\n getWalletCount(): Promise<bigint> {\n return this.read<bigint>('getWalletCount()');\n }\n\n deployedWallets(index: number | bigint): Promise<string> {\n return this.read<string>('deployedWallets(uint256)', index);\n }\n\n predictWalletAddress(\n deployer: Address,\n salt: Bytes32,\n owners: Address[],\n threshold: number,\n minExecutionDelay: number,\n initialModules: Address[],\n initialDelegatecallTargets: Address[],\n ): Promise<string> {\n return this.read<string>(\n 'predictWalletAddress(address,bytes32,address[],uint256,uint32,address[],address[])',\n deployer,\n salt,\n owners,\n threshold,\n minExecutionDelay,\n initialModules,\n initialDelegatecallTargets,\n );\n }\n\n /** Full 6-argument overload. The SDK always uses it so mining stays consistent. */\n createWallet(\n owners: Address[],\n threshold: number,\n salt: Bytes32,\n minExecutionDelay: number,\n initialModules: Address[],\n initialDelegatecallTargets: Address[],\n ): Promise<ContractTransactionResponse> {\n return this.fn('createWallet(address[],uint256,bytes32,uint32,address[],address[])')(\n owners,\n threshold,\n salt,\n minExecutionDelay,\n initialModules,\n initialDelegatecallTargets,\n ) as Promise<ContractTransactionResponse>;\n }\n\n registerWallet(wallet: Address): Promise<ContractTransactionResponse> {\n return this.fn('registerWallet(address)')(wallet) as Promise<ContractTransactionResponse>;\n }\n}\n","import { Interface, AbiCoder } from 'quais';\nimport type { ErrorFragment } from 'quais';\nimport {\n QuaiVaultAbi,\n QuaiVaultFactoryAbi,\n SocialRecoveryModuleAbi,\n QuaiVaultProxyAbi,\n} from '../abi/index.js';\nimport type { DecodedRevert, Hex } from '../types.js';\n\nconst SOLIDITY_ERROR_SELECTOR = '0x08c379a0'; // Error(string)\nconst SOLIDITY_PANIC_SELECTOR = '0x4e487b71'; // Panic(uint256)\n\ninterface ErrorEntry {\n fragment: ErrorFragment;\n iface: Interface;\n}\n\n/** selector -> fragment, built once across every ABI the SDK knows about. */\nlet registry: Map<string, ErrorEntry> | null = null;\n\nfunction buildRegistry(): Map<string, ErrorEntry> {\n const map = new Map<string, ErrorEntry>();\n for (const abi of [QuaiVaultAbi, QuaiVaultFactoryAbi, SocialRecoveryModuleAbi, QuaiVaultProxyAbi]) {\n const iface = new Interface(abi);\n iface.forEachError((fragment) => {\n // First ABI wins; collisions across our own contracts are same-signature by construction.\n if (!map.has(fragment.selector)) map.set(fragment.selector, { fragment, iface });\n });\n }\n return map;\n}\n\nfunction getRegistry(): Map<string, ErrorEntry> {\n if (!registry) registry = buildRegistry();\n return registry;\n}\n\n/**\n * Guidance keyed by custom error name. This is the difference between\n * \"execution reverted (unknown custom error)\" and something a caller can act on.\n */\nconst REMEDIATION: Record<string, string> = {\n // --- QuaiVault: authorisation\n NotAnOwner: 'The calling address is not an owner of this vault.',\n OnlySelf:\n 'This function can only be invoked as a vault self-call. Propose a transaction targeting the vault itself.',\n NotAnAuthorizedModule: 'The caller is not an enabled module on this vault.',\n NotProposer: 'Only the address that proposed a transaction may cancel it directly.',\n\n // --- QuaiVault: transaction lifecycle\n TransactionDoesNotExist: 'No transaction with that hash exists on this vault.',\n TransactionAlreadyExecuted: 'This transaction has already been executed and is terminal.',\n TransactionAlreadyCancelled: 'This transaction has already been cancelled or expired.',\n TransactionAlreadyExists:\n 'An identical transaction (same target, value, data and nonce) is already pending.',\n AlreadyApproved: 'This owner has already approved the transaction.',\n NotApproved: 'This owner has no active approval to revoke.',\n NotEnoughApprovals: 'The approval threshold has not been reached yet.',\n CannotCancelApprovedTransaction:\n 'The transaction reached quorum, which permanently locks proposer-cancel. Propose a cancelByConsensus self-call instead.',\n TransactionIsExpired: 'The transaction passed its expiration timestamp and can no longer execute.',\n TransactionNotExpired: 'The transaction has not passed its expiration timestamp yet.',\n TimelockNotElapsed: 'The execution delay has not elapsed. Retry after the timelock expires.',\n ExpirationTooSoon:\n 'The expiration must be later than now plus the execution delay, so at least one execution attempt is possible.',\n SelfCallCannotHaveValue: 'Self-calls must have value 0.',\n InvalidDestinationAddress: 'The destination address is the zero address.',\n CalldataTooShort: 'Self-call data must contain at least a 4-byte function selector.',\n UnrecognizedSelfCall:\n 'The self-call selector is not one the vault dispatches. Check the encoded function against the QuaiVault ABI.',\n\n // --- QuaiVault: owners and threshold\n OwnersRequired: 'At least one owner is required.',\n TooManyOwners: 'A vault may have at most 20 owners.',\n MaxOwnersReached: 'This vault already has the maximum of 20 owners.',\n InvalidThreshold: 'The threshold must be between 1 and the number of owners.',\n InvalidOwnerAddress:\n 'Owner addresses cannot be the zero address, the vault itself, or the sentinel 0x…01.',\n DuplicateOwner: 'The owner list contains a duplicate address.',\n AlreadyAnOwner: 'That address is already an owner.',\n CannotRemoveOwnerWouldFallBelowThreshold:\n 'Removing this owner would leave fewer owners than the threshold. Lower the threshold first.',\n\n // --- QuaiVault: modules and delegatecall\n ModuleAlreadyEnabled: 'That module is already enabled.',\n ModuleNotEnabled: 'That module is not enabled on this vault.',\n InvalidModule: 'Module addresses cannot be the zero address or the sentinel 0x…01.',\n InvalidPrevModule:\n 'The predecessor in the module linked list is stale — the module list changed since the proposal was created.',\n MaxModulesReached: 'This vault already has the maximum of 50 modules.',\n DelegateCallNotAllowed:\n 'DelegateCall targets must be explicitly whitelisted. Propose addDelegatecallTarget for this address first.',\n DelegatecallTargetAlreadyAllowed: 'That address is already on the DelegateCall whitelist.',\n DelegatecallTargetNotAllowed: 'That address is not on the DelegateCall whitelist.',\n ImplementationSlotTampered:\n 'A DelegateCall overwrote the ERC1967 implementation slot and was reverted. The target contract is hostile or buggy.',\n\n // --- QuaiVault: misc\n ExecutionDelayTooLong: 'The execution delay may not exceed 30 days (2,592,000 seconds).',\n MessageNotSigned: 'That message hash is not currently signed by the vault.',\n\n // --- Factory\n InvalidImplementationAddress: 'The implementation address is the zero address.',\n InvalidWalletAddress: 'The vault address is the zero address.',\n WalletAlreadyRegistered: 'That vault is already registered with the factory.',\n CallerIsNotAnOwner: 'Only an owner of the vault may register it with the factory.',\n InvalidWalletImplementation:\n 'The address is not a QuaiVaultProxy pointing at this factory’s implementation.',\n\n // --- SocialRecoveryModule\n GuardiansRequired: 'At least one guardian is required.',\n TooManyGuardians: 'Too many guardians for the recovery configuration.',\n RecoveryPeriodTooShort: 'The recovery period is below the module minimum.',\n CannotUpdateConfigWhileRecoveriesPending:\n 'Cancel or resolve all pending recoveries before changing the guardian configuration.',\n InvalidGuardianAddress: 'A guardian address is invalid.',\n DuplicateGuardian: 'The guardian list contains a duplicate address.',\n RecoveryNotConfigured: 'This vault has no social recovery configuration.',\n NotAGuardian: 'The calling address is not a guardian of this vault.',\n RecoveryAlreadyInitiated: 'An identical recovery is already pending.',\n RecoveryNotInitiated: 'No recovery with that hash exists.',\n RecoveryAlreadyExecuted: 'That recovery has already been executed.',\n RecoveryPeriodNotElapsed: 'The recovery time lock has not elapsed yet.',\n RecoveryExpired: 'The recovery passed its expiration deadline.',\n RecoveryNotExpired: 'The recovery has not expired yet.',\n TooManyPendingRecoveries: 'This vault has reached its cap on concurrent pending recoveries.',\n RecoveryExceedsMaxOwners:\n 'Applying this recovery would temporarily exceed the 20-owner maximum during the add-before-remove sequence.',\n MustBeCalledByWallet: 'This function must be called by the vault itself.',\n};\n\nfunction formatArgs(fragment: ErrorFragment, args: readonly unknown[]): string {\n if (args.length === 0) return '';\n const parts = fragment.inputs.map((input, i) => {\n const value = args[i];\n const rendered = typeof value === 'bigint' ? value.toString() : String(value);\n return input.name ? `${input.name}: ${rendered}` : rendered;\n });\n return `(${parts.join(', ')})`;\n}\n\n/**\n * Decode revert data against every QuaiVault ABI, plus the two Solidity builtins.\n * Returns `undefined` for empty data or an unrecognised selector.\n */\nexport function decodeRevert(data: unknown): DecodedRevert | undefined {\n if (typeof data !== 'string' || !data.startsWith('0x') || data.length < 10) return undefined;\n\n const selector = data.slice(0, 10).toLowerCase();\n const coder = AbiCoder.defaultAbiCoder();\n\n if (selector === SOLIDITY_ERROR_SELECTOR) {\n try {\n const [reason] = coder.decode(['string'], '0x' + data.slice(10));\n return {\n name: 'Error',\n args: [reason],\n selector,\n message: String(reason),\n };\n } catch {\n return undefined;\n }\n }\n\n if (selector === SOLIDITY_PANIC_SELECTOR) {\n try {\n const [code] = coder.decode(['uint256'], '0x' + data.slice(10));\n return {\n name: 'Panic',\n args: [code],\n selector,\n message: `Panic(0x${BigInt(code).toString(16)}) — arithmetic or assertion failure in the target contract`,\n };\n } catch {\n return undefined;\n }\n }\n\n const entry = getRegistry().get(selector);\n if (!entry) return undefined;\n\n let args: unknown[] = [];\n try {\n args = Array.from(entry.iface.decodeErrorResult(entry.fragment, data));\n } catch {\n // Selector matched but the payload did not — report the name without args.\n }\n\n const name = entry.fragment.name;\n const remediation = REMEDIATION[name];\n const rendered = `${name}${formatArgs(entry.fragment, args)}`;\n\n return {\n name,\n args,\n selector,\n message: remediation ? `${rendered} — ${remediation}` : rendered,\n };\n}\n\n/** Remediation text for a custom error name, if the SDK knows one. */\nexport function remediationFor(errorName: string): string | undefined {\n return REMEDIATION[errorName];\n}\n\n/**\n * Pull revert data out of the many shapes providers use, then decode it.\n * Handles quais/ethers `CALL_EXCEPTION` errors, raw RPC error bodies and nested causes.\n */\nexport function decodeRevertFromError(error: unknown): DecodedRevert | undefined {\n const seen = new Set<unknown>();\n\n const walk = (node: unknown, depth: number): DecodedRevert | undefined => {\n if (node == null || depth > 6 || seen.has(node)) return undefined;\n if (typeof node === 'string') return decodeRevert(node);\n if (typeof node !== 'object') return undefined;\n seen.add(node);\n\n const obj = node as Record<string, unknown>;\n for (const key of ['data', 'errorData', 'return', 'returnData']) {\n const decoded = decodeRevert(obj[key]);\n if (decoded) return decoded;\n }\n for (const key of ['error', 'cause', 'info', 'body', 'value']) {\n const decoded = walk(obj[key], depth + 1);\n if (decoded) return decoded;\n }\n return undefined;\n };\n\n return walk(error, 0);\n}\n\n/** All known custom error selectors. Exposed for tooling and tests. */\nexport function knownErrorSelectors(): Array<{ selector: Hex; signature: string }> {\n return Array.from(getRegistry().entries()).map(([selector, { fragment }]) => ({\n selector,\n signature: fragment.format('sighash'),\n }));\n}\n","import { AbiCoder, Interface, concat, getBytes, solidityPacked, zeroPadValue, toBeHex } from 'quais';\nimport {\n Erc1155Abi,\n Erc20Abi,\n Erc721Abi,\n MultiSendCallOnlyAbi,\n QuaiVaultAbi,\n SocialRecoveryModuleAbi,\n} from '../abi/index.js';\nimport type { Address, Hex } from '../types.js';\nimport { Operation } from '../types.js';\nimport { ValidationError } from '../errors/index.js';\n\nconst vault = new Interface(QuaiVaultAbi);\nconst recovery = new Interface(SocialRecoveryModuleAbi);\nconst multiSend = new Interface(MultiSendCallOnlyAbi);\nconst erc20 = new Interface(Erc20Abi as unknown as string[]);\nconst erc721 = new Interface(Erc721Abi as unknown as string[]);\nconst erc1155 = new Interface(Erc1155Abi as unknown as string[]);\n\nexport const interfaces = { vault, recovery, multiSend, erc20, erc721, erc1155 };\n\n/** Max value the contracts accept for `minExecutionDelay` / `requestedDelay` (30 days). */\nexport const MAX_EXECUTION_DELAY = 30 * 24 * 60 * 60;\nexport const MAX_OWNERS = 20;\nexport const MAX_MODULES = 50;\n/** Head of the Zodiac module linked list. */\nexport const SENTINEL_MODULES = '0x0000000000000000000000000000000000000001';\n\n// ---------------------------------------------------------------------------\n// Vault self-calls\n//\n// Every one of these must be delivered as a proposed transaction whose `to` is the\n// vault itself. The vault's `_executeSelfCall` dispatcher rejects any selector it\n// does not recognise, so encoding must come from this ABI.\n// ---------------------------------------------------------------------------\n\nexport const selfCall = {\n addOwner: (owner: Address): Hex => vault.encodeFunctionData('addOwner', [owner]),\n\n removeOwner: (owner: Address): Hex => vault.encodeFunctionData('removeOwner', [owner]),\n\n changeThreshold: (threshold: number): Hex => {\n if (!Number.isInteger(threshold) || threshold < 1) {\n throw new ValidationError(`Invalid threshold ${threshold}: must be an integer >= 1.`);\n }\n return vault.encodeFunctionData('changeThreshold', [threshold]);\n },\n\n enableModule: (module: Address): Hex => vault.encodeFunctionData('enableModule', [module]),\n\n /**\n * Disable a module.\n *\n * `prevModule` is the predecessor in the Zodiac linked list and must be resolved\n * against the live list — a proposal built against a stale list can never execute.\n * Prefer `Vault.propose.disableModule`, which resolves it for you.\n */\n disableModule: (prevModule: Address, module: Address): Hex =>\n vault.encodeFunctionData('disableModule', [prevModule, module]),\n\n setMinExecutionDelay: (seconds: number): Hex => {\n if (!Number.isInteger(seconds) || seconds < 0 || seconds > MAX_EXECUTION_DELAY) {\n throw new ValidationError(\n `Invalid execution delay ${seconds}: must be an integer between 0 and ${MAX_EXECUTION_DELAY} (30 days).`,\n );\n }\n return vault.encodeFunctionData('setMinExecutionDelay', [seconds]);\n },\n\n addDelegatecallTarget: (target: Address): Hex =>\n vault.encodeFunctionData('addDelegatecallTarget', [target]),\n\n removeDelegatecallTarget: (target: Address): Hex =>\n vault.encodeFunctionData('removeDelegatecallTarget', [target]),\n\n cancelByConsensus: (txHash: Hex): Hex => vault.encodeFunctionData('cancelByConsensus', [txHash]),\n\n /** Sign arbitrary bytes. For EIP-1271 hash pre-approval use {@link approveHashForEip1271}. */\n signMessage: (data: Hex): Hex => vault.encodeFunctionData('signMessage', [data]),\n\n unsignMessage: (data: Hex): Hex => vault.encodeFunctionData('unsignMessage', [data]),\n\n /**\n * Pre-approve a hash so `isValidSignature(hash, …)` returns the EIP-1271 magic value.\n *\n * `isValidSignature(h)` checks `signedMessages[getMessageHash(abi.encode(h))]`, while\n * `signMessage(data)` stores `getMessageHash(data)`. Because `abi.encode` of a static\n * `bytes32` is the identity on its 32 bytes, this produces calldata identical to\n * `signMessage(hash)` — the encoding step is a no-op for a well-formed hash.\n *\n * It is a separate helper because the *length* is what matters: signing an\n * arbitrary-length message `M` does NOT make `isValidSignature(keccak256(M))`\n * validate, since EIP-1271 hashes the 32-byte dataHash, not `M`. This entry point\n * enforces the 32-byte precondition and states the intent, so that mistake is\n * caught here rather than discovered when a counterparty's check silently fails.\n */\n approveHashForEip1271: (hash: Hex): Hex => {\n if (!/^0x[0-9a-fA-F]{64}$/.test(hash)) {\n throw new ValidationError('approveHashForEip1271 expects a 32-byte hash.');\n }\n const encoded = AbiCoder.defaultAbiCoder().encode(['bytes32'], [hash]);\n return vault.encodeFunctionData('signMessage', [encoded]);\n },\n\n /** Revoke a hash previously approved via {@link approveHashForEip1271}. */\n revokeHashForEip1271: (hash: Hex): Hex => {\n if (!/^0x[0-9a-fA-F]{64}$/.test(hash)) {\n throw new ValidationError('revokeHashForEip1271 expects a 32-byte hash.');\n }\n const encoded = AbiCoder.defaultAbiCoder().encode(['bytes32'], [hash]);\n return vault.encodeFunctionData('unsignMessage', [encoded]);\n },\n};\n\n// ---------------------------------------------------------------------------\n// Token calls\n// ---------------------------------------------------------------------------\n\nexport const token = {\n erc20Transfer: (to: Address, amount: bigint): Hex =>\n erc20.encodeFunctionData('transfer', [to, amount]),\n erc20Approve: (spender: Address, amount: bigint): Hex =>\n erc20.encodeFunctionData('approve', [spender, amount]),\n erc721Transfer: (from: Address, to: Address, tokenId: bigint): Hex =>\n erc721.encodeFunctionData('safeTransferFrom(address,address,uint256)', [from, to, tokenId]),\n erc1155Transfer: (from: Address, to: Address, id: bigint, amount: bigint, data: Hex = '0x'): Hex =>\n erc1155.encodeFunctionData('safeTransferFrom', [from, to, id, amount, data]),\n erc1155BatchTransfer: (\n from: Address,\n to: Address,\n ids: bigint[],\n amounts: bigint[],\n data: Hex = '0x',\n ): Hex => {\n if (ids.length !== amounts.length) {\n throw new ValidationError('erc1155BatchTransfer: ids and amounts must be the same length.');\n }\n return erc1155.encodeFunctionData('safeBatchTransferFrom', [from, to, ids, amounts, data]);\n },\n};\n\n// ---------------------------------------------------------------------------\n// Social recovery\n// ---------------------------------------------------------------------------\n\nexport const recoveryCall = {\n /** Encoded for a vault-proposed call to the module (not a self-call). */\n setupRecovery: (\n vaultAddress: Address,\n guardians: Address[],\n threshold: number,\n recoveryPeriodSeconds: number,\n ): Hex => {\n if (guardians.length === 0) throw new ValidationError('At least one guardian is required.');\n if (!Number.isInteger(threshold) || threshold < 1 || threshold > guardians.length) {\n throw new ValidationError(\n `Invalid guardian threshold ${threshold}: must be between 1 and ${guardians.length}.`,\n );\n }\n return recovery.encodeFunctionData('setupRecovery', [\n vaultAddress,\n guardians,\n threshold,\n recoveryPeriodSeconds,\n ]);\n },\n};\n\n// ---------------------------------------------------------------------------\n// MultiSend batching\n// ---------------------------------------------------------------------------\n\nexport interface BatchCall {\n to: Address;\n value?: bigint;\n data?: Hex;\n}\n\n/**\n * Pack calls into MultiSendCallOnly's transaction blob:\n * `operation(1) ‖ to(20) ‖ value(32) ‖ dataLength(32) ‖ data`, concatenated.\n *\n * `MultiSendCallOnly` rejects nested DelegateCall, so operation is always 0.\n */\nexport function encodeMultiSendPayload(calls: BatchCall[]): Hex {\n if (calls.length === 0) throw new ValidationError('encodeMultiSendPayload: no calls supplied.');\n\n const parts = calls.map((call) => {\n const data = call.data ?? '0x';\n const bytes = getBytes(data);\n return solidityPacked(\n ['uint8', 'address', 'uint256', 'uint256', 'bytes'],\n [Operation.Call, call.to, call.value ?? 0n, bytes.length, bytes],\n );\n });\n\n return concat(parts);\n}\n\n/** Full `multiSend(bytes)` calldata for a batch of calls. */\nexport function encodeMultiSend(calls: BatchCall[]): Hex {\n return multiSend.encodeFunctionData('multiSend', [encodeMultiSendPayload(calls)]);\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Smallest expiration the contract will accept for a given delay.\n *\n * `_proposeTransaction` rejects `expiration <= block.timestamp + effectiveDelay` with\n * `ExpirationTooSoon`, so a proposal must leave at least one execution opportunity\n * after the timelock elapses. The margin absorbs the gap between building the\n * proposal and it being mined.\n */\nexport function minimumExpiration(\n effectiveDelaySeconds: number,\n marginSeconds = 300,\n at: number = Math.floor(Date.now() / 1000),\n): number {\n return at + effectiveDelaySeconds + marginSeconds;\n}\n\nexport { zeroPadValue, toBeHex };\n","import type { Provider, Signer } from 'quais';\n\nexport type Address = string;\nexport type Hex = string;\nexport type Bytes32 = string;\n\nexport type { Provider, Signer };\n\n/** Zodiac IAvatar operation type. Mirrors `Enum.Operation` in the contracts. */\nexport enum Operation {\n Call = 0,\n DelegateCall = 1,\n}\n\n// ---------------------------------------------------------------------------\n// Configuration\n// ---------------------------------------------------------------------------\n\nexport interface ContractAddresses {\n implementation: Address;\n factory: Address;\n socialRecovery?: Address;\n multiSendCallOnly?: Address;\n}\n\nexport interface IndexerConfig {\n /** Supabase project URL. */\n url: string;\n /** Public anon key. Read-only by RLS policy — safe to distribute. */\n anonKey: string;\n /** Postgres schema for this network (`mainnet`, `testnet`, `dev`). */\n schema: string;\n /** Base URL of the indexer health server, used for lag/liveness checks. */\n healthUrl?: string;\n}\n\nexport interface NetworkConfig {\n name: string;\n chainId: number;\n rpcUrl: string;\n explorerUrl?: string;\n contracts: ContractAddresses;\n indexer?: IndexerConfig;\n}\n\n/**\n * How reads resolve between the indexer and the chain.\n *\n * - `indexed` — indexer only. Fastest; may be stale; fails if the indexer is down.\n * - `chain` — RPC only. Authoritative; slower; some history queries are unavailable.\n * - `auto` — indexer when it is fresh enough (see {@link ClientOptions.maxIndexerLagBlocks}),\n * otherwise the chain. This is the default.\n *\n * Write paths always re-validate preconditions against the chain regardless of this\n * setting — indexed approval counts can diverge from on-chain reality after an owner\n * is removed (approval epochs), so they must never gate a signature.\n */\nexport type Consistency = 'auto' | 'indexed' | 'chain';\n\nexport interface ClientOptions {\n network?: NetworkConfig | keyof typeof import('./config/networks.js').networks;\n provider?: Provider;\n signer?: Signer;\n /** Private key for a local signer. Prefer the `QUAIVAULT_PRIVATE_KEY` env var. */\n privateKey?: string;\n rpcUrl?: string;\n indexer?: Partial<IndexerConfig>;\n contracts?: Partial<ContractAddresses>;\n consistency?: Consistency;\n /** Beyond this many blocks behind, `auto` reads fall through to the chain. Default 50. */\n maxIndexerLagBlocks?: number;\n /** Read env vars for anything not passed explicitly. Default true. */\n useEnv?: boolean;\n /**\n * Retry policy for transient RPC and indexer failures. Applies to reads only —\n * writes are never retried, since a resubmit risks a double broadcast.\n */\n retry?: {\n maxAttempts?: number;\n baseDelayMs?: number;\n maxDelayMs?: number;\n onRetry?: (info: { attempt: number; delayMs: number; error: unknown }) => void;\n };\n}\n\n// ---------------------------------------------------------------------------\n// Vault domain model\n// ---------------------------------------------------------------------------\n\nexport interface VaultInfo {\n address: Address;\n owners: Address[];\n threshold: number;\n /** Vault-level minimum timelock for external calls, in seconds. 0 = simple quorum. */\n minExecutionDelay: number;\n nonce: number;\n balance: bigint;\n moduleCount: number;\n}\n\nexport type TransactionKind =\n | 'transfer'\n | 'erc20_transfer'\n | 'erc721_transfer'\n | 'erc1155_transfer'\n | 'wallet_admin'\n | 'module_config'\n | 'module_execution'\n | 'message_signing'\n | 'recovery_setup'\n | 'batched_call'\n | 'external_call'\n | 'unknown';\n\n/**\n * Lifecycle state of a vault transaction.\n *\n * `ready` and `timelocked` are SDK-derived refinements of the contract's \"pending\":\n * both mean not-yet-executed with quorum reached, differing only on whether the\n * execution delay has elapsed.\n */\nexport type TransactionStatus =\n | 'pending' // awaiting approvals\n | 'timelocked' // quorum reached, execution delay not yet elapsed\n | 'ready' // quorum reached, executable now\n | 'executed'\n | 'failed' // executed, but the external call reverted (terminal)\n | 'cancelled'\n | 'expired';\n\nexport interface ApprovalRecord {\n owner: Address;\n /** Whether this approval currently counts toward the threshold. */\n active: boolean;\n}\n\nexport interface DecodedCall {\n /** Function name, e.g. `addOwner`. */\n name: string;\n signature: string;\n args: Record<string, unknown>;\n /** Contract the selector was resolved against. */\n target: 'vault' | 'socialRecovery' | 'multiSend' | 'erc20' | 'erc721' | 'erc1155';\n}\n\nexport interface VaultTransaction {\n hash: Bytes32;\n vault: Address;\n to: Address;\n value: bigint;\n data: Hex;\n\n proposer: Address;\n /** Unix seconds when the proposal was recorded on chain. */\n proposedAt: number;\n\n kind: TransactionKind;\n decoded?: DecodedCall;\n /** One-line human-readable description. */\n summary: string;\n\n status: TransactionStatus;\n approvals: ApprovalRecord[];\n /** Count of approvals that currently count toward the threshold. */\n approvalCount: number;\n threshold: number;\n\n /** Unix seconds after which the tx can no longer execute. 0 = never expires. */\n expiration: number;\n /** Seconds of timelock locked in at proposal time. */\n executionDelay: number;\n /** Unix seconds when quorum was first reached. 0 = never reached. */\n approvedAt: number;\n /** `approvedAt + executionDelay`, or 0 if the clock has not started. */\n executableAfter: number;\n\n /** Raw revert data from a `TransactionFailed` event. */\n failedReturnData?: Hex;\n decodedRevert?: DecodedRevert;\n\n /** Where this record came from. */\n source: 'indexer' | 'chain';\n /** Indexer head at read time; absent for chain reads. */\n indexedAtBlock?: number;\n}\n\nexport interface DecodedRevert {\n /** Custom error name, or `Error` / `Panic` for the builtins. */\n name: string;\n args: unknown[];\n selector: Hex;\n /** Human-readable rendering. */\n message: string;\n}\n\n// ---------------------------------------------------------------------------\n// Writes\n// ---------------------------------------------------------------------------\n\nexport interface ProposeOptions {\n /** Unix seconds after which the tx can no longer execute. 0 / omitted = no expiry. */\n expiration?: number;\n /** Extra delay beyond the vault floor, in seconds. */\n executionDelay?: number;\n /** Build and return the call without signing. */\n dryRun?: boolean;\n}\n\nexport interface ProposeResult {\n /** The vault-transaction hash (bytes32), not the Quai transaction hash. */\n txHash: Bytes32;\n /** The on-chain Quai transaction hash that carried the proposal. */\n chainTxHash: Hex;\n to: Address;\n value: bigint;\n data: Hex;\n}\n\n/** Result of a dry-run write: everything needed to inspect or submit later. */\nexport interface DryRunResult {\n dryRun: true;\n to: Address;\n data: Hex;\n value: bigint;\n /** Estimated gas, or null if estimation reverted. */\n gasEstimate: bigint | null;\n /** Decoded revert if estimation failed. */\n wouldRevert?: DecodedRevert;\n description: string;\n}\n\n/**\n * Outcome of an execute attempt.\n *\n * A successful Quai transaction receipt does NOT imply the vault transaction ran.\n * See `docs/execution-outcomes.md`.\n */\nexport type ExecuteOutcome =\n | 'executed' // TransactionExecuted emitted — the target call succeeded\n | 'failed' // TransactionFailed emitted — target reverted; vault tx is terminal\n | 'timelock_started' // lazy clock: approvedAt was set, nothing executed; retry after the delay\n | 'approved_only'; // approveAndExecute recorded an approval but could not execute\n\nexport interface ExecuteResult {\n outcome: ExecuteOutcome;\n txHash: Bytes32;\n chainTxHash: Hex;\n blockNumber: number;\n gasUsed: bigint;\n /** Set when `outcome === 'failed'`. */\n returnData?: Hex;\n decodedRevert?: DecodedRevert;\n /** Set when `outcome === 'timelock_started'`. Unix seconds. */\n executableAfter?: number;\n /** Set when `outcome === 'approved_only'`. */\n approvalsNeeded?: number;\n /** Human-readable explanation of what happened and what to do next. */\n message: string;\n}\n\n// ---------------------------------------------------------------------------\n// Affordances\n// ---------------------------------------------------------------------------\n\nexport type VaultAction =\n | 'approve'\n | 'revokeApproval'\n | 'execute'\n | 'approveAndExecute'\n | 'cancel'\n | 'expire'\n | 'proposeCancelByConsensus';\n\nexport type AffordanceBlocker =\n | 'not_owner'\n | 'already_approved'\n | 'not_approved'\n | 'threshold'\n | 'timelock'\n | 'expired'\n | 'terminal_state'\n | 'quorum_locked'\n | 'not_proposer'\n | 'no_expiration';\n\nexport interface Affordance {\n action: VaultAction;\n allowed: boolean;\n /** Plain-language explanation, suitable for surfacing directly to a user. */\n reason: string;\n /** Unix seconds when a time gate lifts, if the only blocker is time. */\n availableAt?: number;\n blockedBy?: AffordanceBlocker;\n}\n\n// ---------------------------------------------------------------------------\n// Deployment\n// ---------------------------------------------------------------------------\n\nexport interface CreateVaultParams {\n owners: Address[];\n threshold: number;\n /** Vault-level minimum timelock in seconds. Max 30 days. Default 0. */\n minExecutionDelay?: number;\n /** Modules enabled at deploy time. */\n initialModules?: Address[];\n /** DelegateCall whitelist entries. Empty (default) means DelegateCall is disabled. */\n initialDelegatecallTargets?: Address[];\n /** Pre-mined salt. Omit to mine one automatically. */\n salt?: Bytes32;\n}\n\nexport interface MinedSalt {\n salt: Bytes32;\n predictedAddress: Address;\n attempts: number;\n durationMs: number;\n}\n\nexport interface CreateVaultResult {\n address: Address;\n chainTxHash: Hex;\n salt: Bytes32;\n /** Whether the deployed address matched the mined prediction. */\n predictionMatched: boolean;\n}\n\n// ---------------------------------------------------------------------------\n// Social recovery\n// ---------------------------------------------------------------------------\n\nexport interface RecoveryConfig {\n guardians: Address[];\n /** Guardian approvals required to execute a recovery. */\n threshold: number;\n /** Delay in seconds between initiation and executability. */\n recoveryPeriod: number;\n /** False when the vault has no recovery configured. */\n configured: boolean;\n}\n\n/**\n * Lifecycle state of a recovery request.\n *\n * `cancelled` is only ever reported from the indexer: `cancelRecovery` deletes the\n * on-chain struct, so a chain read cannot distinguish a cancelled recovery from one\n * that never existed.\n */\nexport type RecoveryStatus =\n | 'pending' // awaiting guardian approvals\n | 'timelocked' // approved, waiting out the recovery period\n | 'ready' // approved and executable now\n | 'executed'\n | 'cancelled'\n | 'expired';\n\nexport interface RecoveryRequest {\n hash: Bytes32;\n vault: Address;\n newOwners: Address[];\n newThreshold: number;\n approvalCount: number;\n /** Threshold captured at initiation — config changes mid-recovery do not move it. */\n requiredThreshold: number;\n /** Unix seconds after which execution is permitted. */\n executionTime: number;\n /** Unix seconds after which the recovery is dead and can be cleaned up. */\n expiration: number;\n status: RecoveryStatus;\n executed: boolean;\n /** Guardians who have approved. Only populated on indexer reads. */\n approvedBy?: Address[];\n initiator?: Address;\n source: 'indexer' | 'chain';\n}\n\nexport type RecoveryAction =\n | 'approve'\n | 'revokeApproval'\n | 'execute'\n | 'cancel'\n | 'expire';\n\nexport interface RecoveryAffordance {\n action: RecoveryAction;\n allowed: boolean;\n reason: string;\n availableAt?: number;\n blockedBy?:\n | 'not_guardian'\n | 'not_owner'\n | 'already_approved'\n | 'not_approved'\n | 'threshold'\n | 'timelock'\n | 'expired'\n | 'not_expired'\n | 'terminal_state'\n | 'module_disabled';\n}\n\n// ---------------------------------------------------------------------------\n// Indexer\n// ---------------------------------------------------------------------------\n\nexport interface Pagination {\n limit?: number;\n offset?: number;\n}\n\nexport interface Page<T> {\n data: T[];\n total: number;\n hasMore: boolean;\n}\n\nexport interface IndexerHealth {\n available: boolean;\n lastIndexedBlock: number;\n chainHead?: number;\n blocksBehind?: number;\n isSyncing: boolean;\n /** Reason the indexer was judged unavailable. */\n error?: string;\n}\n","import { getCreate2Address, hexlify, isQuaiAddress, keccak256, randomBytes, solidityPacked } from 'quais';\nimport type { Address, Bytes32, CreateVaultParams, MinedSalt } from '../types.js';\nimport { SaltMiningError } from '../errors/index.js';\nimport { computeBytecodeHash, encodeInitData, shardPrefixOf } from './predict.js';\n\nexport interface MineSaltOptions {\n factory: Address;\n implementation: Address;\n /** Address that will call `createWallet`. The mined address lands on its shard. */\n deployer: Address;\n params: CreateVaultParams;\n /** Override the target shard prefix. Defaults to the deployer's. */\n targetPrefix?: string;\n maxAttempts?: number;\n /** Abort after this long. Default 120_000 ms. */\n timeoutMs?: number;\n /** Called roughly every 1000 attempts. */\n onProgress?: (attempts: number) => void;\n signal?: AbortSignal;\n}\n\nexport interface MiningStrategy {\n readonly name: string;\n mine(options: Required<Pick<MineSaltOptions, 'factory' | 'deployer'>> & ResolvedMineJob): Promise<MinedSalt>;\n}\n\n/** Everything the inner loop needs, precomputed once. */\nexport interface ResolvedMineJob {\n bytecodeHash: Bytes32;\n targetPrefix: string;\n maxAttempts: number;\n timeoutMs: number;\n onProgress?: (attempts: number) => void;\n signal?: AbortSignal;\n}\n\nconst DEFAULT_MAX_ATTEMPTS = 500_000;\nconst DEFAULT_TIMEOUT_MS = 120_000;\nconst PROGRESS_INTERVAL = 1_000;\n/** Attempts per synchronous chunk before yielding to the event loop. */\nconst CHUNK = 250;\n\nfunction tryOne(\n factory: Address,\n deployer: Address,\n bytecodeHash: Bytes32,\n targetPrefix: string,\n): { salt: Bytes32; address: Address } | null {\n const salt = hexlify(randomBytes(32));\n const fullSalt = keccak256(solidityPacked(['address', 'bytes32'], [deployer, salt]));\n const address = getCreate2Address(factory, fullSalt, bytecodeHash);\n\n if (address.toLowerCase().startsWith(targetPrefix) && isQuaiAddress(address)) {\n return { salt, address };\n }\n return null;\n}\n\n/**\n * Chunked single-threaded miner. Yields to the event loop between chunks so it does\n * not block a browser UI thread or a Node server's other work.\n *\n * Works everywhere, which makes it the safe default.\n */\nexport const syncStrategy: MiningStrategy = {\n name: 'sync',\n async mine({ factory, deployer, bytecodeHash, targetPrefix, maxAttempts, timeoutMs, onProgress, signal }) {\n const startedAt = Date.now();\n\n for (let attempts = 0; attempts < maxAttempts; ) {\n if (signal?.aborted) throw new SaltMiningError('Salt mining was aborted.');\n if (Date.now() - startedAt > timeoutMs) {\n throw new SaltMiningError(\n `Salt mining timed out after ${timeoutMs} ms (${attempts} attempts).`,\n 'Raise timeoutMs, or use the worker_threads strategy on Node for more throughput.',\n );\n }\n\n const chunkEnd = Math.min(attempts + CHUNK, maxAttempts);\n for (; attempts < chunkEnd; attempts++) {\n const hit = tryOne(factory, deployer, bytecodeHash, targetPrefix);\n if (hit) {\n return {\n salt: hit.salt,\n predictedAddress: hit.address,\n attempts: attempts + 1,\n durationMs: Date.now() - startedAt,\n };\n }\n if ((attempts + 1) % PROGRESS_INTERVAL === 0) onProgress?.(attempts + 1);\n }\n\n await new Promise((resolve) => setTimeout(resolve, 0));\n }\n\n throw new SaltMiningError(\n `No valid salt found for prefix ${targetPrefix} after ${maxAttempts} attempts.`,\n 'Raise maxAttempts, or confirm the deployer address is on the shard you expect.',\n );\n },\n};\n\n/**\n * Node-only multi-core miner. Falls back to {@link syncStrategy} when\n * `node:worker_threads` is unavailable (browsers, restricted runtimes).\n */\nexport const workerThreadsStrategy: MiningStrategy = {\n name: 'worker_threads',\n async mine(job) {\n let Worker: typeof import('node:worker_threads').Worker;\n let availableParallelism: () => number;\n try {\n ({ Worker } = await import('node:worker_threads'));\n const os = await import('node:os');\n availableParallelism = os.availableParallelism ?? (() => os.cpus().length);\n } catch {\n return syncStrategy.mine(job);\n }\n\n const { factory, deployer, bytecodeHash, targetPrefix, maxAttempts, timeoutMs, onProgress, signal } = job;\n const workerCount = Math.max(1, Math.min(8, availableParallelism() - 1));\n const perWorker = Math.ceil(maxAttempts / workerCount);\n const startedAt = Date.now();\n\n // Inlined worker source keeps the package free of a separate entry file, so it\n // works the same whether consumed from source, from dist, or through a bundler.\n const workerSource = `\n const { parentPort, workerData } = require('node:worker_threads');\n const { getCreate2Address, hexlify, isQuaiAddress, keccak256, randomBytes, solidityPacked } = require('quais');\n const { factory, deployer, bytecodeHash, targetPrefix, maxAttempts } = workerData;\n for (let i = 0; i < maxAttempts; i++) {\n const salt = hexlify(randomBytes(32));\n const fullSalt = keccak256(solidityPacked(['address', 'bytes32'], [deployer, salt]));\n const address = getCreate2Address(factory, fullSalt, bytecodeHash);\n if (address.toLowerCase().startsWith(targetPrefix) && isQuaiAddress(address)) {\n parentPort.postMessage({ type: 'result', salt, address, attempts: i + 1 });\n return;\n }\n if ((i + 1) % ${PROGRESS_INTERVAL} === 0) parentPort.postMessage({ type: 'progress', attempts: i + 1 });\n }\n parentPort.postMessage({ type: 'exhausted', attempts: maxAttempts });\n `;\n\n return new Promise<MinedSalt>((resolve, reject) => {\n const workers: Array<InstanceType<typeof Worker>> = [];\n let settled = false;\n let exhausted = 0;\n let totalAttempts = 0;\n const progressByWorker = new Array<number>(workerCount).fill(0);\n\n const cleanup = () => {\n clearTimeout(timer);\n signal?.removeEventListener('abort', onAbort);\n for (const w of workers) void w.terminate();\n };\n const settle = (fn: () => void) => {\n if (settled) return;\n settled = true;\n cleanup();\n fn();\n };\n\n const timer = setTimeout(\n () =>\n settle(() =>\n reject(\n new SaltMiningError(\n `Salt mining timed out after ${timeoutMs} ms (~${totalAttempts} attempts across ${workerCount} workers).`,\n 'Raise timeoutMs or maxAttempts.',\n ),\n ),\n ),\n timeoutMs,\n );\n\n const onAbort = () => settle(() => reject(new SaltMiningError('Salt mining was aborted.')));\n signal?.addEventListener('abort', onAbort, { once: true });\n\n for (let i = 0; i < workerCount; i++) {\n const worker = new Worker(workerSource, {\n eval: true,\n workerData: { factory, deployer, bytecodeHash, targetPrefix, maxAttempts: perWorker },\n });\n workers.push(worker);\n\n worker.on('message', (msg: { type: string; salt?: string; address?: string; attempts?: number }) => {\n if (msg.type === 'progress') {\n progressByWorker[i] = msg.attempts ?? 0;\n totalAttempts = progressByWorker.reduce((a, b) => a + b, 0);\n onProgress?.(totalAttempts);\n } else if (msg.type === 'result') {\n settle(() =>\n resolve({\n salt: msg.salt as Bytes32,\n predictedAddress: msg.address as Address,\n attempts: totalAttempts + (msg.attempts ?? 0),\n durationMs: Date.now() - startedAt,\n }),\n );\n } else if (msg.type === 'exhausted') {\n if (++exhausted === workerCount) {\n settle(() =>\n reject(\n new SaltMiningError(\n `No valid salt found for prefix ${targetPrefix} after ${maxAttempts} attempts.`,\n 'Raise maxAttempts, or confirm the deployer address is on the shard you expect.',\n ),\n ),\n );\n }\n }\n });\n\n worker.on('error', (err) =>\n settle(() => reject(new SaltMiningError(`Salt mining worker failed: ${err.message}`))),\n );\n }\n });\n },\n};\n\n/** Prefer worker_threads on Node; the sync miner degrades gracefully everywhere else. */\nexport function defaultStrategy(): MiningStrategy {\n const hasNode =\n typeof (globalThis as { process?: { versions?: { node?: string } } }).process?.versions?.node ===\n 'string';\n return hasNode ? workerThreadsStrategy : syncStrategy;\n}\n\n/**\n * Mine a CREATE2 salt that deploys a vault onto the deployer's Quai shard.\n *\n * The predicted address is a pure function of (factory, implementation, deployer,\n * salt, create params) — so the caller can mine ahead of time, persist the salt,\n * and deploy later, as long as every one of those inputs is unchanged.\n */\nexport async function mineSalt(\n options: MineSaltOptions,\n strategy: MiningStrategy = defaultStrategy(),\n): Promise<MinedSalt> {\n const targetPrefix = (options.targetPrefix ?? shardPrefixOf(options.deployer)).toLowerCase();\n const initData = encodeInitData(options.params);\n const bytecodeHash = computeBytecodeHash(options.implementation, initData);\n\n return strategy.mine({\n factory: options.factory,\n deployer: options.deployer,\n bytecodeHash,\n targetPrefix,\n maxAttempts: options.maxAttempts ?? DEFAULT_MAX_ATTEMPTS,\n timeoutMs: options.timeoutMs ?? DEFAULT_TIMEOUT_MS,\n onProgress: options.onProgress,\n signal: options.signal,\n });\n}\n","import { AbiCoder, Interface, concat, getCreate2Address, keccak256, solidityPacked } from 'quais';\nimport { QuaiVaultAbi, QuaiVaultProxyBytecode } from '../abi/index.js';\nimport type { Address, Bytes32, CreateVaultParams } from '../types.js';\nimport { ValidationError } from '../errors/index.js';\n\nconst vaultInterface = new Interface(QuaiVaultAbi);\n\n/**\n * Encode the `initialize` call the factory delegatecalls from the proxy constructor.\n *\n * This MUST match `QuaiVaultFactory._createWallet` exactly — including the module and\n * delegatecall-target arrays. Encoding `[]` for those while deploying with a non-empty\n * array yields a different bytecode hash, so the mined address will not be the address\n * the factory actually deploys to.\n */\nexport function encodeInitData(params: {\n owners: Address[];\n threshold: number;\n minExecutionDelay?: number;\n initialModules?: Address[];\n initialDelegatecallTargets?: Address[];\n}): string {\n return vaultInterface.encodeFunctionData('initialize', [\n params.owners,\n params.threshold,\n params.minExecutionDelay ?? 0,\n params.initialModules ?? [],\n params.initialDelegatecallTargets ?? [],\n ]);\n}\n\n/**\n * keccak256 of the full proxy creation bytecode (creation code + ABI-encoded\n * constructor args), which is the third input to CREATE2.\n *\n * Constant for a given set of create params, so it is computed once and reused\n * across every mining attempt.\n */\nexport function computeBytecodeHash(implementation: Address, initData: string): Bytes32 {\n const encodedArgs = AbiCoder.defaultAbiCoder().encode(\n ['address', 'bytes'],\n [implementation, initData],\n );\n return keccak256(concat([QuaiVaultProxyBytecode, encodedArgs]));\n}\n\n/**\n * The factory namespaces user salts by caller:\n * `fullSalt = keccak256(abi.encodePacked(msg.sender, userSalt))`.\n * Two deployers using the same user salt therefore get different addresses.\n */\nexport function computeFullSalt(deployer: Address, userSalt: Bytes32): Bytes32 {\n return keccak256(solidityPacked(['address', 'bytes32'], [deployer, userSalt]));\n}\n\n/**\n * Reproduce `QuaiVaultFactory.predictWalletAddress` off-chain — no RPC needed.\n */\nexport function predictVaultAddress(args: {\n factory: Address;\n implementation: Address;\n deployer: Address;\n salt: Bytes32;\n params: CreateVaultParams;\n}): Address {\n const initData = encodeInitData(args.params);\n const bytecodeHash = computeBytecodeHash(args.implementation, initData);\n const fullSalt = computeFullSalt(args.deployer, args.salt);\n return getCreate2Address(args.factory, fullSalt, bytecodeHash);\n}\n\n/**\n * The shard prefix of a Quai address: `0x` plus the leading byte.\n *\n * Quai addresses are shard-scoped. A vault deployed outside the deployer's shard is\n * unreachable from it, which is why deployment requires mining a salt rather than\n * picking one at random.\n */\nexport function shardPrefixOf(address: Address): string {\n if (typeof address !== 'string' || !address.startsWith('0x') || address.length < 4) {\n throw new ValidationError(`Cannot derive a shard prefix from \"${address}\".`);\n }\n return address.slice(0, 4).toLowerCase();\n}\n","import { createClient, type SupabaseClient } from '@supabase/supabase-js';\nimport type { z } from 'zod';\nimport type { IndexerConfig, IndexerHealth } from '../types.js';\nimport { IndexerQueryError } from '../errors/index.js';\nimport { IndexerStateSchema, toNumber } from './schemas.js';\n\nconst SDK_VERSION = '0.1.0';\n\n/**\n * The indexer uses one Postgres schema per network, chosen at runtime, so the\n * client cannot be pinned to supabase-js's default `\"public\"` schema generic.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnySupabaseClient = SupabaseClient<any, any, any, any, any>;\n\n/**\n * Thin wrapper over the indexer's Supabase project.\n *\n * The anon key is a public read-only credential: the indexer's RLS grants `anon`\n * SELECT on every table and nothing else, with all writes reserved for\n * `service_role`. It carries no authority beyond reading already-public chain data.\n */\nexport class IndexerClient {\n readonly config: IndexerConfig;\n private readonly client: AnySupabaseClient;\n private healthCache: { value: IndexerHealth; at: number } | null = null;\n private inflightHealth: Promise<IndexerHealth> | null = null;\n\n /** Health results are reused for this long to keep read paths cheap. */\n readonly healthCacheMs: number;\n\n constructor(config: IndexerConfig, options: { healthCacheMs?: number } = {}) {\n this.config = config;\n this.healthCacheMs = options.healthCacheMs ?? 5_000;\n this.client = createClient(config.url, config.anonKey, {\n db: { schema: config.schema },\n auth: { persistSession: false, autoRefreshToken: false },\n global: { headers: { 'x-client-info': `quaivault-sdk/${SDK_VERSION}` } },\n });\n }\n\n /** Raw Supabase client, for queries the SDK does not wrap. */\n get raw(): AnySupabaseClient {\n return this.client;\n }\n\n from(table: string) {\n return this.client.from(table);\n }\n\n /**\n * Run a query, parse each row, and surface failures as `IndexerQueryError`.\n *\n * No retry wrapper here on purpose. `postgrest-js` already retries GET/HEAD/OPTIONS\n * internally (3 attempts, retryable statuses and fetch errors, honouring\n * `Retry-After`), and it reports failures as a resolved `{ error }` value rather\n * than a rejection — so an outer `withRetry` would be dead code that silently\n * multiplied attempts if it were ever made to work. Chain reads, which do reject,\n * are retried in `src/chain/retry.ts`.\n */\n async select<S extends z.ZodTypeAny>(\n table: string,\n schema: S,\n build: (q: ReturnType<AnySupabaseClient[\"from\"]>) => PromiseLike<{\n data: unknown[] | null;\n error: { message: string; code?: string } | null;\n }>,\n ): Promise<Array<z.infer<S>>> {\n const { data, error } = await build(this.client.from(table));\n if (error) {\n throw new IndexerQueryError(`Indexer query on \"${table}\" failed: ${error.message}`, error);\n }\n return (data ?? []).map((row) => schema.parse(row) as z.infer<S>);\n }\n\n /** Single-row variant. Returns null for PostgREST's \"no rows\" code. */\n async selectOne<S extends z.ZodTypeAny>(\n table: string,\n schema: S,\n build: (q: ReturnType<AnySupabaseClient[\"from\"]>) => PromiseLike<{\n data: unknown | null;\n error: { message: string; code?: string } | null;\n }>,\n ): Promise<z.infer<S> | null> {\n const { data, error } = await build(this.client.from(table));\n if (error) {\n if (error.code === 'PGRST116') return null; // no rows matched\n throw new IndexerQueryError(`Indexer query on \"${table}\" failed: ${error.message}`, error);\n }\n return data === null ? null : (schema.parse(data) as z.infer<S>);\n }\n\n /** The indexer's sync head, straight from the `indexer_state` table. */\n async state(): Promise<{ lastIndexedBlock: number; isSyncing: boolean } | null> {\n const row = await this.selectOne('indexer_state', IndexerStateSchema, (q) =>\n q.select('*').eq('id', 'main').single(),\n );\n if (!row) return null;\n return {\n lastIndexedBlock: toNumber(row.last_indexed_block),\n isSyncing: row.is_syncing ?? false,\n };\n }\n\n /**\n * Liveness and lag. Prefers the HTTP health endpoint (which knows the chain head)\n * and falls back to the `indexer_state` table when it is unreachable.\n */\n async health(force = false): Promise<IndexerHealth> {\n const now = Date.now();\n if (!force && this.healthCache && now - this.healthCache.at < this.healthCacheMs) {\n return this.healthCache.value;\n }\n if (this.inflightHealth) return this.inflightHealth;\n\n this.inflightHealth = this.probeHealth()\n .then((value) => {\n this.healthCache = { value, at: Date.now() };\n return value;\n })\n .finally(() => {\n this.inflightHealth = null;\n });\n\n return this.inflightHealth;\n }\n\n /**\n * Block until the indexer has processed `blockNumber`.\n *\n * Closes the write-then-read race: a transaction confirmed at block N is not\n * queryable until the indexer reaches N, so `propose()` immediately followed by\n * `pendingTransactions()` will silently miss it. Await this in between.\n *\n * Resolves immediately when the head is already at or past the target.\n */\n async waitForBlock(\n blockNumber: number,\n options: { timeoutMs?: number; pollIntervalMs?: number; signal?: AbortSignal } = {},\n ): Promise<{ reached: boolean; lastIndexedBlock: number }> {\n const timeoutMs = options.timeoutMs ?? 60_000;\n const pollIntervalMs = options.pollIntervalMs ?? 1_500;\n const deadline = Date.now() + timeoutMs;\n\n for (;;) {\n if (options.signal?.aborted) throw new Error('Aborted');\n\n // Bypass the health cache: a stale hit would add a needless poll interval.\n const state = await this.state();\n const head = state?.lastIndexedBlock ?? 0;\n if (head >= blockNumber) return { reached: true, lastIndexedBlock: head };\n\n if (Date.now() + pollIntervalMs > deadline) {\n return { reached: false, lastIndexedBlock: head };\n }\n await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));\n }\n }\n\n private async probeHealth(): Promise<IndexerHealth> {\n if (this.config.healthUrl) {\n try {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), 5_000);\n const res = await fetch(new URL('/health', this.config.healthUrl), {\n signal: controller.signal,\n }).finally(() => clearTimeout(timer));\n\n const body = (await res.json()) as {\n status?: string;\n details?: {\n currentBlock?: number;\n lastIndexedBlock?: number;\n blocksBehind?: number;\n isSyncing?: boolean;\n };\n };\n const d = body.details ?? {};\n return {\n available: res.ok && body.status === 'healthy',\n lastIndexedBlock: d.lastIndexedBlock ?? 0,\n chainHead: d.currentBlock,\n blocksBehind: d.blocksBehind,\n isSyncing: d.isSyncing ?? false,\n ...(res.ok ? {} : { error: `health endpoint returned ${res.status}` }),\n };\n } catch {\n // Fall through to the database probe — a dead health server does not imply\n // a dead indexer, and reads go to Supabase anyway.\n }\n }\n\n try {\n const state = await this.state();\n if (!state) {\n return { available: false, lastIndexedBlock: 0, isSyncing: false, error: 'no indexer_state row' };\n }\n return {\n available: true,\n lastIndexedBlock: state.lastIndexedBlock,\n isSyncing: state.isSyncing,\n };\n } catch (err) {\n return {\n available: false,\n lastIndexedBlock: 0,\n isSyncing: false,\n error: err instanceof Error ? err.message : String(err),\n };\n }\n }\n}\n","import { z } from 'zod';\n\n/**\n * Row schemas for the indexer's Postgres tables.\n *\n * Mirrors quaivault-indexer/supabase/migrations/schema.sql. Parsing is strict on\n * shape but tolerant of added columns, so an indexer that ships new fields does not\n * break an older SDK.\n */\n\nconst address = z.string();\nconst nullableNumber = z.union([z.number(), z.string()]).nullable().optional();\n\nexport const WalletSchema = z.object({\n address: address,\n name: z.string().nullable().optional(),\n threshold: z.number(),\n owner_count: z.number(),\n created_at_block: z.union([z.number(), z.string()]),\n created_at_tx: z.string(),\n min_execution_delay: z.number().nullable().optional(),\n created_at: z.string().nullable().optional(),\n updated_at: z.string().nullable().optional(),\n});\nexport type WalletRow = z.infer<typeof WalletSchema>;\n\nexport const WalletOwnerSchema = z.object({\n wallet_address: address,\n owner_address: address,\n added_at_block: z.union([z.number(), z.string()]),\n added_at_tx: z.string(),\n removed_at_block: nullableNumber,\n removed_at_tx: z.string().nullable().optional(),\n is_active: z.boolean(),\n});\nexport type WalletOwnerRow = z.infer<typeof WalletOwnerSchema>;\n\nexport const TransactionStatusEnum = z.enum([\n 'pending',\n 'executed',\n 'cancelled',\n 'expired',\n 'failed',\n]);\n\nexport const TransactionSchema = z.object({\n wallet_address: address,\n tx_hash: z.string(),\n to_address: address,\n value: z.string(),\n data: z.string().nullable().optional(),\n transaction_type: z.string(),\n decoded_params: z.unknown().nullable().optional(),\n status: TransactionStatusEnum,\n confirmation_count: z.number().nullable().optional(),\n submitted_by: address,\n submitted_at_block: z.union([z.number(), z.string()]),\n submitted_at_tx: z.string(),\n executed_at_block: nullableNumber,\n executed_at_tx: z.string().nullable().optional(),\n executed_by: z.string().nullable().optional(),\n cancelled_at_block: nullableNumber,\n cancelled_at_tx: z.string().nullable().optional(),\n expiration: z.union([z.number(), z.string()]).nullable().optional(),\n execution_delay: z.number().nullable().optional(),\n approved_at: z.union([z.number(), z.string()]).nullable().optional(),\n executable_after: z.union([z.number(), z.string()]).nullable().optional(),\n is_expired: z.boolean().nullable().optional(),\n failed_return_data: z.string().nullable().optional(),\n created_at: z.string().nullable().optional(),\n updated_at: z.string().nullable().optional(),\n});\nexport type TransactionRow = z.infer<typeof TransactionSchema>;\n\nexport const ConfirmationSchema = z.object({\n wallet_address: address,\n tx_hash: z.string(),\n owner_address: address,\n confirmed_at_block: z.union([z.number(), z.string()]),\n confirmed_at_tx: z.string(),\n revoked_at_block: nullableNumber,\n revoked_at_tx: z.string().nullable().optional(),\n is_active: z.boolean(),\n});\nexport type ConfirmationRow = z.infer<typeof ConfirmationSchema>;\n\nexport const WalletModuleSchema = z.object({\n wallet_address: address,\n module_address: address,\n enabled_at_block: z.union([z.number(), z.string()]),\n enabled_at_tx: z.string(),\n disabled_at_block: nullableNumber,\n disabled_at_tx: z.string().nullable().optional(),\n is_active: z.boolean(),\n});\nexport type WalletModuleRow = z.infer<typeof WalletModuleSchema>;\n\nexport const DelegatecallTargetSchema = z.object({\n wallet_address: address,\n target_address: address,\n added_at_block: z.union([z.number(), z.string()]),\n added_at_tx: z.string(),\n removed_at_block: nullableNumber,\n removed_at_tx: z.string().nullable().optional(),\n is_active: z.boolean(),\n});\nexport type DelegatecallTargetRow = z.infer<typeof DelegatecallTargetSchema>;\n\nexport const DepositSchema = z.object({\n wallet_address: address,\n sender_address: address,\n amount: z.string(),\n deposited_at_block: z.union([z.number(), z.string()]),\n deposited_at_tx: z.string(),\n created_at: z.string().nullable().optional(),\n});\nexport type DepositRow = z.infer<typeof DepositSchema>;\n\nexport const TokenSchema = z.object({\n address: address,\n standard: z.enum(['ERC20', 'ERC721', 'ERC1155']),\n symbol: z.string(),\n name: z.string(),\n decimals: z.number(),\n discovered_at_block: nullableNumber,\n discovered_via: z.string().nullable().optional(),\n});\nexport type TokenRow = z.infer<typeof TokenSchema>;\n\nexport const TokenTransferSchema = z.object({\n token_address: address,\n wallet_address: address,\n from_address: address,\n to_address: address,\n value: z.string(),\n token_id: z.string().nullable().optional(),\n batch_index: z.number().nullable().optional(),\n direction: z.enum(['inflow', 'outflow']),\n block_number: z.union([z.number(), z.string()]),\n transaction_hash: z.string(),\n log_index: z.number(),\n});\nexport type TokenTransferRow = z.infer<typeof TokenTransferSchema>;\n\nexport const SignedMessageSchema = z.object({\n wallet_address: address,\n msg_hash: z.string(),\n data: z.string().nullable().optional(),\n signed_at_block: z.union([z.number(), z.string()]),\n signed_at_tx: z.string(),\n unsigned_at_block: nullableNumber,\n unsigned_at_tx: z.string().nullable().optional(),\n is_active: z.boolean(),\n});\nexport type SignedMessageRow = z.infer<typeof SignedMessageSchema>;\n\nexport const IndexerStateSchema = z.object({\n id: z.string(),\n last_indexed_block: z.union([z.number(), z.string()]),\n last_block_hash: z.string().nullable().optional(),\n last_indexed_at: z.string().nullable().optional(),\n is_syncing: z.boolean().nullable().optional(),\n});\nexport type IndexerStateRow = z.infer<typeof IndexerStateSchema>;\n\nexport const RecoveryConfigSchema = z.object({\n wallet_address: address,\n threshold: z.number(),\n recovery_period: z.union([z.number(), z.string()]),\n setup_at_block: z.union([z.number(), z.string()]),\n setup_at_tx: z.string(),\n is_active: z.boolean(),\n});\nexport type RecoveryConfigRow = z.infer<typeof RecoveryConfigSchema>;\n\nexport const RecoveryGuardianSchema = z.object({\n wallet_address: address,\n guardian_address: address,\n added_at_block: z.union([z.number(), z.string()]),\n added_at_tx: z.string(),\n is_active: z.boolean(),\n});\nexport type RecoveryGuardianRow = z.infer<typeof RecoveryGuardianSchema>;\n\nexport const RecoverySchema = z.object({\n wallet_address: address,\n recovery_hash: z.string(),\n new_owners: z.array(address),\n new_threshold: z.number(),\n initiator_address: address,\n approval_count: z.number().nullable().optional(),\n required_threshold: z.number(),\n execution_time: z.union([z.number(), z.string()]),\n status: z.enum(['pending', 'executed', 'cancelled', 'invalidated', 'expired']),\n initiated_at_block: z.union([z.number(), z.string()]),\n initiated_at_tx: z.string(),\n expiration: z.union([z.number(), z.string()]).nullable().optional(),\n});\nexport type RecoveryRow = z.infer<typeof RecoverySchema>;\n\nexport const RecoveryApprovalSchema = z.object({\n wallet_address: address,\n recovery_hash: z.string(),\n guardian_address: address,\n approved_at_block: z.union([z.number(), z.string()]),\n approved_at_tx: z.string(),\n is_active: z.boolean(),\n});\nexport type RecoveryApprovalRow = z.infer<typeof RecoveryApprovalSchema>;\n\n/** Coerce the bigint-ish columns Postgres returns as strings. */\nexport function toNumber(value: unknown, fallback = 0): number {\n if (value === null || value === undefined) return fallback;\n const n = typeof value === 'string' ? Number(value) : (value as number);\n return Number.isFinite(n) ? n : fallback;\n}\n","import type { IndexerClient } from './client.js';\nimport {\n ConfirmationSchema,\n DelegatecallTargetSchema,\n DepositSchema,\n RecoveryApprovalSchema,\n RecoveryConfigSchema,\n RecoveryGuardianSchema,\n RecoverySchema,\n SignedMessageSchema,\n TokenSchema,\n TokenTransferSchema,\n TransactionSchema,\n WalletModuleSchema,\n WalletOwnerSchema,\n WalletSchema,\n type ConfirmationRow,\n type DepositRow,\n type RecoveryApprovalRow,\n type RecoveryRow,\n type SignedMessageRow,\n type TokenRow,\n type TokenTransferRow,\n type TransactionRow,\n type WalletRow,\n} from './schemas.js';\nimport { IndexerQueryError } from '../errors/index.js';\nimport type { Address, Page, Pagination } from '../types.js';\n\nconst DEFAULT_LIMIT = 50;\nconst MAX_LIMIT = 200;\n\nfunction lower(address: Address): string {\n return address.toLowerCase();\n}\n\nfunction bounds(options: Pagination = {}) {\n const limit = Math.min(Math.max(options.limit ?? DEFAULT_LIMIT, 1), MAX_LIMIT);\n const offset = Math.max(options.offset ?? 0, 0);\n return { limit, offset };\n}\n\nexport class IndexerQueries {\n constructor(private readonly client: IndexerClient) {}\n\n // ---- wallets -------------------------------------------------------------\n\n async wallet(address: Address): Promise<WalletRow | null> {\n return this.client.selectOne('wallets', WalletSchema, (q) =>\n q.select('*').eq('address', lower(address)).single(),\n );\n }\n\n /** Active owner addresses, lowercased as stored. */\n async owners(address: Address): Promise<string[]> {\n const rows = await this.client.select('wallet_owners', WalletOwnerSchema, (q) =>\n q.select('*').eq('wallet_address', lower(address)).eq('is_active', true),\n );\n return rows.map((r) => r.owner_address);\n }\n\n async vaultsForOwner(owner: Address, options: Pagination = {}): Promise<WalletRow[]> {\n const { limit, offset } = bounds(options);\n const { data, error } = await this.client\n .from('wallet_owners')\n .select('wallet_address, wallets (*)')\n .eq('owner_address', lower(owner))\n .eq('is_active', true)\n .range(offset, offset + limit - 1);\n\n if (error) throw new IndexerQueryError(`Indexer query failed: ${error.message}`, error);\n return extractJoined(data, WalletSchema);\n }\n\n async vaultsForGuardian(guardian: Address, options: Pagination = {}): Promise<WalletRow[]> {\n const { limit, offset } = bounds(options);\n const { data, error } = await this.client\n .from('social_recovery_guardians')\n .select('wallet_address, wallets (*)')\n .eq('guardian_address', lower(guardian))\n .eq('is_active', true)\n .range(offset, offset + limit - 1);\n\n if (error) throw new IndexerQueryError(`Indexer query failed: ${error.message}`, error);\n return extractJoined(data, WalletSchema);\n }\n\n // ---- transactions --------------------------------------------------------\n\n async pendingTransactions(vault: Address, options: Pagination = {}): Promise<TransactionRow[]> {\n const { limit, offset } = bounds(options);\n return this.client.select('transactions', TransactionSchema, (q) =>\n q\n .select('*')\n .eq('wallet_address', lower(vault))\n .eq('status', 'pending')\n .order('submitted_at_block', { ascending: false })\n .range(offset, offset + limit - 1),\n );\n }\n\n async transaction(vault: Address, txHash: string): Promise<TransactionRow | null> {\n return this.client.selectOne('transactions', TransactionSchema, (q) =>\n q.select('*').eq('wallet_address', lower(vault)).eq('tx_hash', txHash.toLowerCase()).single(),\n );\n }\n\n async transactionHistory(\n vault: Address,\n options: Pagination & { status?: string[] } = {},\n ): Promise<Page<TransactionRow>> {\n const { limit, offset } = bounds(options);\n const statuses = options.status ?? ['executed', 'cancelled', 'expired', 'failed'];\n\n const { data, error, count } = await this.client\n .from('transactions')\n .select('*', { count: 'exact' })\n .eq('wallet_address', lower(vault))\n .in('status', statuses)\n .order('submitted_at_block', { ascending: false })\n .range(offset, offset + limit - 1);\n\n if (error) throw new IndexerQueryError(`Indexer query failed: ${error.message}`, error);\n\n const rows = (data ?? []).map((r) => TransactionSchema.parse(r));\n const total = count ?? rows.length;\n return { data: rows, total, hasMore: offset + rows.length < total };\n }\n\n /** All confirmations for one transaction, including revoked ones. */\n async confirmations(vault: Address, txHash: string): Promise<ConfirmationRow[]> {\n return this.client.select('confirmations', ConfirmationSchema, (q) =>\n q\n .select('*')\n .eq('wallet_address', lower(vault))\n .eq('tx_hash', txHash.toLowerCase())\n .order('confirmed_at_block', { ascending: true }),\n );\n }\n\n /**\n * Active confirmations for many transactions in one round trip.\n *\n * \"Active\" here means not revoked. It does NOT mean the confirming address is\n * still an owner — the indexer does not deactivate confirmations when an owner is\n * removed, while the contract invalidates them via approval epochs. Callers must\n * intersect with the active owner set; `Vault` does this for you.\n */\n async activeConfirmationsBatch(\n vault: Address,\n txHashes: string[],\n ): Promise<Map<string, ConfirmationRow[]>> {\n const result = new Map<string, ConfirmationRow[]>();\n for (const hash of txHashes) result.set(hash.toLowerCase(), []);\n if (txHashes.length === 0) return result;\n\n const rows = await this.client.select('confirmations', ConfirmationSchema, (q) =>\n q\n .select('*')\n .eq('wallet_address', lower(vault))\n .in(\n 'tx_hash',\n txHashes.map((h) => h.toLowerCase()),\n )\n .eq('is_active', true),\n );\n\n for (const row of rows) {\n const key = row.tx_hash.toLowerCase();\n const list = result.get(key);\n if (list) list.push(row);\n else result.set(key, [row]);\n }\n return result;\n }\n\n // ---- modules and delegatecall --------------------------------------------\n\n async modules(vault: Address): Promise<string[]> {\n const rows = await this.client.select('wallet_modules', WalletModuleSchema, (q) =>\n q.select('*').eq('wallet_address', lower(vault)).eq('is_active', true),\n );\n return rows.map((r) => r.module_address);\n }\n\n async delegatecallTargets(vault: Address): Promise<string[]> {\n const rows = await this.client.select(\n 'wallet_delegatecall_targets',\n DelegatecallTargetSchema,\n (q) => q.select('*').eq('wallet_address', lower(vault)).eq('is_active', true),\n );\n return rows.map((r) => r.target_address);\n }\n\n // ---- value movement ------------------------------------------------------\n\n async deposits(vault: Address, options: Pagination = {}): Promise<Page<DepositRow>> {\n const { limit, offset } = bounds(options);\n const { data, error, count } = await this.client\n .from('deposits')\n .select('*', { count: 'exact' })\n .eq('wallet_address', lower(vault))\n .order('deposited_at_block', { ascending: false })\n .range(offset, offset + limit - 1);\n\n if (error) throw new IndexerQueryError(`Indexer query failed: ${error.message}`, error);\n const rows = (data ?? []).map((r) => DepositSchema.parse(r));\n const total = count ?? rows.length;\n return { data: rows, total, hasMore: offset + rows.length < total };\n }\n\n async tokenTransfers(vault: Address, options: Pagination = {}): Promise<Page<TokenTransferRow>> {\n const { limit, offset } = bounds(options);\n const { data, error, count } = await this.client\n .from('token_transfers')\n .select('*', { count: 'exact' })\n .eq('wallet_address', lower(vault))\n .order('block_number', { ascending: false })\n .range(offset, offset + limit - 1);\n\n if (error) throw new IndexerQueryError(`Indexer query failed: ${error.message}`, error);\n const rows = (data ?? []).map((r) => TokenTransferSchema.parse(r));\n const total = count ?? rows.length;\n return { data: rows, total, hasMore: offset + rows.length < total };\n }\n\n async tokens(addresses: string[]): Promise<TokenRow[]> {\n if (addresses.length === 0) return [];\n return this.client.select('tokens', TokenSchema, (q) =>\n q.select('*').in('address', addresses.map(lower)),\n );\n }\n\n async signedMessages(vault: Address): Promise<SignedMessageRow[]> {\n return this.client.select('signed_messages', SignedMessageSchema, (q) =>\n q.select('*').eq('wallet_address', lower(vault)).eq('is_active', true),\n );\n }\n\n // ---- social recovery -----------------------------------------------------\n\n async recoveryConfig(\n vault: Address,\n ): Promise<{ threshold: number; recoveryPeriod: number; guardians: string[] } | null> {\n const config = await this.client.selectOne('social_recovery_configs', RecoveryConfigSchema, (q) =>\n q.select('*').eq('wallet_address', lower(vault)).eq('is_active', true).single(),\n );\n if (!config) return null;\n\n const guardians = await this.client.select(\n 'social_recovery_guardians',\n RecoveryGuardianSchema,\n (q) => q.select('*').eq('wallet_address', lower(vault)).eq('is_active', true),\n );\n\n return {\n threshold: config.threshold,\n recoveryPeriod: Number(config.recovery_period),\n guardians: guardians.map((g) => g.guardian_address),\n };\n }\n\n async pendingRecoveries(vault: Address): Promise<RecoveryRow[]> {\n return this.client.select('social_recoveries', RecoverySchema, (q) =>\n q.select('*').eq('wallet_address', lower(vault)).eq('status', 'pending'),\n );\n }\n\n async recoveryHistory(vault: Address, options: Pagination = {}): Promise<RecoveryRow[]> {\n const { limit, offset } = bounds(options);\n return this.client.select('social_recoveries', RecoverySchema, (q) =>\n q\n .select('*')\n .eq('wallet_address', lower(vault))\n .order('initiated_at_block', { ascending: false })\n .range(offset, offset + limit - 1),\n );\n }\n\n async recoveryApprovals(vault: Address, recoveryHash: string): Promise<RecoveryApprovalRow[]> {\n return this.client.select('social_recovery_approvals', RecoveryApprovalSchema, (q) =>\n q\n .select('*')\n .eq('wallet_address', lower(vault))\n .eq('recovery_hash', recoveryHash.toLowerCase())\n .eq('is_active', true),\n );\n }\n}\n\n/**\n * Pull the embedded rows out of a PostgREST join, dropping any that fail validation\n * rather than failing the whole query over one malformed row.\n */\nfunction extractJoined<T>(\n data: unknown[] | null,\n schema: { parse: (value: unknown) => T },\n): T[] {\n const out: T[] = [];\n for (const row of data ?? []) {\n const embedded = (row as { wallets?: unknown }).wallets;\n if (!embedded) continue;\n // PostgREST returns an object for a to-one join, an array for to-many.\n const candidates = Array.isArray(embedded) ? embedded : [embedded];\n for (const candidate of candidates) {\n try {\n out.push(schema.parse(candidate));\n } catch {\n continue;\n }\n }\n }\n return out;\n}\n","import { formatQuai, getAddress, getZoneForAddress, toShard } from 'quais';\nimport { assertQuaiAddress, assertQuaiAddresses } from './address.js';\nimport type { Connection } from './chain/connection.js';\nimport { VaultContract } from './chain/vault-contract.js';\nimport { RecoveryModule } from './recovery.js';\nimport { loadBalances, type BalanceOptions, type VaultBalances } from './balances.js';\nimport { watchVault, type Subscription, type WatchEvent, type WatchOptions } from './indexer/watch.js';\nimport { normalizeTxHash } from './chain/connection.js';\nimport type { IndexerClient } from './indexer/client.js';\nimport type { IndexerQueries } from './indexer/queries.js';\nimport type { TransactionRow } from './indexer/schemas.js';\nimport { toNumber } from './indexer/schemas.js';\nimport { decodeCall, type DecodedBatchCall } from './decode/index.js';\nimport { decodeRevert, decodeRevertFromError } from './errors/decode.js';\nimport {\n MAX_EXECUTION_DELAY,\n SENTINEL_MODULES,\n encodeMultiSend,\n minimumExpiration,\n selfCall,\n token as tokenEncode,\n recoveryCall,\n type BatchCall,\n} from './encode/index.js';\nimport {\n NoIndexerError,\n NotFoundError,\n PreconditionError,\n RevertError,\n StaleProposalError,\n ValidationError,\n} from './errors/index.js';\nimport { computeAffordances } from './lifecycle/affordances.js';\nimport { classifyExecution, extractProposedTxHash, type ReceiptLike } from './lifecycle/outcome.js';\nimport { deriveStatus, executableAfterOf, nowSeconds } from './lifecycle/status.js';\nimport type {\n Address,\n Affordance,\n ApprovalRecord,\n Bytes32,\n ContractAddresses,\n Consistency,\n DryRunResult,\n ExecuteResult,\n Hex,\n Page,\n Pagination,\n ProposeOptions,\n ProposeResult,\n VaultInfo,\n VaultTransaction,\n} from './types.js';\n\nexport interface VaultContext {\n connection: Connection;\n indexer: IndexerClient | null;\n queries: IndexerQueries | null;\n contracts: ContractAddresses;\n consistency: Consistency;\n maxIndexerLagBlocks: number;\n}\n\n/** A handle to one deployed vault. Cheap to construct; performs no I/O until used. */\nexport class Vault {\n readonly address: Address;\n /** Guardian-based recovery for this vault. */\n readonly recovery: RecoveryModule;\n private readonly ctx: VaultContext;\n\n constructor(address: Address, ctx: VaultContext) {\n // A deployed vault is always a Quai-ledger contract in a real zone, so anything\n // else is a typo or a Qi address and would fail every call.\n this.address = assertQuaiAddress(address, 'vault address');\n this.ctx = ctx;\n this.recovery = new RecoveryModule({\n connection: ctx.connection,\n queries: ctx.queries,\n vaultAddress: this.address,\n moduleAddress: ctx.contracts.socialRecovery,\n });\n }\n\n // =========================================================================\n // Read resolution\n // =========================================================================\n\n /**\n * Whether an indexer read is acceptable right now.\n *\n * `auto` uses the indexer only while it is live and within the configured lag\n * budget, so a stalled indexer silently degrades to chain reads instead of\n * serving stale state.\n */\n private async useIndexer(): Promise<boolean> {\n if (this.ctx.consistency === 'chain') return false;\n if (!this.ctx.indexer || !this.ctx.queries) {\n if (this.ctx.consistency === 'indexed') throw new NoIndexerError('This read');\n return false;\n }\n if (this.ctx.consistency === 'indexed') return true;\n\n const health = await this.ctx.indexer.health();\n if (!health.available) return false;\n if (health.blocksBehind !== undefined && health.blocksBehind > this.ctx.maxIndexerLagBlocks) {\n return false;\n }\n return true;\n }\n\n private requireQueries(operation: string): IndexerQueries {\n if (!this.ctx.queries) throw new NoIndexerError(operation);\n return this.ctx.queries;\n }\n\n private contract(write = false): VaultContract {\n return new VaultContract(this.ctx.connection.vault(this.address, write), this.ctx.connection.retry);\n }\n\n // =========================================================================\n // Vault state\n // =========================================================================\n\n /** Owners, threshold, timelock floor, nonce and balance. Always read from chain. */\n async info(): Promise<VaultInfo> {\n const vault = this.contract();\n const [owners, threshold, minExecutionDelay, nonce, moduleCount, balance] = await Promise.all([\n vault.getOwners(),\n vault.threshold(),\n vault.minExecutionDelay(),\n vault.nonce(),\n vault.moduleCount(),\n this.ctx.connection.provider.getBalance(this.address),\n ]);\n\n return {\n address: this.address,\n owners: Array.from(owners).map((o) => getAddress(String(o))),\n threshold: Number(threshold),\n minExecutionDelay: Number(minExecutionDelay),\n nonce: Number(nonce),\n moduleCount: Number(moduleCount),\n balance: BigInt(balance),\n };\n }\n\n /** Active owners. Prefers the indexer, falls back to chain. */\n async owners(): Promise<Address[]> {\n if (await this.useIndexer()) {\n try {\n const owners = await this.requireQueries('owners').owners(this.address);\n if (owners.length > 0) return owners.map((o) => getAddress(o));\n } catch {\n // fall through to chain\n }\n }\n return (await this.contract().getOwners()).map((o) => getAddress(String(o)));\n }\n\n async isOwner(address: Address): Promise<boolean> {\n return this.contract().isOwner(getAddress(address));\n }\n\n async threshold(): Promise<number> {\n return Number(await this.contract().threshold());\n }\n\n async balance(): Promise<bigint> {\n return BigInt(await this.ctx.connection.provider.getBalance(this.address));\n }\n\n /**\n * Enabled modules, in linked-list order.\n *\n * Order matters: `disableModule` needs each module's predecessor, so this always\n * reads the chain rather than the indexer (which stores an unordered set).\n */\n async modules(): Promise<Address[]> {\n return (await this.contract().getModules()).map((m) => getAddress(String(m)));\n }\n\n async isModuleEnabled(module: Address): Promise<boolean> {\n return this.contract().isModuleEnabled(getAddress(module));\n }\n\n /** Addresses permitted as DelegateCall targets. Empty means DelegateCall is disabled. */\n async delegatecallTargets(): Promise<Address[]> {\n // Indexer-only, with no fallback and no retry-on-failure: `delegatecallAllowed`\n // is a mapping, so the chain cannot enumerate it. A failure here is terminal, and\n // swallowing it only to reissue the identical query would double the load and\n // surface a more confusing second error. Use `isDelegatecallAllowed(target)` to\n // check a specific address against the chain.\n const targets = await this.requireQueries('Listing DelegateCall targets').delegatecallTargets(\n this.address,\n );\n return targets.map((t) => getAddress(t));\n }\n\n async isDelegatecallAllowed(target: Address): Promise<boolean> {\n return this.contract().delegatecallAllowed(getAddress(target));\n }\n\n /** Whether a hash has been pre-approved for EIP-1271 validation. */\n async isValidSignature(hash: Bytes32): Promise<boolean> {\n const magic = await this.contract().isValidSignature(normalizeTxHash(hash, 'hash'), '0x');\n return magic.toLowerCase() === '0x1626ba7e';\n }\n\n // =========================================================================\n // Transactions\n // =========================================================================\n\n /** The vault-transaction hash for a given call, at a given nonce. */\n async transactionHash(\n to: Address,\n value: bigint,\n data: Hex,\n nonce?: number,\n ): Promise<Bytes32> {\n const vault = this.contract();\n const n = nonce ?? Number(await vault.nonce());\n return vault.getTransactionHash(getAddress(to), value, data, n);\n }\n\n async transaction(txHash: Bytes32): Promise<VaultTransaction> {\n const hash = normalizeTxHash(txHash);\n\n if (await this.useIndexer()) {\n try {\n const tx = await this.fromIndexer(hash);\n if (tx) return tx;\n } catch {\n // fall through to chain\n }\n }\n return this.fromChain(hash);\n }\n\n async pendingTransactions(options: Pagination = {}): Promise<VaultTransaction[]> {\n const queries = this.requireQueries('Listing pending transactions');\n const [rows, owners, threshold] = await Promise.all([\n queries.pendingTransactions(this.address, options),\n this.owners(),\n this.threshold(),\n ]);\n return this.hydrateRows(rows, owners, threshold);\n }\n\n async transactionHistory(\n options: Pagination & { status?: string[] } = {},\n ): Promise<Page<VaultTransaction>> {\n const queries = this.requireQueries('Listing transaction history');\n const [page, owners, threshold] = await Promise.all([\n queries.transactionHistory(this.address, options),\n this.owners(),\n this.threshold(),\n ]);\n return {\n data: await this.hydrateRows(page.data, owners, threshold),\n total: page.total,\n hasMore: page.hasMore,\n };\n }\n\n // ---- hydration -----------------------------------------------------------\n\n private async hydrateRows(\n rows: TransactionRow[],\n owners: Address[],\n threshold: number,\n ): Promise<VaultTransaction[]> {\n if (rows.length === 0) return [];\n const queries = this.requireQueries('Loading confirmations');\n const confirmations = await queries.activeConfirmationsBatch(\n this.address,\n rows.map((r) => r.tx_hash),\n );\n const indexedAtBlock = (await this.ctx.indexer?.state())?.lastIndexedBlock;\n\n return rows.map((row) => {\n const confirmed = (confirmations.get(row.tx_hash.toLowerCase()) ?? []).map(\n (c) => c.owner_address,\n );\n return this.buildTransaction({\n row,\n confirmedBy: confirmed,\n owners,\n threshold,\n indexedAtBlock,\n });\n });\n }\n\n private async fromIndexer(hash: Bytes32): Promise<VaultTransaction | null> {\n const queries = this.requireQueries('Reading a transaction');\n const [row, owners, threshold] = await Promise.all([\n queries.transaction(this.address, hash),\n this.owners(),\n this.threshold(),\n ]);\n if (!row) return null;\n\n const confirmations = await queries.confirmations(this.address, hash);\n const indexedAtBlock = (await this.ctx.indexer?.state())?.lastIndexedBlock;\n\n return this.buildTransaction({\n row,\n confirmedBy: confirmations.filter((c) => c.is_active).map((c) => c.owner_address),\n owners,\n threshold,\n indexedAtBlock,\n });\n }\n\n /**\n * Build a `VaultTransaction` from an indexed row.\n *\n * Approval counting intersects the indexer's confirmations with the current owner\n * set. The indexer marks a confirmation inactive only on an explicit\n * `ApprovalRevoked`; it does not react to `OwnerRemoved`. On chain, removing an\n * owner bumps `ownerVersions` and invalidates every approval that address made, so\n * the stored `confirmation_count` over-reports after any removal. Intersecting here\n * reproduces the contract's `_countValidApprovals`.\n */\n private buildTransaction(input: {\n row: TransactionRow;\n confirmedBy: string[];\n owners: Address[];\n threshold: number;\n indexedAtBlock?: number;\n }): VaultTransaction {\n const { row, owners, threshold, indexedAtBlock } = input;\n const ownerSet = new Set(owners.map((o) => o.toLowerCase()));\n const confirmedSet = new Set(input.confirmedBy.map((c) => c.toLowerCase()));\n\n const approvals: ApprovalRecord[] = owners\n .filter((o) => confirmedSet.has(o.toLowerCase()))\n .map((o) => ({ owner: o, active: true }));\n\n // Confirmations from addresses that are no longer owners: surfaced but not counted.\n for (const confirmed of confirmedSet) {\n if (!ownerSet.has(confirmed)) {\n approvals.push({ owner: getAddress(confirmed), active: false });\n }\n }\n\n const approvalCount = approvals.filter((a) => a.active).length;\n const value = BigInt(row.value);\n const data = (row.data ?? '0x') as Hex;\n const to = getAddress(row.to_address);\n\n const decodeResult = decodeCall({\n vault: this.address,\n to,\n value,\n data,\n socialRecovery: this.ctx.contracts.socialRecovery,\n multiSendCallOnly: this.ctx.contracts.multiSendCallOnly,\n });\n\n const expiration = toNumber(row.expiration);\n const executionDelay = toNumber(row.execution_delay);\n const approvedAt = toNumber(row.approved_at);\n\n const status = deriveStatus({\n executed: row.status === 'executed' || row.status === 'failed',\n cancelled: row.status === 'cancelled' || row.status === 'expired',\n isExpired: row.is_expired ?? row.status === 'expired',\n expiration,\n executionDelay,\n approvedAt,\n approvalCount,\n threshold,\n failed: row.status === 'failed',\n });\n\n const failedReturnData = row.failed_return_data ?? undefined;\n\n return {\n hash: row.tx_hash,\n vault: this.address,\n to,\n value,\n data,\n proposer: getAddress(row.submitted_by),\n proposedAt: toNumber(row.submitted_at_block),\n kind: decodeResult.kind,\n decoded: decodeResult.decoded,\n summary: decodeResult.summary,\n status,\n approvals,\n approvalCount,\n threshold,\n expiration,\n executionDelay,\n approvedAt,\n executableAfter: executableAfterOf(approvedAt, executionDelay),\n failedReturnData: failedReturnData as Hex | undefined,\n decodedRevert: failedReturnData ? decodeRevert(failedReturnData) : undefined,\n source: 'indexer',\n indexedAtBlock,\n };\n }\n\n /** Authoritative read: the struct plus a `hasApproved` probe per current owner. */\n private async fromChain(hash: Bytes32): Promise<VaultTransaction> {\n const vault = this.contract();\n const [raw, owners, threshold, isExpired] = await Promise.all([\n vault.transactions(hash),\n vault.getOwners(),\n vault.threshold(),\n vault.expiredTxs(hash),\n ]);\n\n const to = String(raw.to);\n if (!to || to === '0x0000000000000000000000000000000000000000') {\n throw new NotFoundError(`No transaction ${hash} on vault ${this.address}.`);\n }\n\n const ownerList = owners.map((o) => getAddress(String(o)));\n const approvalFlags = await Promise.all(\n ownerList.map((owner) => vault.hasApproved(hash, owner)),\n );\n const approvals: ApprovalRecord[] = ownerList\n .map((owner, i) => ({ owner, active: approvalFlags[i] === true }))\n .filter((a) => a.active);\n\n const value = BigInt(raw.value ?? 0);\n const data = String(raw.data ?? '0x') as Hex;\n const expiration = Number(raw.expiration ?? 0);\n const executionDelay = Number(raw.executionDelay ?? 0);\n const approvedAt = Number(raw.approvedAt ?? 0);\n const executed = Boolean(raw.executed);\n const cancelled = Boolean(raw.cancelled);\n\n const decodeResult = decodeCall({\n vault: this.address,\n to: getAddress(to),\n value,\n data,\n socialRecovery: this.ctx.contracts.socialRecovery,\n multiSendCallOnly: this.ctx.contracts.multiSendCallOnly,\n });\n\n return {\n hash,\n vault: this.address,\n to: getAddress(to),\n value,\n data,\n proposer: getAddress(String(raw.proposer)),\n proposedAt: Number(raw.timestamp ?? 0),\n kind: decodeResult.kind,\n decoded: decodeResult.decoded,\n summary: decodeResult.summary,\n status: deriveStatus({\n executed,\n cancelled,\n isExpired,\n expiration,\n executionDelay,\n approvedAt,\n approvalCount: approvals.length,\n threshold: Number(threshold),\n }),\n approvals,\n approvalCount: approvals.length,\n threshold: Number(threshold),\n expiration,\n executionDelay,\n approvedAt,\n executableAfter: executableAfterOf(approvedAt, executionDelay),\n source: 'chain',\n };\n }\n\n // =========================================================================\n // Affordances\n // =========================================================================\n\n /**\n * What `caller` may legally do to `txHash` right now, and when blocked actions\n * become available. Defaults to the connected signer's address.\n */\n async affordances(txHash: Bytes32, caller?: Address): Promise<Affordance[]> {\n const hash = normalizeTxHash(txHash);\n const who = caller ?? (await this.ctx.connection.addressOrNull());\n if (!who) {\n throw new ValidationError(\n 'affordances() needs a caller address when the client has no signer.',\n );\n }\n\n const vault = this.contract();\n const [tx, isOwner, hasApproved] = await Promise.all([\n this.transaction(hash),\n vault.isOwner(getAddress(who)),\n vault.hasApproved(hash, getAddress(who)),\n ]);\n\n return computeAffordances({ tx, caller: getAddress(who), isOwner, hasApproved });\n }\n\n // =========================================================================\n // Proposals\n // =========================================================================\n\n /**\n * Proposal builders.\n *\n * Every method here is async, including the ones whose work is purely local. Mixing\n * synchronous throws with rejected promises is a footgun: `propose.addOwner(bad)`\n * would throw before `.catch()` could attach. Validation failures are always\n * rejections.\n */\n readonly propose = {\n /** Propose an arbitrary call. Every other `propose.*` helper routes through this. */\n call: async (\n params: { to: Address; value?: bigint; data?: Hex } & ProposeOptions,\n ): Promise<ProposeResult | DryRunResult> =>\n this.proposeCall({\n to: assertQuaiAddress(params.to, 'target'),\n value: params.value,\n data: params.data,\n ...proposeOptionsOf(params),\n }),\n\n /** Send native QUAI. */\n transfer: async (\n params: { to: Address; amount: bigint } & ProposeOptions,\n ): Promise<ProposeResult | DryRunResult> =>\n this.proposeCall({\n // Native value sent to a Qi address leaves the Quai ledger and is unrecoverable.\n to: assertQuaiAddress(params.to, 'recipient'),\n value: params.amount,\n data: '0x',\n ...proposeOptionsOf(params),\n }),\n\n erc20Transfer: async (\n params: { token: Address; to: Address; amount: bigint } & ProposeOptions,\n ): Promise<ProposeResult | DryRunResult> =>\n this.proposeCall({\n to: assertQuaiAddress(params.token, 'token'),\n value: 0n,\n data: tokenEncode.erc20Transfer(assertQuaiAddress(params.to, 'recipient'), params.amount),\n ...proposeOptionsOf(params),\n }),\n\n erc721Transfer: async (\n params: { token: Address; to: Address; tokenId: bigint } & ProposeOptions,\n ): Promise<ProposeResult | DryRunResult> =>\n this.proposeCall({\n to: assertQuaiAddress(params.token, 'token'),\n value: 0n,\n data: tokenEncode.erc721Transfer(\n this.address,\n assertQuaiAddress(params.to, 'recipient'),\n params.tokenId,\n ),\n ...proposeOptionsOf(params),\n }),\n\n erc1155Transfer: async (\n params: {\n token: Address;\n to: Address;\n id: bigint;\n amount: bigint;\n data?: Hex;\n } & ProposeOptions,\n ): Promise<ProposeResult | DryRunResult> =>\n this.proposeCall({\n to: assertQuaiAddress(params.token, 'token'),\n value: 0n,\n data: tokenEncode.erc1155Transfer(\n this.address,\n assertQuaiAddress(params.to, 'recipient'),\n params.id,\n params.amount,\n params.data ?? '0x',\n ),\n ...proposeOptionsOf(params),\n }),\n\n /**\n * Batch several calls through MultiSendCallOnly.\n *\n * Requires MultiSendCallOnly to be on this vault's DelegateCall whitelist, which\n * is empty by default. The precondition is checked before signing so the failure\n * names the missing `addDelegatecallTarget` proposal instead of reverting.\n */\n batch: async (\n calls: BatchCall[],\n options: ProposeOptions = {},\n ): Promise<ProposeResult | DryRunResult> => {\n const multiSend = this.ctx.contracts.multiSendCallOnly;\n if (!multiSend) {\n throw new ValidationError(\n 'No MultiSendCallOnly address is configured for this network.',\n 'Set QUAIVAULT_MULTISEND_CALL_ONLY or pass contracts.multiSendCallOnly.',\n );\n }\n if (!(await this.isDelegatecallAllowed(multiSend))) {\n throw new PreconditionError(\n `MultiSendCallOnly (${multiSend}) is not on this vault's DelegateCall whitelist, so a ` +\n 'batched call cannot execute.',\n {\n remediation:\n `Propose and execute addDelegatecallTarget(${multiSend}) first — it requires full ` +\n 'owner consensus, by design.',\n },\n );\n }\n calls.forEach((call, i) => assertQuaiAddress(call.to, `calls[${i}].to`));\n return this.proposeCall({\n to: multiSend,\n value: 0n,\n data: encodeMultiSend(calls),\n ...proposeOptionsOf(options),\n });\n },\n\n // --- self-calls -------------------------------------------------------\n\n addOwner: async (owner: Address, options: ProposeOptions = {}) =>\n this.proposeSelfCall(selfCall.addOwner(assertQuaiAddress(owner, 'owner')), options),\n\n removeOwner: async (owner: Address, options: ProposeOptions = {}) => {\n const [owners, threshold] = await Promise.all([this.owners(), this.threshold()]);\n if (!owners.some((o) => o.toLowerCase() === owner.toLowerCase())) {\n throw new PreconditionError(`${owner} is not an owner of this vault.`);\n }\n if (owners.length - 1 < threshold) {\n throw new PreconditionError(\n `Removing an owner would leave ${owners.length - 1} owners, below the threshold of ${threshold}.`,\n { remediation: 'Lower the threshold first, in a separate proposal.' },\n );\n }\n return this.proposeSelfCall(selfCall.removeOwner(getAddress(owner)), options);\n },\n\n changeThreshold: async (threshold: number, options: ProposeOptions = {}) => {\n const owners = await this.owners();\n if (threshold < 1 || threshold > owners.length) {\n throw new ValidationError(\n `Invalid threshold ${threshold}: this vault has ${owners.length} owners.`,\n );\n }\n return this.proposeSelfCall(selfCall.changeThreshold(threshold), options);\n },\n\n setMinExecutionDelay: async (seconds: number, options: ProposeOptions = {}) =>\n this.proposeSelfCall(selfCall.setMinExecutionDelay(seconds), options),\n\n enableModule: async (module: Address, options: ProposeOptions = {}) =>\n this.proposeSelfCall(selfCall.enableModule(assertQuaiAddress(module, 'module')), options),\n\n /**\n * Disable a module, resolving its predecessor in the Zodiac linked list.\n *\n * The predecessor is baked into the proposal, so any module added or removed\n * before this executes invalidates it. `execute` re-checks and raises\n * `StaleProposalError` rather than letting it revert on chain.\n */\n disableModule: async (module: Address, options: ProposeOptions = {}) => {\n const prev = await this.previousModule(getAddress(module));\n return this.proposeSelfCall(selfCall.disableModule(prev, getAddress(module)), options);\n },\n\n addDelegatecallTarget: async (target: Address, options: ProposeOptions = {}) =>\n this.proposeSelfCall(\n selfCall.addDelegatecallTarget(assertQuaiAddress(target, 'delegatecall target')),\n options,\n ),\n\n removeDelegatecallTarget: async (target: Address, options: ProposeOptions = {}) =>\n this.proposeSelfCall(selfCall.removeDelegatecallTarget(getAddress(target)), options),\n\n /** Cancel a transaction that has already reached quorum. Needs full consensus. */\n cancelByConsensus: async (txHash: Bytes32, options: ProposeOptions = {}) =>\n this.proposeSelfCall(selfCall.cancelByConsensus(normalizeTxHash(txHash)), options),\n\n /** Sign arbitrary bytes. For EIP-1271 hash approval use `approveHashForEip1271`. */\n signMessage: async (message: Hex, options: ProposeOptions = {}) =>\n this.proposeSelfCall(selfCall.signMessage(message), options),\n\n unsignMessage: async (message: Hex, options: ProposeOptions = {}) =>\n this.proposeSelfCall(selfCall.unsignMessage(message), options),\n\n /**\n * Make `isValidSignature(hash, …)` return the EIP-1271 magic value.\n *\n * Enforces the 32-byte precondition: signing an arbitrary-length message `M`\n * does not make `isValidSignature(keccak256(M))` validate, because EIP-1271\n * hashes the dataHash itself, not `M`.\n */\n approveHashForEip1271: async (hash: Bytes32, options: ProposeOptions = {}) =>\n this.proposeSelfCall(selfCall.approveHashForEip1271(normalizeTxHash(hash, 'hash')), options),\n\n revokeHashForEip1271: async (hash: Bytes32, options: ProposeOptions = {}) =>\n this.proposeSelfCall(selfCall.revokeHashForEip1271(normalizeTxHash(hash, 'hash')), options),\n\n /** Configure social recovery. A call to the module, not a self-call. */\n setupRecovery: async (\n params: { guardians: Address[]; threshold: number; recoveryPeriodSeconds: number } & ProposeOptions,\n ) => {\n const module = this.ctx.contracts.socialRecovery;\n if (!module) {\n throw new ValidationError(\n 'No SocialRecoveryModule address is configured for this network.',\n 'Set QUAIVAULT_SOCIAL_RECOVERY_MODULE or pass contracts.socialRecovery.',\n );\n }\n return this.proposeCall({\n to: module,\n value: 0n,\n data: recoveryCall.setupRecovery(\n this.address,\n // A Qi guardian could never approve a recovery.\n assertQuaiAddresses(params.guardians, 'guardians'),\n params.threshold,\n params.recoveryPeriodSeconds,\n ),\n ...proposeOptionsOf(params),\n });\n },\n };\n\n /** Predecessor of `module` in the Zodiac linked list, for `disableModule`. */\n async previousModule(module: Address): Promise<Address> {\n const modules = await this.modules();\n const index = modules.findIndex((m) => m.toLowerCase() === module.toLowerCase());\n if (index === -1) {\n throw new PreconditionError(`Module ${module} is not enabled on this vault.`);\n }\n // Safe: `index === -1` already threw, and the ternary excludes 0, so index >= 1.\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n return index === 0 ? SENTINEL_MODULES : modules[index - 1]!;\n }\n\n private proposeSelfCall(data: Hex, options: ProposeOptions) {\n // Self-calls always execute immediately: the contract forces executionDelay to 0\n // and rejects any value. Passing a delay would be silently ignored, so reject it.\n if (options.executionDelay) {\n throw new ValidationError(\n 'Self-calls always execute immediately — the vault forces executionDelay to 0 for them.',\n );\n }\n return this.proposeCall({\n to: this.address,\n value: 0n,\n data,\n ...proposeOptionsOf(options),\n });\n }\n\n private async proposeCall(params: {\n to: Address;\n value?: bigint;\n data?: Hex;\n expiration?: number;\n executionDelay?: number;\n dryRun?: boolean;\n }): Promise<ProposeResult | DryRunResult> {\n const to = getAddress(params.to);\n const value = params.value ?? 0n;\n const data = params.data ?? '0x';\n\n if (data !== '0x' && !/^0x([0-9a-fA-F]{2})*$/.test(data)) {\n throw new ValidationError('Transaction data must be 0x-prefixed hex with an even length.');\n }\n\n const isSelfCall = to.toLowerCase() === this.address.toLowerCase();\n if (isSelfCall && value > 0n) {\n throw new ValidationError(\n 'Self-calls cannot carry value — the vault rejects them at proposal time.',\n );\n }\n\n const expiration = params.expiration ?? 0;\n const executionDelay = params.executionDelay ?? 0;\n\n if (executionDelay > MAX_EXECUTION_DELAY) {\n throw new ValidationError(\n `executionDelay ${executionDelay}s exceeds the 30-day maximum (${MAX_EXECUTION_DELAY}s).`,\n );\n }\n\n // Reproduce the contract's ExpirationTooSoon check before signing.\n if (expiration > 0) {\n const floor = isSelfCall ? 0 : Math.max(executionDelay, await this.minExecutionDelay());\n const earliest = minimumExpiration(floor, 0);\n if (expiration <= earliest) {\n throw new ValidationError(\n `expiration ${expiration} is too soon: with an effective delay of ${floor}s the vault ` +\n `requires an expiration after ${earliest}.`,\n `Use at least ${minimumExpiration(floor)} to leave a margin for block time.`,\n );\n }\n }\n\n // Explicit overload signatures — quais cannot disambiguate the three\n // proposeTransaction overloads from argument counts alone.\n const useFullOverload = params.expiration != null || params.executionDelay != null;\n\n if (params.dryRun) {\n const readVault = this.contract();\n const encoded = useFullOverload\n ? readVault.encode('proposeTransaction(address,uint256,bytes,uint48,uint32)', [\n to,\n value,\n data,\n expiration,\n executionDelay,\n ])\n : readVault.encode('proposeTransaction(address,uint256,bytes)', [to, value, data]);\n\n let gasEstimate: bigint | null = null;\n let wouldRevert;\n const from = await this.ctx.connection.addressOrNull();\n // Quai requires `from` on a transaction request (it selects the shard), and it\n // matters semantically too: the vault's onlyOwner check makes estimation revert\n // for a non-owner, which is exactly the signal a dry run should surface. Without\n // a signer there is nothing to estimate against, so the estimate stays null.\n if (from) {\n try {\n gasEstimate = BigInt(\n await this.ctx.connection.provider.estimateGas({\n to: this.address,\n data: encoded,\n from,\n }),\n );\n } catch (err) {\n wouldRevert = decodeRevertFromError(err);\n }\n }\n const decoded = decodeCall({\n vault: this.address,\n to,\n value,\n data,\n socialRecovery: this.ctx.contracts.socialRecovery,\n multiSendCallOnly: this.ctx.contracts.multiSendCallOnly,\n });\n return {\n dryRun: true,\n to: this.address,\n data: encoded,\n value: 0n,\n gasEstimate,\n wouldRevert,\n description: `Propose: ${decoded.summary}`,\n };\n }\n\n await this.assertCallerIsOwner('Proposing a transaction');\n\n const writeVault = this.contract(true);\n let receipt: ReceiptLike;\n try {\n const sent = useFullOverload\n ? await writeVault.proposeTransactionFull(to, value, data, expiration, executionDelay)\n : await writeVault.proposeTransactionSimple(to, value, data);\n receipt = (await sent.wait()) as ReceiptLike;\n } catch (err) {\n throw toRevertError(err, 'Transaction proposal failed');\n }\n\n assertReceipt(receipt, 'Proposal', 'The proposal transaction reverted.');\n\n const txHash = extractProposedTxHash(receipt, this.address);\n if (!txHash) {\n throw new RevertError(\n 'The proposal was mined but no TransactionProposed event was found. ' +\n 'Check that the vault address is correct.',\n );\n }\n\n return {\n txHash,\n chainTxHash: (receipt.hash ?? receipt.transactionHash ?? '') as Hex,\n to,\n value,\n data,\n };\n }\n\n private async minExecutionDelay(): Promise<number> {\n return Number(await this.contract().minExecutionDelay());\n }\n\n // =========================================================================\n // Lifecycle writes\n // =========================================================================\n\n async approve(txHash: Bytes32): Promise<{ chainTxHash: Hex }> {\n const hash = normalizeTxHash(txHash);\n const caller = await this.assertCallerIsOwner('Approving a transaction');\n\n const vault = this.contract(true);\n if (await vault.hasApproved(hash, caller)) {\n throw new PreconditionError('You have already approved this transaction.');\n }\n\n try {\n const sent = await vault.approveTransaction(hash);\n const receipt = (await sent.wait()) as ReceiptLike;\n assertReceipt(receipt, 'Approval', 'The approval transaction reverted.');\n return { chainTxHash: (receipt.hash ?? receipt.transactionHash ?? '') as Hex };\n } catch (err) {\n throw toRevertError(err, 'Approval failed');\n }\n }\n\n async revokeApproval(txHash: Bytes32): Promise<{ chainTxHash: Hex }> {\n const hash = normalizeTxHash(txHash);\n const caller = await this.assertCallerIsOwner('Revoking an approval');\n\n const vault = this.contract(true);\n if (!(await vault.hasApproved(hash, caller))) {\n throw new PreconditionError('You have no active approval on this transaction to revoke.');\n }\n\n try {\n const sent = await vault.revokeApproval(hash);\n const receipt = (await sent.wait()) as ReceiptLike;\n assertReceipt(receipt, 'Revocation', 'The revocation transaction reverted.');\n return { chainTxHash: (receipt.hash ?? receipt.transactionHash ?? '') as Hex };\n } catch (err) {\n throw toRevertError(err, 'Revoking the approval failed');\n }\n }\n\n /**\n * Execute a transaction that has reached quorum.\n *\n * The returned {@link ExecuteResult} says what actually happened. A successful\n * receipt does not imply execution — see {@link classifyExecution}.\n */\n async execute(txHash: Bytes32): Promise<ExecuteResult> {\n const hash = normalizeTxHash(txHash);\n await this.assertCallerIsOwner('Executing a transaction');\n await this.assertExecutable(hash);\n\n const vault = this.contract(true);\n try {\n const sent = await vault.executeTransaction(hash);\n const receipt = (await sent.wait()) as ReceiptLike;\n assertReceipt(receipt, 'Execution', 'The execution transaction reverted.');\n return classifyExecution(receipt, this.address, hash);\n } catch (err) {\n throw toRevertError(err, 'Execution failed');\n }\n }\n\n /** Approve and, if that meets quorum and the timelock allows, execute in one call. */\n async approveAndExecute(txHash: Bytes32): Promise<ExecuteResult> {\n const hash = normalizeTxHash(txHash);\n const caller = await this.assertCallerIsOwner('Approving and executing');\n\n const vault = this.contract(true);\n if (await vault.hasApproved(hash, caller)) {\n throw new PreconditionError('You have already approved this transaction.', {\n remediation: 'Use execute() instead.',\n });\n }\n\n try {\n const sent = await vault.approveAndExecute(hash);\n const receipt = (await sent.wait()) as ReceiptLike;\n assertReceipt(receipt, 'Approve-and-execute', 'The transaction reverted.');\n return classifyExecution(receipt, this.address, hash);\n } catch (err) {\n throw toRevertError(err, 'Approve-and-execute failed');\n }\n }\n\n /** Cancel a transaction you proposed, before it ever reaches quorum. */\n async cancel(txHash: Bytes32): Promise<{ chainTxHash: Hex }> {\n const hash = normalizeTxHash(txHash);\n const caller = await this.assertCallerIsOwner('Cancelling a transaction');\n const tx = await this.fromChain(hash);\n\n if (tx.proposer.toLowerCase() !== caller.toLowerCase()) {\n throw new PreconditionError('Only the proposer can cancel a transaction directly.', {\n remediation: 'Propose a cancelByConsensus self-call instead.',\n });\n }\n if (tx.approvedAt !== 0) {\n throw new PreconditionError(\n 'This transaction reached quorum, which permanently blocks proposer-cancel.',\n { remediation: 'Use propose.cancelByConsensus() instead.' },\n );\n }\n\n try {\n const sent = await this.contract(true).cancelTransaction(hash);\n const receipt = (await sent.wait()) as ReceiptLike;\n assertReceipt(receipt, 'Cancellation', 'The cancellation reverted.');\n return { chainTxHash: (receipt.hash ?? receipt.transactionHash ?? '') as Hex };\n } catch (err) {\n throw toRevertError(err, 'Cancellation failed');\n }\n }\n\n /** Close out an expired transaction. Permissionless — no ownership required. */\n async expire(txHash: Bytes32): Promise<{ chainTxHash: Hex }> {\n const hash = normalizeTxHash(txHash);\n try {\n const sent = await this.contract(true).expireTransaction(hash);\n const receipt = (await sent.wait()) as ReceiptLike;\n assertReceipt(receipt, 'Expiry', 'The expiry transaction reverted.');\n return { chainTxHash: (receipt.hash ?? receipt.transactionHash ?? '') as Hex };\n } catch (err) {\n throw toRevertError(err, 'Expiring the transaction failed');\n }\n }\n\n // =========================================================================\n // Preconditions\n // =========================================================================\n\n private async assertCallerIsOwner(operation: string): Promise<Address> {\n const caller = await this.ctx.connection.address();\n const isOwner = await this.contract().isOwner(caller);\n if (!isOwner) {\n throw new PreconditionError(`${operation} requires an owner. ${caller} is not one.`);\n }\n return getAddress(caller);\n }\n\n /**\n * Re-validate on chain immediately before signing an execute.\n *\n * Reads always go through the chain here, never the indexer: indexed approval\n * counts can over-report after an owner removal, and a stale count must never gate\n * a signature.\n */\n private async assertExecutable(hash: Bytes32): Promise<void> {\n const tx = await this.fromChain(hash);\n\n if (tx.status === 'executed' || tx.status === 'failed') {\n throw new PreconditionError('This transaction has already been executed.');\n }\n if (tx.status === 'cancelled') {\n throw new PreconditionError('This transaction has been cancelled.');\n }\n if (tx.status === 'expired') {\n throw new PreconditionError('This transaction has expired and can no longer execute.', {\n remediation: 'Call expire() to close it out, then propose a replacement.',\n });\n }\n if (tx.approvalCount < tx.threshold) {\n throw new PreconditionError(\n `Not enough approvals: ${tx.approvalCount} of ${tx.threshold}.`,\n );\n }\n\n // A stale prevModule can never execute — surface it now rather than on chain.\n if (tx.decoded?.name === 'disableModule' && tx.decoded.target === 'vault') {\n const module = String(tx.decoded.args.module ?? '');\n const bakedPrev = String(tx.decoded.args.prevModule ?? '');\n const modules = await this.modules();\n const index = modules.findIndex((m) => m.toLowerCase() === module.toLowerCase());\n if (index === -1) {\n throw new StaleProposalError(\n `This proposal disables module ${module}, which is no longer enabled.`,\n );\n }\n // Safe: `index === -1` already threw, and the ternary excludes 0, so index >= 1.\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const expectedPrev = index === 0 ? SENTINEL_MODULES : modules[index - 1]!;\n if (expectedPrev.toLowerCase() !== bakedPrev.toLowerCase()) {\n throw new StaleProposalError(\n `The module list changed since this proposal was created: it names ${bakedPrev} as the ` +\n `predecessor of ${module}, but the current predecessor is ${expectedPrev}.`,\n );\n }\n }\n }\n\n // =========================================================================\n // Holdings and activity\n // =========================================================================\n\n /**\n * Native and token holdings.\n *\n * Token discovery needs the indexer — the chain cannot answer \"which contracts has\n * this address touched\" without scanning every log. Amounts are verified on chain\n * by default; pass `{ verify: false }` to accept replayed transfer totals instead.\n */\n async balances(options: BalanceOptions = {}): Promise<VaultBalances> {\n return loadBalances(this.ctx.connection, this.ctx.queries, this.address, options);\n }\n\n /** Native QUAI received by the vault. Indexer-only. */\n async deposits(options: Pagination = {}) {\n return this.requireQueries('Listing deposits').deposits(this.address, options);\n }\n\n /** ERC20/721/1155 transfers involving this vault. Indexer-only. */\n async tokenTransfers(options: Pagination = {}) {\n return this.requireQueries('Listing token transfers').tokenTransfers(this.address, options);\n }\n\n /** Message hashes currently signed by the vault for EIP-1271. Indexer-only. */\n async signedMessages() {\n return this.requireQueries('Listing signed messages').signedMessages(this.address);\n }\n\n /**\n * Follow indexer changes for this vault over Supabase Realtime.\n *\n * Events fire after the indexer processes a block, so treat them as a signal to\n * re-read rather than as state themselves — re-read through this handle so approval\n * counts stay intersected with the current owner set.\n *\n * ```ts\n * const sub = vault.watch((e) => console.log(e.topic, e.type));\n * // …later\n * await sub.unsubscribe();\n * ```\n */\n watch(handler: (event: WatchEvent) => void, options: WatchOptions = {}): Subscription {\n if (!this.ctx.indexer) throw new NoIndexerError('Watching a vault');\n return watchVault(this.ctx.indexer, this.address, handler, options);\n }\n\n // =========================================================================\n // Waiting\n // =========================================================================\n\n /**\n * Block until the indexer has caught up to `blockNumber` (or to the chain head\n * when omitted), so a subsequent indexed read reflects a write you just made.\n *\n * Returns `reached: false` on timeout rather than throwing — a lagging indexer is\n * an expected operating condition, and the caller may reasonably fall back to a\n * chain read. Requires an indexer; without one there is nothing to wait for.\n */\n async waitForIndexer(\n blockNumber?: number,\n options: { timeoutMs?: number; pollIntervalMs?: number; signal?: AbortSignal } = {},\n ): Promise<{ reached: boolean; lastIndexedBlock: number }> {\n if (!this.ctx.indexer) throw new NoIndexerError('Waiting for the indexer');\n\n let target = blockNumber;\n if (target === undefined) {\n // Quai is sharded, so there is no single chain head — the head that matters is\n // the one for this vault's own zone, derived from its address prefix.\n const zone = getZoneForAddress(this.address);\n if (!zone) {\n throw new ValidationError(\n `Cannot determine the Quai zone for vault ${this.address}; pass an explicit block number.`,\n );\n }\n // Zone and Shard share their wire values but are nominally distinct types.\n target = Number(await this.ctx.connection.provider.getBlockNumber(toShard(zone)));\n }\n return this.ctx.indexer.waitForBlock(target, options);\n }\n\n /**\n * Poll until a transaction is executable, then resolve with its current state.\n *\n * Lets a caller express \"run this when it can run\" instead of reimplementing the\n * timelock arithmetic. Resolves as soon as the status reaches `ready`; rejects if\n * the transaction reaches a terminal state first, or if the deadline passes.\n *\n * Reads go through the chain so the answer is authoritative — a `ready` verdict\n * here is immediately actionable.\n */\n async waitForExecutable(\n txHash: Bytes32,\n options: {\n /** Give up after this long. Default 1 hour. */\n timeoutMs?: number;\n /** Poll interval. Default 15s, roughly three Quai blocks. */\n pollIntervalMs?: number;\n signal?: AbortSignal;\n onPoll?: (tx: VaultTransaction) => void;\n } = {},\n ): Promise<VaultTransaction> {\n const hash = normalizeTxHash(txHash);\n const timeoutMs = options.timeoutMs ?? 60 * 60 * 1000;\n const pollIntervalMs = options.pollIntervalMs ?? 15_000;\n const deadline = Date.now() + timeoutMs;\n\n for (;;) {\n if (options.signal?.aborted) {\n throw new PreconditionError('Waiting for the transaction was aborted.');\n }\n\n const tx = await this.fromChain(hash);\n options.onPoll?.(tx);\n\n if (tx.status === 'ready') return tx;\n\n if (tx.status === 'executed' || tx.status === 'failed') {\n throw new PreconditionError(`Transaction ${hash} has already been executed.`);\n }\n if (tx.status === 'cancelled' || tx.status === 'expired') {\n throw new PreconditionError(`Transaction ${hash} is ${tx.status} and can never execute.`);\n }\n\n // Below quorum there is no deadline to wait for — only more approvals help.\n if (tx.approvalCount < tx.threshold) {\n throw new PreconditionError(\n `Transaction ${hash} needs ${tx.threshold} approvals and has ${tx.approvalCount}. ` +\n 'Waiting cannot resolve this.',\n { remediation: 'Collect the remaining approvals, then wait for the timelock.' },\n );\n }\n\n // Timelocked with quorum: sleep until the clock lifts, or the next poll tick.\n const untilExecutable =\n tx.executableAfter > 0 ? tx.executableAfter * 1000 - Date.now() : pollIntervalMs;\n const wait = Math.max(1_000, Math.min(untilExecutable, pollIntervalMs));\n\n if (Date.now() + wait > deadline) {\n throw new PreconditionError(\n `Timed out after ${timeoutMs}ms waiting for ${hash} to become executable.`,\n {\n ...(tx.executableAfter > 0 ? { retryableAt: tx.executableAfter } : {}),\n remediation:\n tx.executableAfter > 0\n ? `Executable after ${new Date(tx.executableAfter * 1000).toISOString()}.`\n : 'The timelock clock has not started yet.',\n },\n );\n }\n\n await new Promise((resolve) => setTimeout(resolve, wait));\n }\n }\n\n // =========================================================================\n // Presentation\n // =========================================================================\n\n /** Compact human-readable summary of a transaction's state. */\n async describe(txHash: Bytes32, caller?: Address): Promise<string> {\n const tx = await this.transaction(txHash);\n const lines = [\n `Transaction ${tx.hash}`,\n ` ${tx.summary}`,\n ` status: ${tx.status} (${tx.approvalCount}/${tx.threshold} approvals)`,\n ];\n if (tx.value > 0n) lines.push(` value: ${formatQuai(tx.value)} QUAI`);\n if (tx.approvedAt > 0) {\n lines.push(` quorum reached: ${new Date(tx.approvedAt * 1000).toISOString()}`);\n }\n if (tx.executableAfter > 0) {\n const remaining = tx.executableAfter - nowSeconds();\n lines.push(\n ` executable after: ${new Date(tx.executableAfter * 1000).toISOString()}` +\n (remaining > 0 ? ` (in ${remaining}s)` : ' (now)'),\n );\n }\n if (tx.expiration > 0) {\n lines.push(` expires: ${new Date(tx.expiration * 1000).toISOString()}`);\n }\n if (tx.decodedRevert) lines.push(` revert: ${tx.decodedRevert.message}`);\n lines.push(` source: ${tx.source}`);\n\n if (caller || this.ctx.connection.hasSigner()) {\n const affordances = await this.affordances(txHash, caller);\n const allowed = affordances.filter((a) => a.allowed).map((a) => a.action);\n lines.push(` you can: ${allowed.length > 0 ? allowed.join(', ') : 'nothing right now'}`);\n }\n return lines.join('\\n');\n }\n}\n\n/**\n * Assert a receipt exists and did not revert.\n *\n * `wait()` resolves to null when the transaction was replaced or dropped rather than\n * mined. Without this guard the caller would get a `TypeError` from dereferencing\n * `receipt.hash` instead of an explanation of what happened.\n */\nfunction assertReceipt(\n receipt: ReceiptLike | null | undefined,\n operation: string,\n revertMessage: string,\n): asserts receipt is ReceiptLike {\n if (!receipt) {\n throw new RevertError(\n `${operation} produced no receipt — the transaction was replaced or dropped before it was mined.`,\n undefined,\n { remediation: 'Check the mempool for a replacement, then retry if it never landed.' },\n );\n }\n if (receipt.status === 0) throw new RevertError(revertMessage);\n}\n\n/**\n * Extract only the proposal options from a params bag.\n *\n * Spreading the whole bag would let a caller-facing field named `to` (the token\n * recipient) overwrite the encoded call target (the token contract) — silently\n * sending a proposal to the wrong address.\n */\nfunction proposeOptionsOf(options: ProposeOptions): ProposeOptions {\n return {\n ...(options.expiration != null ? { expiration: options.expiration } : {}),\n ...(options.executionDelay != null ? { executionDelay: options.executionDelay } : {}),\n ...(options.dryRun != null ? { dryRun: options.dryRun } : {}),\n };\n}\n\n/** Wrap a provider/contract error with decoded revert data when available. */\nfunction toRevertError(err: unknown, context: string): Error {\n if (err instanceof RevertError || err instanceof PreconditionError) return err;\n const decoded = decodeRevertFromError(err);\n const detail = decoded ? `: ${decoded.message}` : '';\n const base = err instanceof Error ? err.message : String(err);\n return new RevertError(`${context}${detail || `: ${base}`}`, decoded, { cause: err });\n}\n\nexport type { DecodedBatchCall };\n","import { getAddress } from 'quais';\nimport { assertQuaiAddress } from './address.js';\nimport type { Connection } from './chain/connection.js';\nimport { normalizeTxHash } from './chain/connection.js';\nimport { RecoveryContract, type RawRecovery } from './chain/recovery-contract.js';\nimport type { IndexerQueries } from './indexer/queries.js';\nimport { decodeRevertFromError } from './errors/decode.js';\nimport {\n NotFoundError,\n PreconditionError,\n RevertError,\n ValidationError,\n} from './errors/index.js';\nimport { deriveRecoveryStatus, nowSeconds } from './lifecycle/status.js';\nimport type { ReceiptLike } from './lifecycle/outcome.js';\nimport type {\n Address,\n Bytes32,\n Hex,\n RecoveryAffordance,\n RecoveryConfig,\n RecoveryRequest,\n} from './types.js';\n\n/** Sentinel head of the module linked list — never valid as an owner. */\nconst SENTINEL = '0x0000000000000000000000000000000000000001';\nconst ZERO = '0x0000000000000000000000000000000000000000';\n\nexport interface RecoveryModuleContext {\n connection: Connection;\n queries: IndexerQueries | null;\n vaultAddress: Address;\n moduleAddress: Address | undefined;\n}\n\n/**\n * Guardian-based recovery for one vault.\n *\n * Recovery is an escape hatch that bypasses the owner multisig entirely: enough\n * guardians can replace the owner set after a delay. Every write here is therefore\n * gated on the module still being enabled on the vault, which is the vault owners'\n * only lever once guardians are configured.\n */\nexport class RecoveryModule {\n constructor(private readonly ctx: RecoveryModuleContext) {}\n\n /** The module address, or a typed error naming the variable to set. */\n get address(): Address {\n if (!this.ctx.moduleAddress) {\n throw new ValidationError(\n 'No SocialRecoveryModule address is configured for this network.',\n 'Set QUAIVAULT_SOCIAL_RECOVERY_MODULE or pass contracts.socialRecovery.',\n );\n }\n return this.ctx.moduleAddress;\n }\n\n private contract(write = false): RecoveryContract {\n return new RecoveryContract(this.ctx.connection.socialRecovery(this.address, write), this.ctx.connection.retry);\n }\n\n private get vault(): Address {\n return this.ctx.vaultAddress;\n }\n\n // =========================================================================\n // Reads\n // =========================================================================\n\n /** Whether the module is currently enabled on the vault. */\n async isEnabled(): Promise<boolean> {\n if (!this.ctx.moduleAddress) return false;\n const vault = this.ctx.connection.vault(this.vault);\n return vault.getFunction('isModuleEnabled(address)')(this.address) as Promise<boolean>;\n }\n\n async config(): Promise<RecoveryConfig> {\n const raw = await this.contract().getRecoveryConfig(this.vault);\n const guardians = Array.from(raw.guardians ?? []).map((g) => getAddress(String(g)));\n return {\n guardians,\n threshold: Number(raw.threshold ?? 0),\n recoveryPeriod: Number(raw.recoveryPeriod ?? 0),\n configured: guardians.length > 0,\n };\n }\n\n async isGuardian(address: Address): Promise<boolean> {\n return this.contract().isGuardian(this.vault, getAddress(address));\n }\n\n /** Hashes of recoveries the module still tracks as pending. */\n async pendingHashes(): Promise<Bytes32[]> {\n return (await this.contract().getPendingRecoveryHashes(this.vault)).map((h) => String(h));\n }\n\n async hasPending(): Promise<boolean> {\n return this.contract().hasPendingRecoveries(this.vault);\n }\n\n /**\n * One recovery request, read from chain.\n *\n * Throws `NotFoundError` for a hash that was never initiated *or* was cancelled —\n * `cancelRecovery` deletes the struct, so the two are indistinguishable on chain.\n * Use {@link history} for cancelled recoveries.\n */\n async get(recoveryHash: Bytes32): Promise<RecoveryRequest> {\n const hash = normalizeTxHash(recoveryHash, 'recovery hash');\n const raw = await this.contract().getRecovery(this.vault, hash);\n\n if (Number(raw.executionTime ?? 0) === 0) {\n throw new NotFoundError(\n `No active recovery ${hash} on vault ${this.vault}. It was never initiated, or it was ` +\n 'cancelled (cancellation deletes the on-chain record).',\n );\n }\n return this.buildFromChain(hash, raw);\n }\n\n /** Every recovery the module still tracks as pending, hydrated. */\n async pending(): Promise<RecoveryRequest[]> {\n const hashes = await this.pendingHashes();\n const contract = this.contract();\n const results = await Promise.all(\n hashes.map(async (hash) => {\n const raw = await contract.getRecovery(this.vault, hash);\n if (Number(raw.executionTime ?? 0) === 0) return null;\n return this.buildFromChain(hash, raw);\n }),\n );\n return results.filter((r): r is RecoveryRequest => r !== null);\n }\n\n /**\n * Full recovery history including executed, cancelled and expired requests.\n * Indexer-only — the chain retains no record of cancelled recoveries.\n */\n async history(options: { limit?: number; offset?: number } = {}): Promise<RecoveryRequest[]> {\n const queries = this.ctx.queries;\n if (!queries) return [];\n\n const rows = await queries.recoveryHistory(this.vault, options);\n return rows.map((row) => ({\n hash: row.recovery_hash,\n vault: this.vault,\n newOwners: row.new_owners.map((o) => getAddress(o)),\n newThreshold: row.new_threshold,\n approvalCount: row.approval_count ?? 0,\n requiredThreshold: row.required_threshold,\n executionTime: Number(row.execution_time),\n expiration: Number(row.expiration ?? 0),\n // Trust the indexer only for states it alone can observe (cancelled /\n // invalidated); derive everything else, since an un-cleaned recovery stays\n // 'pending' in the database long after its deadline.\n status:\n row.status === 'cancelled' || row.status === 'invalidated'\n ? 'cancelled'\n : deriveRecoveryStatus({\n executed: row.status === 'executed',\n approvalCount: row.approval_count ?? 0,\n requiredThreshold: row.required_threshold,\n executionTime: Number(row.execution_time),\n expiration: Number(row.expiration ?? 0),\n }),\n executed: row.status === 'executed',\n initiator: getAddress(row.initiator_address),\n source: 'indexer' as const,\n }));\n }\n\n /** Guardians who have an active approval on a recovery. */\n async approvals(recoveryHash: Bytes32): Promise<Address[]> {\n const hash = normalizeTxHash(recoveryHash, 'recovery hash');\n\n // The chain has no enumeration, so probe each configured guardian.\n const { guardians } = await this.config();\n const contract = this.contract();\n const flags = await Promise.all(\n guardians.map((g) => contract.recoveryApprovals(this.vault, hash, g)),\n );\n return guardians.filter((_, i) => flags[i] === true);\n }\n\n /** Hash the next `initiate` with these parameters would produce. */\n async predictHash(newOwners: Address[], newThreshold: number): Promise<Bytes32> {\n return this.contract().predictNextRecoveryHash(\n this.vault,\n newOwners.map((o) => getAddress(o)),\n newThreshold,\n );\n }\n\n // =========================================================================\n // Writes\n // =========================================================================\n\n /**\n * Initiate a recovery. Guardians only.\n *\n * Returns the recovery hash, read from the `RecoveryInitiated` event — the function's\n * return value is not recoverable from a receipt.\n */\n async initiate(params: {\n newOwners: Address[];\n newThreshold: number;\n }): Promise<{ recoveryHash: Bytes32; chainTxHash: Hex }> {\n // A Qi or zone-less owner could never sign, so a recovery installing one would\n // hand the vault to a set that cannot act.\n const newOwners = params.newOwners.map((o, i) => assertQuaiAddress(o, `newOwners[${i}]`));\n this.validateNewOwners(newOwners, params.newThreshold);\n\n const caller = await this.ctx.connection.address();\n await this.assertEnabled('Initiating a recovery');\n\n const config = await this.config();\n if (!config.configured) {\n throw new PreconditionError('This vault has no social recovery configuration.', {\n remediation:\n 'Owners must first propose and execute setupRecovery via vault.propose.setupRecovery().',\n });\n }\n if (!(await this.isGuardian(caller))) {\n throw new PreconditionError(`${caller} is not a guardian of this vault.`);\n }\n\n const contract = this.contract(true);\n try {\n const sent = await contract.initiateRecovery(this.vault, newOwners, params.newThreshold);\n const receipt = (await sent.wait()) as ReceiptLike;\n if (!receipt || receipt.status === 0) {\n throw new RevertError('The recovery initiation reverted.');\n }\n const recoveryHash = this.extractRecoveryHash(receipt);\n if (!recoveryHash) {\n throw new RevertError(\n 'The recovery was initiated but no RecoveryInitiated event was found.',\n );\n }\n return { recoveryHash, chainTxHash: (receipt.hash ?? receipt.transactionHash ?? '') as Hex };\n } catch (err) {\n throw this.toRevert(err, 'Initiating the recovery failed');\n }\n }\n\n /** Approve a recovery. Guardians only. */\n async approve(recoveryHash: Bytes32): Promise<{ chainTxHash: Hex }> {\n const hash = normalizeTxHash(recoveryHash, 'recovery hash');\n const caller = await this.ctx.connection.address();\n await this.assertEnabled('Approving a recovery');\n\n if (!(await this.isGuardian(caller))) {\n throw new PreconditionError(`${caller} is not a guardian of this vault.`);\n }\n const request = await this.get(hash);\n this.assertLive(request);\n if (await this.contract().recoveryApprovals(this.vault, hash, caller)) {\n throw new PreconditionError('You have already approved this recovery.');\n }\n\n return this.send((c) => c.approveRecovery(this.vault, hash), 'Approving the recovery failed');\n }\n\n /** Withdraw a guardian approval before the recovery executes. */\n async revokeApproval(recoveryHash: Bytes32): Promise<{ chainTxHash: Hex }> {\n const hash = normalizeTxHash(recoveryHash, 'recovery hash');\n const caller = await this.ctx.connection.address();\n\n if (!(await this.isGuardian(caller))) {\n throw new PreconditionError(`${caller} is not a guardian of this vault.`);\n }\n if (!(await this.contract().recoveryApprovals(this.vault, hash, caller))) {\n throw new PreconditionError('You have no active approval on this recovery to revoke.');\n }\n\n return this.send(\n (c) => c.revokeRecoveryApproval(this.vault, hash),\n 'Revoking the recovery approval failed',\n );\n }\n\n /**\n * Execute a recovery, replacing the vault's owner set. Permissionless once the\n * guardian threshold is met and the recovery period has elapsed.\n */\n async execute(recoveryHash: Bytes32): Promise<{ chainTxHash: Hex }> {\n const hash = normalizeTxHash(recoveryHash, 'recovery hash');\n await this.assertEnabled('Executing a recovery');\n\n const request = await this.get(hash);\n this.assertLive(request);\n\n if (request.approvalCount < request.requiredThreshold) {\n throw new PreconditionError(\n `Not enough guardian approvals: ${request.approvalCount} of ${request.requiredThreshold}.`,\n );\n }\n const now = nowSeconds();\n if (now < request.executionTime) {\n throw new PreconditionError(\n `The recovery period has not elapsed. Executable after ` +\n `${new Date(request.executionTime * 1000).toISOString()}.`,\n { retryableAt: request.executionTime },\n );\n }\n\n // S-1: new owners are added before old ones are removed, so a fully disjoint\n // replacement can transiently exceed MAX_OWNERS and revert.\n const vault = this.ctx.connection.vault(this.vault);\n const currentOwners = (await vault.getFunction('getOwners()')()) as string[];\n const current = new Set(Array.from(currentOwners).map((o) => String(o).toLowerCase()));\n const overlap = request.newOwners.filter((o) => current.has(o.toLowerCase())).length;\n const peak = current.size + request.newOwners.length - overlap;\n if (peak > 20) {\n throw new PreconditionError(\n `Executing this recovery would transiently hold ${peak} owners, above the 20-owner maximum ` +\n '— new owners are added before old ones are removed.',\n {\n remediation:\n 'Run a recovery that retains at least one existing owner, then a second recovery to ' +\n 'replace it.',\n },\n );\n }\n\n return this.send((c) => c.executeRecovery(this.vault, hash), 'Executing the recovery failed');\n }\n\n /**\n * Cancel a recovery. Callable by any current vault owner — this is the owners'\n * defence against a hostile or mistaken guardian action.\n */\n async cancel(recoveryHash: Bytes32): Promise<{ chainTxHash: Hex }> {\n const hash = normalizeTxHash(recoveryHash, 'recovery hash');\n const caller = await this.ctx.connection.address();\n\n const vault = this.ctx.connection.vault(this.vault);\n const isOwner = (await vault.getFunction('isOwner(address)')(caller)) as boolean;\n if (!isOwner) {\n throw new PreconditionError(\n `Only a current owner of the vault can cancel a recovery. ${caller} is not one.`,\n );\n }\n\n return this.send((c) => c.cancelRecovery(this.vault, hash), 'Cancelling the recovery failed');\n }\n\n /** Clean up a recovery past its deadline. Permissionless. */\n async expire(recoveryHash: Bytes32): Promise<{ chainTxHash: Hex }> {\n const hash = normalizeTxHash(recoveryHash, 'recovery hash');\n return this.send((c) => c.expireRecovery(this.vault, hash), 'Expiring the recovery failed');\n }\n\n // =========================================================================\n // Affordances\n // =========================================================================\n\n /** What `caller` may do to a recovery right now, and when blocked actions unlock. */\n async affordances(recoveryHash: Bytes32, caller?: Address): Promise<RecoveryAffordance[]> {\n const hash = normalizeTxHash(recoveryHash, 'recovery hash');\n const who = caller ?? (await this.ctx.connection.addressOrNull());\n if (!who) {\n throw new ValidationError(\n 'affordances() needs a caller address when the client has no signer.',\n );\n }\n const address = getAddress(who);\n\n const [request, isGuardian, hasApproved, enabled, isOwner] = await Promise.all([\n this.get(hash),\n this.isGuardian(address),\n this.contract().recoveryApprovals(this.vault, hash, address),\n this.isEnabled(),\n this.ctx.connection.vault(this.vault).getFunction('isOwner(address)')(address) as Promise<boolean>,\n ]);\n\n const now = nowSeconds();\n const terminal = request.status === 'executed' || request.status === 'cancelled';\n const expired = now > request.expiration && request.expiration > 0;\n const quorum = request.approvalCount >= request.requiredThreshold;\n const out: RecoveryAffordance[] = [];\n\n const blocked = (\n action: RecoveryAffordance['action'],\n reason: string,\n blockedBy: RecoveryAffordance['blockedBy'],\n availableAt?: number,\n ): RecoveryAffordance => ({\n action,\n allowed: false,\n reason,\n blockedBy,\n ...(availableAt !== undefined ? { availableAt } : {}),\n });\n\n // --- approve\n if (terminal) out.push(blocked('approve', terminalReason(request), 'terminal_state'));\n else if (expired) out.push(blocked('approve', 'The recovery has expired.', 'expired'));\n else if (!enabled) {\n out.push(blocked('approve', 'The recovery module is not enabled on this vault.', 'module_disabled'));\n } else if (!isGuardian) {\n out.push(blocked('approve', 'Only guardians can approve a recovery.', 'not_guardian'));\n } else if (hasApproved) {\n out.push(blocked('approve', 'You have already approved this recovery.', 'already_approved'));\n } else {\n out.push({ action: 'approve', allowed: true, reason: 'You can approve this recovery.' });\n }\n\n // --- revokeApproval (no module-enabled gate on chain)\n if (terminal) out.push(blocked('revokeApproval', terminalReason(request), 'terminal_state'));\n else if (!isGuardian) {\n out.push(blocked('revokeApproval', 'Only guardians can revoke a recovery approval.', 'not_guardian'));\n } else if (!hasApproved) {\n out.push(blocked('revokeApproval', 'You have no active approval to revoke.', 'not_approved'));\n } else {\n out.push({ action: 'revokeApproval', allowed: true, reason: 'You can revoke your approval.' });\n }\n\n // --- execute (permissionless once the gates clear)\n if (terminal) out.push(blocked('execute', terminalReason(request), 'terminal_state'));\n else if (expired) out.push(blocked('execute', 'The recovery has expired.', 'expired'));\n else if (!enabled) {\n out.push(blocked('execute', 'The recovery module is not enabled on this vault.', 'module_disabled'));\n } else if (!quorum) {\n out.push(\n blocked(\n 'execute',\n `Needs ${request.requiredThreshold} guardian approvals, has ${request.approvalCount}.`,\n 'threshold',\n ),\n );\n } else if (now < request.executionTime) {\n out.push(\n blocked(\n 'execute',\n `Recovery period ends ${new Date(request.executionTime * 1000).toISOString()}.`,\n 'timelock',\n request.executionTime,\n ),\n );\n } else {\n out.push({\n action: 'execute',\n allowed: true,\n reason: 'This recovery is ready to execute and will replace the vault owner set.',\n });\n }\n\n // --- cancel (any current owner)\n if (terminal) out.push(blocked('cancel', terminalReason(request), 'terminal_state'));\n else if (!isOwner) {\n out.push(blocked('cancel', 'Only a current vault owner can cancel a recovery.', 'not_owner'));\n } else {\n out.push({\n action: 'cancel',\n allowed: true,\n reason: 'As a vault owner you can cancel this recovery.',\n });\n }\n\n // --- expire (permissionless, past the deadline)\n if (terminal) out.push(blocked('expire', terminalReason(request), 'terminal_state'));\n else if (!expired) {\n out.push(\n blocked(\n 'expire',\n `Not expired yet. Expires ${new Date(request.expiration * 1000).toISOString()}.`,\n 'not_expired',\n request.expiration + 1,\n ),\n );\n } else {\n out.push({\n action: 'expire',\n allowed: true,\n reason: 'Past its deadline — anyone can clean it up, which also unblocks setupRecovery.',\n });\n }\n\n return out;\n }\n\n // =========================================================================\n // Internals\n // =========================================================================\n\n private buildFromChain(hash: Bytes32, raw: RawRecovery): RecoveryRequest {\n const executionTime = Number(raw.executionTime ?? 0);\n const expiration = Number(raw.expiration ?? 0);\n const approvalCount = Number(raw.approvalCount ?? 0);\n const requiredThreshold = Number(raw.requiredThreshold ?? 0);\n const executed = Boolean(raw.executed);\n\n const status = deriveRecoveryStatus({\n executed,\n approvalCount,\n requiredThreshold,\n executionTime,\n expiration,\n });\n\n return {\n hash,\n vault: this.vault,\n newOwners: Array.from(raw.newOwners ?? []).map((o) => getAddress(String(o))),\n newThreshold: Number(raw.newThreshold ?? 0),\n approvalCount,\n requiredThreshold,\n executionTime,\n expiration,\n status,\n executed,\n source: 'chain',\n };\n }\n\n private validateNewOwners(newOwners: Address[], newThreshold: number): void {\n if (newOwners.length === 0) throw new ValidationError('At least one new owner is required.');\n\n const seen = new Set<string>();\n for (const owner of newOwners) {\n const key = owner.toLowerCase();\n if (key === ZERO || key === SENTINEL) {\n throw new ValidationError(\n `New owner ${owner} is reserved — the zero address and the module sentinel 0x…01 are rejected.`,\n );\n }\n if (key === this.vault.toLowerCase()) {\n throw new ValidationError('The vault cannot be an owner of itself.');\n }\n if (seen.has(key)) throw new ValidationError(`Duplicate new owner: ${owner}.`);\n seen.add(key);\n }\n if (!Number.isInteger(newThreshold) || newThreshold < 1 || newThreshold > newOwners.length) {\n throw new ValidationError(\n `Invalid new threshold ${newThreshold}: must be between 1 and ${newOwners.length}.`,\n );\n }\n }\n\n private assertLive(request: RecoveryRequest): void {\n if (request.executed) {\n throw new PreconditionError('This recovery has already been executed.');\n }\n if (request.expiration > 0 && nowSeconds() > request.expiration) {\n throw new PreconditionError('This recovery has expired.', {\n remediation: 'Call expire() to clean it up, then initiate a new recovery.',\n });\n }\n }\n\n private async assertEnabled(operation: string): Promise<void> {\n if (!(await this.isEnabled())) {\n throw new PreconditionError(\n `${operation} requires the SocialRecoveryModule to be enabled on this vault.`,\n {\n remediation:\n 'Owners must propose and execute enableModule for the recovery module first.',\n },\n );\n }\n }\n\n private async send(\n call: (contract: RecoveryContract) => Promise<{ hash: string; wait(): Promise<unknown> }>,\n context: string,\n ): Promise<{ chainTxHash: Hex }> {\n try {\n const sent = await call(this.contract(true));\n const receipt = (await sent.wait()) as ReceiptLike;\n if (!receipt || receipt.status === 0) throw new RevertError(`${context}: reverted.`);\n return { chainTxHash: (receipt.hash ?? receipt.transactionHash ?? '') as Hex };\n } catch (err) {\n throw this.toRevert(err, context);\n }\n }\n\n private extractRecoveryHash(receipt: ReceiptLike): Bytes32 | null {\n const iface = this.contract().interface;\n const target = this.address.toLowerCase();\n for (const log of receipt.logs ?? []) {\n if (log.address && log.address.toLowerCase() !== target) continue;\n try {\n const parsed = iface.parseLog({ topics: Array.from(log.topics), data: log.data });\n if (parsed?.name === 'RecoveryInitiated') {\n const index = parsed.fragment.inputs.findIndex((i) => i.name === 'recoveryHash');\n const value = index >= 0 ? parsed.args[index] : undefined;\n if (typeof value === 'string') return value;\n }\n } catch {\n continue;\n }\n }\n return null;\n }\n\n private toRevert(err: unknown, context: string): Error {\n if (err instanceof RevertError || err instanceof PreconditionError) return err;\n const decoded = decodeRevertFromError(err);\n const base = err instanceof Error ? err.message : String(err);\n return new RevertError(`${context}${decoded ? `: ${decoded.message}` : `: ${base}`}`, decoded, {\n cause: err,\n });\n }\n}\n\nfunction terminalReason(request: RecoveryRequest): string {\n if (request.executed) return 'This recovery has already been executed.';\n if (request.status === 'cancelled') return 'This recovery was cancelled.';\n return 'This recovery is in a terminal state.';\n}\n","import type { Contract } from 'quais';\nimport { withRetry, type RetryOptions } from './retry.js';\nimport type { Address, Bytes32 } from '../types.js';\nimport type { ContractTransactionResponse } from './vault-contract.js';\n\n/** Raw `RecoveryConfig` struct from `getRecoveryConfig(address)`. */\nexport interface RawRecoveryConfig {\n guardians: string[];\n threshold: bigint;\n recoveryPeriod: bigint;\n}\n\n/** Raw `Recovery` struct from `getRecovery(address,bytes32)`. */\nexport interface RawRecovery {\n newOwners: string[];\n newThreshold: bigint;\n approvalCount: bigint;\n executionTime: bigint;\n expiration: bigint;\n requiredThreshold: bigint;\n executed: boolean;\n}\n\n/**\n * Typed facade over `SocialRecoveryModule`.\n *\n * Every function is wallet-scoped: one module deployment serves every vault, so the\n * vault address is always the first argument.\n */\nexport class RecoveryContract {\n constructor(\n readonly contract: Contract,\n private readonly retry: RetryOptions = {},\n ) {}\n\n private fn(signature: string) {\n return this.contract.getFunction(signature);\n }\n\n /**\n * Reads retry transient RPC failures (see {@link withRetry}); writes never do,\n * because a resubmit that looks like a timeout may already be in the mempool.\n */\n private read<T>(signature: string, ...args: unknown[]): Promise<T> {\n return withRetry(() => this.fn(signature)(...args) as Promise<T>, this.retry);\n }\n\n get interface() {\n return this.contract.interface;\n }\n\n // ---- reads ---------------------------------------------------------------\n\n getRecoveryConfig(vault: Address): Promise<RawRecoveryConfig> {\n return this.read<RawRecoveryConfig>('getRecoveryConfig(address)', vault);\n }\n\n getRecovery(vault: Address, recoveryHash: Bytes32): Promise<RawRecovery> {\n return this.read<RawRecovery>('getRecovery(address,bytes32)', vault, recoveryHash);\n }\n\n isGuardian(vault: Address, guardian: Address): Promise<boolean> {\n return this.read<boolean>('isGuardian(address,address)', vault, guardian);\n }\n\n getPendingRecoveryHashes(vault: Address): Promise<string[]> {\n return this.read<string[]>('getPendingRecoveryHashes(address)', vault);\n }\n\n hasPendingRecoveries(vault: Address): Promise<boolean> {\n return this.read<boolean>('hasPendingRecoveries(address)', vault);\n }\n\n recoveryApprovals(vault: Address, recoveryHash: Bytes32, guardian: Address): Promise<boolean> {\n return this.read<boolean>(\n 'recoveryApprovals(address,bytes32,address)',\n vault, recoveryHash, guardian,\n );\n }\n\n recoveryNonces(vault: Address): Promise<bigint> {\n return this.read<bigint>('recoveryNonces(address)', vault);\n }\n\n maxGuardians(): Promise<bigint> {\n return this.read<bigint>('MAX_GUARDIANS()');\n }\n\n /** Hash for an explicit nonce. Use {@link predictNextRecoveryHash} for the next one. */\n getRecoveryHash(\n vault: Address,\n newOwners: Address[],\n newThreshold: number,\n nonce: bigint | number,\n ): Promise<Bytes32> {\n return this.read<Bytes32>(\n 'getRecoveryHash(address,address[],uint256,uint256)',\n vault, newOwners, newThreshold, nonce,\n );\n }\n\n /** Hash the next `initiateRecovery` would produce, at the current nonce. */\n predictNextRecoveryHash(\n vault: Address,\n newOwners: Address[],\n newThreshold: number,\n ): Promise<Bytes32> {\n return this.read<Bytes32>(\n 'predictNextRecoveryHash(address,address[],uint256)',\n vault, newOwners, newThreshold,\n );\n }\n\n // ---- writes --------------------------------------------------------------\n\n initiateRecovery(\n vault: Address,\n newOwners: Address[],\n newThreshold: number,\n ): Promise<ContractTransactionResponse> {\n return this.fn('initiateRecovery(address,address[],uint256)')(\n vault,\n newOwners,\n newThreshold,\n ) as Promise<ContractTransactionResponse>;\n }\n\n approveRecovery(vault: Address, recoveryHash: Bytes32): Promise<ContractTransactionResponse> {\n return this.fn('approveRecovery(address,bytes32)')(\n vault,\n recoveryHash,\n ) as Promise<ContractTransactionResponse>;\n }\n\n revokeRecoveryApproval(\n vault: Address,\n recoveryHash: Bytes32,\n ): Promise<ContractTransactionResponse> {\n return this.fn('revokeRecoveryApproval(address,bytes32)')(\n vault,\n recoveryHash,\n ) as Promise<ContractTransactionResponse>;\n }\n\n executeRecovery(vault: Address, recoveryHash: Bytes32): Promise<ContractTransactionResponse> {\n return this.fn('executeRecovery(address,bytes32)')(\n vault,\n recoveryHash,\n ) as Promise<ContractTransactionResponse>;\n }\n\n cancelRecovery(vault: Address, recoveryHash: Bytes32): Promise<ContractTransactionResponse> {\n return this.fn('cancelRecovery(address,bytes32)')(\n vault,\n recoveryHash,\n ) as Promise<ContractTransactionResponse>;\n }\n\n expireRecovery(vault: Address, recoveryHash: Bytes32): Promise<ContractTransactionResponse> {\n return this.fn('expireRecovery(address,bytes32)')(\n vault,\n recoveryHash,\n ) as Promise<ContractTransactionResponse>;\n }\n}\n","import type { RecoveryStatus, TransactionStatus } from '../types.js';\n\nexport interface RawTransactionState {\n executed: boolean;\n cancelled: boolean;\n /** From `expiredTxs[txHash]` — distinguishes expiry from voluntary cancellation. */\n isExpired?: boolean;\n expiration: number;\n executionDelay: number;\n approvedAt: number;\n approvalCount: number;\n threshold: number;\n /** Set when a TransactionFailed event was indexed. */\n failed?: boolean;\n}\n\nexport function nowSeconds(): number {\n return Math.floor(Date.now() / 1000);\n}\n\n/**\n * `approvedAt + executionDelay`, or 0 when the timelock clock has not started.\n *\n * `approvedAt` is written once, on the first threshold crossing, and is never\n * cleared — revoking approvals below the threshold does not reset the clock.\n */\nexport function executableAfterOf(approvedAt: number, executionDelay: number): number {\n return approvedAt > 0 ? approvedAt + executionDelay : 0;\n}\n\n/**\n * Derive the lifecycle status from raw contract state.\n *\n * `ready` and `timelocked` refine the contract's \"pending\": both mean not yet\n * executed with quorum reached, differing only on whether the delay has elapsed.\n * The contract has no such distinction — it is computed here so callers do not\n * have to reimplement the timelock arithmetic.\n */\nexport function deriveStatus(state: RawTransactionState, at: number = nowSeconds()): TransactionStatus {\n if (state.failed) return 'failed';\n if (state.executed) return 'executed';\n\n // expireTransaction sets both `cancelled` and `expiredTxs`, so check expiry first\n // to avoid reporting a timed-out transaction as voluntarily cancelled.\n if (state.cancelled) return state.isExpired ? 'expired' : 'cancelled';\n\n // Past its deadline but not yet formally closed by expireTransaction.\n if (state.expiration > 0 && at > state.expiration) return 'expired';\n\n if (state.approvalCount < state.threshold) return 'pending';\n\n const executableAfter = executableAfterOf(state.approvedAt, state.executionDelay);\n // approvedAt === 0 with quorum met means the clock has not started (e.g. the\n // threshold was lowered after approvals were collected). The first execute call\n // will start it rather than execute — treat that as timelocked, not ready.\n if (state.executionDelay > 0 && (state.approvedAt === 0 || at < executableAfter)) {\n return 'timelocked';\n }\n return 'ready';\n}\n\n/** Whether the status admits no further state transitions. */\nexport function isTerminal(status: TransactionStatus): boolean {\n return status === 'executed' || status === 'failed' || status === 'cancelled' || status === 'expired';\n}\n\nexport interface RawRecoveryState {\n executed: boolean;\n approvalCount: number;\n /** Threshold captured at initiation, not the current config. */\n requiredThreshold: number;\n executionTime: number;\n expiration: number;\n}\n\n/**\n * Derive a recovery's lifecycle status from raw module state.\n *\n * Expiry is computed from `expiration` rather than taken from a stored flag, because\n * nothing transitions a recovery to expired on its own — `expireRecovery` is a\n * permissionless cleanup call somebody has to make. The indexer only writes an\n * expired status when it sees `RecoveryExpiredEvent`, so an un-cleaned recovery reads\n * as `pending` there long after it died. Computing it here keeps the SDK honest\n * regardless of which side the data came from.\n *\n * `cancelled` is never returned: `cancelRecovery` deletes the on-chain struct, so it\n * is only observable through indexed history.\n */\nexport function deriveRecoveryStatus(\n state: RawRecoveryState,\n at: number = nowSeconds(),\n): Exclude<RecoveryStatus, 'cancelled'> {\n if (state.executed) return 'executed';\n if (state.expiration > 0 && at > state.expiration) return 'expired';\n if (state.approvalCount < state.requiredThreshold) return 'pending';\n if (at < state.executionTime) return 'timelocked';\n return 'ready';\n}\n","import { Contract, getAddress } from 'quais';\nimport { Erc1155Abi, Erc20Abi, Erc721Abi } from './abi/index.js';\nimport type { Connection } from './chain/connection.js';\nimport type { IndexerQueries } from './indexer/queries.js';\nimport type { TokenRow, TokenTransferRow } from './indexer/schemas.js';\nimport type { Address } from './types.js';\n\nexport interface TokenBalance {\n token: Address;\n standard: 'ERC20' | 'ERC721' | 'ERC1155';\n symbol: string;\n name: string;\n decimals: number;\n /** ERC20: raw units. ERC721: number held. ERC1155: total across ids. */\n balance: bigint;\n /** ERC721 / ERC1155 only. */\n tokenIds?: string[];\n /** True when the balance came from an on-chain read rather than transfer replay. */\n verified: boolean;\n /**\n * Set when more candidate ids existed than `maxTokenIdChecks` allowed, so\n * `tokenIds` is a subset. The `balance` is still the authoritative on-chain count.\n */\n tokenIdsTruncated?: boolean;\n}\n\nexport interface VaultBalances {\n native: bigint;\n tokens: TokenBalance[];\n /**\n * Set when a scan limit was hit, so the result may be incomplete. Silent\n * truncation would read as \"these are all the holdings\" when they are not.\n */\n truncated?: {\n /** More transfer history existed than `transferScanLimit` scanned. */\n transfers?: boolean;\n /** More distinct tokens were discovered than `maxTokens` allowed. */\n tokens?: boolean;\n };\n}\n\nexport interface BalanceOptions {\n /**\n * Confirm each candidate balance with an on-chain read. Slower, but authoritative —\n * a token that moved through a path the indexer does not observe still reports\n * correctly. Default true.\n */\n verify?: boolean;\n /** Cap on tokens considered, newest activity first. Default 50. */\n maxTokens?: number;\n /**\n * How many recent transfer rows to scan when discovering tokens. Default 500.\n *\n * A vault with more transfers than this may not surface its oldest holdings, so\n * raise it for long-lived vaults. Reported back in {@link VaultBalances.truncated}.\n */\n transferScanLimit?: number;\n /** Cap on ERC721 ids ownership-checked per token. Default 100. */\n maxTokenIdChecks?: number;\n}\n\n/**\n * Aggregate a vault's holdings.\n *\n * Discovery is indexer-driven: `token_transfers` tells us which contracts a vault has\n * ever touched, which the chain cannot answer without scanning every log. Amounts are\n * then read on chain by default, because replaying transfers misses anything the\n * indexer did not observe (a token discovered after the transfer, a rebasing balance,\n * a direct mint). Set `verify: false` to skip the reads and accept replayed totals.\n */\nexport async function loadBalances(\n connection: Connection,\n queries: IndexerQueries | null,\n vault: Address,\n options: BalanceOptions = {},\n): Promise<VaultBalances> {\n const verify = options.verify !== false;\n const maxTokens = options.maxTokens ?? 50;\n const transferScanLimit = options.transferScanLimit ?? 500;\n const maxTokenIdChecks = options.maxTokenIdChecks ?? 100;\n const address = getAddress(vault);\n\n const native = BigInt(await connection.provider.getBalance(address));\n if (!queries) return { native, tokens: [] };\n\n // Discover candidates from transfer history, most recent first.\n const transfers = await queries.tokenTransfers(address, { limit: transferScanLimit });\n const seen = new Map<string, TokenTransferRow[]>();\n for (const row of transfers.data) {\n const key = row.token_address.toLowerCase();\n const list = seen.get(key);\n if (list) list.push(row);\n else seen.set(key, [row]);\n }\n\n const allCandidates = Array.from(seen.keys());\n const candidates = allCandidates.slice(0, maxTokens);\n const truncated = {\n ...(transfers.hasMore ? { transfers: true } : {}),\n ...(allCandidates.length > maxTokens ? { tokens: true } : {}),\n };\n\n if (candidates.length === 0) {\n return { native, tokens: [], ...(Object.keys(truncated).length ? { truncated } : {}) };\n }\n\n const metadata = await queries.tokens(candidates);\n const byAddress = new Map(metadata.map((t) => [t.address.toLowerCase(), t]));\n\n const balances = await Promise.all(\n candidates.map((token) =>\n buildBalance(\n connection,\n address,\n token,\n byAddress.get(token),\n seen.get(token) ?? [],\n verify,\n maxTokenIdChecks,\n ),\n ),\n );\n\n return {\n native,\n // Drop dust and fully-exited positions so callers get a holdings view, not a history.\n tokens: balances.filter((b): b is TokenBalance => b !== null && b.balance > 0n),\n ...(Object.keys(truncated).length ? { truncated } : {}),\n };\n}\n\nasync function buildBalance(\n connection: Connection,\n vault: Address,\n token: string,\n meta: TokenRow | undefined,\n transfers: TokenTransferRow[],\n verify: boolean,\n maxTokenIdChecks: number,\n): Promise<TokenBalance | null> {\n const standard = meta?.standard ?? inferStandard(transfers);\n const replayed = replayBalance(transfers, standard);\n\n const base: TokenBalance = {\n token: getAddress(token),\n standard,\n symbol: meta?.symbol ?? '???',\n name: meta?.name ?? 'Unknown token',\n decimals: meta?.decimals ?? (standard === 'ERC20' ? 18 : 0),\n balance: replayed.balance,\n ...(replayed.tokenIds.length > 0 ? { tokenIds: replayed.tokenIds } : {}),\n verified: false,\n };\n\n if (!verify) return base;\n\n try {\n if (standard === 'ERC20') {\n const contract = new Contract(token, Erc20Abi as unknown as string[], connection.provider);\n const balance = (await contract.getFunction('balanceOf(address)')(vault)) as bigint;\n return { ...base, balance: BigInt(balance), verified: true };\n }\n\n if (standard === 'ERC721') {\n const contract = new Contract(token, Erc721Abi as unknown as string[], connection.provider);\n const count = (await contract.getFunction('balanceOf(address)')(vault)) as bigint;\n // ERC721 has no enumeration without the optional extension; keep the replayed\n // id list but trust the on-chain count.\n const owned = await filterOwned(contract, vault, replayed.tokenIds, maxTokenIdChecks);\n return {\n ...base,\n balance: BigInt(count),\n ...(owned.length > 0 ? { tokenIds: owned } : {}),\n ...(replayed.tokenIds.length > maxTokenIdChecks ? { tokenIdsTruncated: true } : {}),\n verified: true,\n };\n }\n\n // ERC1155: balances are per-id, so read the ids the vault has touched.\n const contract = new Contract(token, Erc1155Abi as unknown as string[], connection.provider);\n const ids = replayed.tokenIds;\n if (ids.length === 0) return { ...base, verified: true };\n\n const amounts = (await contract.getFunction('balanceOfBatch(address[],uint256[])')(\n ids.map(() => vault),\n ids,\n )) as bigint[];\n\n const held: string[] = [];\n let total = 0n;\n ids.forEach((id, i) => {\n const amount = BigInt(amounts[i] ?? 0);\n if (amount > 0n) {\n held.push(id);\n total += amount;\n }\n });\n return { ...base, balance: total, ...(held.length > 0 ? { tokenIds: held } : {}), verified: true };\n } catch {\n // Unreadable contract (self-destructed, non-standard, wrong shard): fall back to\n // the replayed figure rather than dropping the position silently.\n return base;\n }\n}\n\n/** Net inflows minus outflows, and the set of ids currently believed held. */\nfunction replayBalance(\n transfers: TokenTransferRow[],\n standard: 'ERC20' | 'ERC721' | 'ERC1155',\n): { balance: bigint; tokenIds: string[] } {\n if (standard === 'ERC20') {\n let balance = 0n;\n for (const t of transfers) {\n const value = safeBigInt(t.value);\n balance += t.direction === 'inflow' ? value : -value;\n }\n return { balance: balance > 0n ? balance : 0n, tokenIds: [] };\n }\n\n // NFTs: track per-id net position, oldest first so later transfers win.\n const perId = new Map<string, bigint>();\n const ordered = [...transfers].sort((a, b) => Number(a.block_number) - Number(b.block_number));\n for (const t of ordered) {\n const id = t.token_id ?? '0';\n const amount = standard === 'ERC721' ? 1n : safeBigInt(t.value);\n const current = perId.get(id) ?? 0n;\n perId.set(id, current + (t.direction === 'inflow' ? amount : -amount));\n }\n\n const tokenIds: string[] = [];\n let balance = 0n;\n for (const [id, amount] of perId) {\n if (amount > 0n) {\n tokenIds.push(id);\n balance += amount;\n }\n }\n return { balance, tokenIds };\n}\n\n/** Confirm current ownership of candidate ERC721 ids. */\nasync function filterOwned(\n contract: Contract,\n vault: Address,\n ids: string[],\n limit: number,\n): Promise<string[]> {\n if (ids.length === 0) return [];\n const results = await Promise.all(\n ids.slice(0, limit).map(async (id) => {\n try {\n const owner = (await contract.getFunction('ownerOf(uint256)')(id)) as string;\n return owner.toLowerCase() === vault.toLowerCase() ? id : null;\n } catch {\n return null; // burned or non-existent\n }\n }),\n );\n return results.filter((id): id is string => id !== null);\n}\n\nfunction inferStandard(transfers: TokenTransferRow[]): 'ERC20' | 'ERC721' | 'ERC1155' {\n const withId = transfers.find((t) => t.token_id != null);\n if (!withId) return 'ERC20';\n // ERC1155 fans batches out with a batch_index; ERC721 never does.\n return transfers.some((t) => (t.batch_index ?? 0) > 0) ? 'ERC1155' : 'ERC721';\n}\n\nfunction safeBigInt(value: string): bigint {\n try {\n return BigInt(value);\n } catch {\n return 0n;\n }\n}\n","import type { RealtimeChannel } from '@supabase/supabase-js';\nimport { isAddress } from 'quais';\nimport type { IndexerClient } from './client.js';\nimport { ValidationError } from '../errors/index.js';\nimport type { Address } from '../types.js';\n\n/** Indexer tables a vault subscription can follow. */\nexport type WatchTopic =\n | 'transactions'\n | 'confirmations'\n | 'owners'\n | 'modules'\n | 'deposits'\n | 'tokenTransfers'\n | 'recoveries'\n | 'signedMessages';\n\nconst TABLE_FOR: Record<WatchTopic, string> = {\n transactions: 'transactions',\n confirmations: 'confirmations',\n owners: 'wallet_owners',\n modules: 'wallet_modules',\n deposits: 'deposits',\n tokenTransfers: 'token_transfers',\n recoveries: 'social_recoveries',\n signedMessages: 'signed_messages',\n};\n\nexport interface WatchEvent {\n topic: WatchTopic;\n table: string;\n /** Postgres operation that produced the event. */\n type: 'INSERT' | 'UPDATE' | 'DELETE';\n /** Row after the change. Absent for DELETE. */\n row: Record<string, unknown> | null;\n /** Row before the change, when the table's replica identity provides it. */\n previous: Record<string, unknown> | null;\n}\n\nexport interface WatchOptions {\n topics?: WatchTopic[];\n /** Called on subscription lifecycle changes, so callers can surface reconnects. */\n onStatus?: (status: string, error?: Error) => void;\n}\n\n/** Handle returned by {@link watchVault}. Call `unsubscribe` to release the channel. */\nexport interface Subscription {\n unsubscribe(): Promise<void>;\n readonly topics: WatchTopic[];\n}\n\nconst DEFAULT_TOPICS: WatchTopic[] = ['transactions', 'confirmations', 'owners'];\n\n/**\n * Follow indexer changes for one vault over Supabase Realtime.\n *\n * All topics share a single channel — one WebSocket per vault rather than one per\n * table, which matters because Realtime caps concurrent channels per client.\n *\n * Realtime delivers *indexer* writes, so events arrive only after the indexer has\n * processed the block. It is a change feed, not a chain subscription: use it to know\n * when to re-read, and re-read through `Vault` so approval counts stay correct.\n */\nexport function watchVault(\n client: IndexerClient,\n vault: Address,\n handler: (event: WatchEvent) => void,\n options: WatchOptions = {},\n): Subscription {\n // The address is interpolated into a PostgREST filter string, so validate it here\n // rather than trusting the caller — this function is exported, not just reached\n // through `Vault.watch()` where the address is already checked.\n if (!isAddress(vault)) {\n throw new ValidationError(`Invalid vault address for subscription: \"${vault}\".`);\n }\n const topics = options.topics ?? DEFAULT_TOPICS;\n const address = vault.toLowerCase();\n const schema = client.config.schema;\n\n // Channel names must be unique per client; include the vault so two handles on\n // different vaults do not collide.\n const channel: RealtimeChannel = client.raw.channel(`quaivault:${schema}:${address}`);\n\n for (const topic of topics) {\n const table = TABLE_FOR[topic];\n channel.on(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n 'postgres_changes' as any,\n {\n event: '*',\n schema,\n table,\n // Every watched table keys the vault on wallet_address.\n filter: `wallet_address=eq.${address}`,\n },\n (payload: {\n eventType: 'INSERT' | 'UPDATE' | 'DELETE';\n new: Record<string, unknown> | null;\n old: Record<string, unknown> | null;\n }) => {\n handler({\n topic,\n table,\n type: payload.eventType,\n row: payload.new && Object.keys(payload.new).length > 0 ? payload.new : null,\n previous: payload.old && Object.keys(payload.old).length > 0 ? payload.old : null,\n });\n },\n );\n }\n\n channel.subscribe((status, err) => {\n options.onStatus?.(status, err instanceof Error ? err : undefined);\n });\n\n return {\n topics,\n async unsubscribe() {\n await client.raw.removeChannel(channel);\n },\n };\n}\n","import { formatQuai, getBytes } from 'quais';\nimport { interfaces } from '../encode/index.js';\nimport type { Address, DecodedCall, Hex, TransactionKind } from '../types.js';\n\nexport interface DecodeContext {\n /** The vault the transaction belongs to — used to detect self-calls. */\n vault: Address;\n to: Address;\n value: bigint;\n data: Hex;\n /** Known module addresses, for classifying `module_config` calls. */\n socialRecovery?: Address;\n multiSendCallOnly?: Address;\n}\n\nexport interface DecodeResult {\n kind: TransactionKind;\n decoded?: DecodedCall;\n summary: string;\n}\n\nconst SELF_CALL_ADMIN = new Set([\n 'addOwner',\n 'removeOwner',\n 'changeThreshold',\n 'enableModule',\n 'disableModule',\n 'cancelByConsensus',\n 'setMinExecutionDelay',\n 'addDelegatecallTarget',\n 'removeDelegatecallTarget',\n]);\n\nconst MESSAGE_SIGNING = new Set(['signMessage', 'unsignMessage']);\n\nfunction short(address: string): string {\n return address.length > 12 ? `${address.slice(0, 6)}…${address.slice(-4)}` : address;\n}\n\nfunction formatDuration(seconds: number): string {\n if (seconds === 0) return 'none';\n const units: Array<[number, string]> = [\n [86400, 'day'],\n [3600, 'hour'],\n [60, 'minute'],\n ];\n for (const [size, label] of units) {\n if (seconds >= size) {\n const n = Math.floor(seconds / size);\n return `${n} ${label}${n === 1 ? '' : 's'}`;\n }\n }\n return `${seconds} seconds`;\n}\n\nfunction namedArgs(fragmentInputs: ReadonlyArray<{ name: string }>, args: readonly unknown[]) {\n const out: Record<string, unknown> = {};\n fragmentInputs.forEach((input, i) => {\n out[input.name || `arg${i}`] = args[i];\n });\n return out;\n}\n\n/**\n * Classify and describe a proposed vault transaction from its calldata.\n *\n * Resolution order matters: self-calls are checked against the vault ABI first,\n * because several vault selectors would otherwise be ambiguous with token calls.\n */\nexport function decodeCall(ctx: DecodeContext): DecodeResult {\n const { vault, to, value, data } = ctx;\n const isSelfCall = to.toLowerCase() === vault.toLowerCase();\n const hasData = typeof data === 'string' && data !== '0x' && data.length > 2;\n\n if (!hasData) {\n return {\n kind: 'transfer',\n summary: `Transfer ${formatQuai(value)} QUAI to ${short(to)}`,\n };\n }\n\n // --- vault self-calls\n if (isSelfCall) {\n const parsed = tryParse(interfaces.vault, data);\n if (parsed) {\n const decoded: DecodedCall = {\n name: parsed.name,\n signature: parsed.signature,\n args: parsed.args,\n target: 'vault',\n };\n if (MESSAGE_SIGNING.has(parsed.name)) {\n return {\n kind: 'message_signing',\n decoded,\n summary:\n parsed.name === 'signMessage'\n ? 'Sign a message on behalf of the vault (EIP-1271)'\n : 'Revoke a previously signed message (EIP-1271)',\n };\n }\n if (SELF_CALL_ADMIN.has(parsed.name)) {\n return { kind: 'wallet_admin', decoded, summary: describeAdmin(parsed.name, parsed.args) };\n }\n return { kind: 'wallet_admin', decoded, summary: `Vault self-call: ${parsed.name}` };\n }\n }\n\n // --- social recovery module\n if (ctx.socialRecovery && to.toLowerCase() === ctx.socialRecovery.toLowerCase()) {\n const parsed = tryParse(interfaces.recovery, data);\n if (parsed) {\n const decoded: DecodedCall = { ...parsed, target: 'socialRecovery' };\n if (parsed.name === 'setupRecovery') {\n const guardians = parsed.args.guardians as unknown[] | undefined;\n const threshold = parsed.args.threshold;\n return {\n kind: 'recovery_setup',\n decoded,\n summary: `Configure social recovery: ${guardians?.length ?? '?'} guardians, ${String(\n threshold ?? '?',\n )} required`,\n };\n }\n return { kind: 'module_config', decoded, summary: `Social recovery: ${parsed.name}` };\n }\n }\n\n // --- MultiSend batch\n if (ctx.multiSendCallOnly && to.toLowerCase() === ctx.multiSendCallOnly.toLowerCase()) {\n const parsed = tryParse(interfaces.multiSend, data);\n if (parsed?.name === 'multiSend') {\n const inner = decodeMultiSendPayload(parsed.args.transactions as Hex);\n return {\n kind: 'batched_call',\n decoded: { ...parsed, target: 'multiSend' },\n summary: `Batched call: ${inner.length} sub-transaction${inner.length === 1 ? '' : 's'}`,\n };\n }\n }\n\n // --- module execution via Zodiac\n const asVault = tryParse(interfaces.vault, data);\n if (asVault?.name.startsWith('execTransactionFromModule')) {\n return {\n kind: 'module_execution',\n decoded: { ...asVault, target: 'vault' },\n summary: `Module execution against ${short(String(asVault.args.to ?? to))}`,\n };\n }\n\n // --- token standards\n const erc20 = tryParse(interfaces.erc20, data);\n if (erc20 && ['transfer', 'approve', 'transferFrom'].includes(erc20.name)) {\n return {\n kind: 'erc20_transfer',\n decoded: { ...erc20, target: 'erc20' },\n summary: describeErc20(erc20.name, erc20.args, to),\n };\n }\n\n const erc1155 = tryParse(interfaces.erc1155, data);\n if (erc1155 && erc1155.name.startsWith('safe')) {\n return {\n kind: 'erc1155_transfer',\n decoded: { ...erc1155, target: 'erc1155' },\n summary:\n erc1155.name === 'safeBatchTransferFrom'\n ? `Transfer a batch of ERC1155 tokens from ${short(to)}`\n : `Transfer ERC1155 token #${String(erc1155.args.id ?? '?')} from ${short(to)}`,\n };\n }\n\n const erc721 = tryParse(interfaces.erc721, data);\n if (erc721 && erc721.name === 'safeTransferFrom') {\n return {\n kind: 'erc721_transfer',\n decoded: { ...erc721, target: 'erc721' },\n summary: `Transfer NFT #${String(erc721.args.tokenId ?? '?')} to ${short(\n String(erc721.args.to ?? '?'),\n )}`,\n };\n }\n\n const selector = data.slice(0, 10);\n return {\n kind: 'external_call',\n summary:\n `Call ${short(to)} (selector ${selector})` +\n (value > 0n ? ` with ${formatQuai(value)} QUAI` : ''),\n };\n}\n\nfunction tryParse(\n iface: (typeof interfaces)[keyof typeof interfaces],\n data: Hex,\n): { name: string; signature: string; args: Record<string, unknown> } | null {\n try {\n const parsed = iface.parseTransaction({ data });\n if (!parsed) return null;\n return {\n name: parsed.name,\n signature: parsed.fragment.format('sighash'),\n args: namedArgs(parsed.fragment.inputs, parsed.args),\n };\n } catch {\n return null;\n }\n}\n\nfunction describeAdmin(name: string, args: Record<string, unknown>): string {\n switch (name) {\n case 'addOwner':\n return `Add owner ${short(String(args.owner))}`;\n case 'removeOwner':\n return `Remove owner ${short(String(args.owner))}`;\n case 'changeThreshold':\n return `Change approval threshold to ${String(args._threshold ?? args.threshold)}`;\n case 'enableModule':\n return `Enable module ${short(String(args.module))}`;\n case 'disableModule':\n return `Disable module ${short(String(args.module))}`;\n case 'setMinExecutionDelay':\n return `Set minimum execution delay to ${formatDuration(Number(args.delay ?? 0))}`;\n case 'addDelegatecallTarget':\n return `Whitelist ${short(String(args.target))} as a DelegateCall target`;\n case 'removeDelegatecallTarget':\n return `Remove ${short(String(args.target))} from the DelegateCall whitelist`;\n case 'cancelByConsensus':\n return `Cancel transaction ${short(String(args.txHash))} by consensus`;\n default:\n return `Vault admin: ${name}`;\n }\n}\n\nfunction describeErc20(name: string, args: Record<string, unknown>, tokenAddress: string): string {\n switch (name) {\n case 'transfer':\n return `Transfer ${String(args.amount)} units of token ${short(tokenAddress)} to ${short(\n String(args.to),\n )}`;\n case 'approve':\n return `Approve ${short(String(args.spender))} to spend ${String(args.amount)} units of ${short(\n tokenAddress,\n )}`;\n default:\n return `ERC20 ${name} on ${short(tokenAddress)}`;\n }\n}\n\nexport interface DecodedBatchCall {\n operation: number;\n to: Address;\n value: bigint;\n data: Hex;\n}\n\n/**\n * Unpack a MultiSend payload into its constituent calls.\n * Layout per call: `operation(1) ‖ to(20) ‖ value(32) ‖ dataLength(32) ‖ data`.\n */\nexport function decodeMultiSendPayload(payload: Hex): DecodedBatchCall[] {\n const bytes = getBytes(payload);\n const out: DecodedBatchCall[] = [];\n let offset = 0;\n\n while (offset < bytes.length) {\n // 1 + 20 + 32 + 32 = 85 bytes of fixed header\n if (offset + 85 > bytes.length) break;\n\n // Safe: the `offset + 85 > bytes.length` guard above proves this index is in range.\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const operation = bytes[offset]!;\n offset += 1;\n\n const to = hexOf(bytes.subarray(offset, offset + 20));\n offset += 20;\n\n const value = BigInt(hexOf(bytes.subarray(offset, offset + 32)));\n offset += 32;\n\n const length = Number(BigInt(hexOf(bytes.subarray(offset, offset + 32))));\n offset += 32;\n\n if (offset + length > bytes.length) break;\n const data = hexOf(bytes.subarray(offset, offset + length));\n offset += length;\n\n out.push({ operation, to, value, data });\n }\n\n return out;\n}\n\nfunction hexOf(bytes: Uint8Array): string {\n let s = '0x';\n for (const b of bytes) s += b.toString(16).padStart(2, '0');\n return s;\n}\n","import type { Address, Affordance, VaultTransaction } from '../types.js';\nimport { executableAfterOf, isTerminal, nowSeconds } from './status.js';\n\nexport interface AffordanceContext {\n tx: VaultTransaction;\n caller: Address;\n isOwner: boolean;\n /** Whether `caller` currently has a threshold-counting approval. */\n hasApproved: boolean;\n at?: number;\n}\n\nfunction terminalReason(tx: VaultTransaction): string {\n switch (tx.status) {\n case 'executed':\n return 'The transaction has already been executed.';\n case 'failed':\n return 'The transaction executed but its target call reverted. This state is terminal.';\n case 'cancelled':\n return 'The transaction has been cancelled.';\n case 'expired':\n return 'The transaction passed its expiration timestamp.';\n default:\n return 'The transaction is in a terminal state.';\n }\n}\n\n/**\n * Enumerate which actions `caller` may legally take on `tx` right now, and when a\n * blocked action becomes available.\n *\n * Every rule here mirrors an on-chain check, so callers can plan instead of\n * discovering constraints through reverted transactions:\n *\n * - `onlyOwner` on approve / revoke / execute / cancel\n * - epoch-based approvals (`_approvalValid`) for already-approved / not-approved\n * - `approvedAt != 0` permanently locking proposer-cancel, even after revocations\n * - the timelock on external calls (self-calls bypass it)\n * - expiration, and the permissionless `expireTransaction` cleanup path\n */\nexport function computeAffordances(ctx: AffordanceContext): Affordance[] {\n const { tx, isOwner, hasApproved } = ctx;\n const at = ctx.at ?? nowSeconds();\n const terminal = isTerminal(tx.status);\n const quorum = tx.approvalCount >= tx.threshold;\n const isSelfCall = tx.to.toLowerCase() === tx.vault.toLowerCase();\n const executableAfter = executableAfterOf(tx.approvedAt, tx.executionDelay);\n // Self-calls always execute immediately; the contract stores executionDelay 0 for\n // them, but guard here too so a malformed record cannot produce a wrong answer.\n const timelockActive =\n !isSelfCall && tx.executionDelay > 0 && (tx.approvedAt === 0 || at < executableAfter);\n const isProposer = tx.proposer.toLowerCase() === ctx.caller.toLowerCase();\n\n const out: Affordance[] = [];\n\n const notOwner = (action: Affordance['action']): Affordance => ({\n action,\n allowed: false,\n reason: 'Only owners of this vault may take this action.',\n blockedBy: 'not_owner',\n });\n const isTerminalBlocked = (action: Affordance['action']): Affordance => ({\n action,\n allowed: false,\n reason: terminalReason(tx),\n blockedBy: 'terminal_state',\n });\n\n // --- approve\n if (terminal) out.push(isTerminalBlocked('approve'));\n else if (!isOwner) out.push(notOwner('approve'));\n else if (hasApproved) {\n out.push({\n action: 'approve',\n allowed: false,\n reason: 'You have already approved this transaction.',\n blockedBy: 'already_approved',\n });\n } else {\n out.push({ action: 'approve', allowed: true, reason: 'You can approve this transaction.' });\n }\n\n // --- revokeApproval\n if (terminal) out.push(isTerminalBlocked('revokeApproval'));\n else if (!isOwner) out.push(notOwner('revokeApproval'));\n else if (!hasApproved) {\n out.push({\n action: 'revokeApproval',\n allowed: false,\n reason: 'You have no active approval on this transaction to revoke.',\n blockedBy: 'not_approved',\n });\n } else {\n out.push({\n action: 'revokeApproval',\n allowed: true,\n reason:\n tx.approvedAt > 0\n ? 'You can revoke your approval. Note that quorum was already reached, so the ' +\n 'timelock clock keeps running and the proposer still cannot cancel.'\n : 'You can revoke your approval.',\n });\n }\n\n // --- execute\n if (terminal) out.push(isTerminalBlocked('execute'));\n else if (!isOwner) out.push(notOwner('execute'));\n else if (!quorum) {\n out.push({\n action: 'execute',\n allowed: false,\n reason: `Needs ${tx.threshold} approvals, has ${tx.approvalCount}.`,\n blockedBy: 'threshold',\n });\n } else if (timelockActive) {\n out.push({\n action: 'execute',\n allowed: false,\n reason:\n tx.approvedAt === 0\n ? 'Quorum is met but the timelock clock has not started. The next execute call will ' +\n `start it and return without executing; you must call execute again ${tx.executionDelay}s later.`\n : `Timelocked until ${new Date(executableAfter * 1000).toISOString()}.`,\n blockedBy: 'timelock',\n ...(tx.approvedAt > 0 ? { availableAt: executableAfter } : {}),\n });\n } else {\n out.push({ action: 'execute', allowed: true, reason: 'This transaction is ready to execute.' });\n }\n\n // --- approveAndExecute: approve and, if that meets quorum and the timelock allows, execute\n if (terminal) out.push(isTerminalBlocked('approveAndExecute'));\n else if (!isOwner) out.push(notOwner('approveAndExecute'));\n else if (hasApproved) {\n out.push({\n action: 'approveAndExecute',\n allowed: false,\n reason: 'You have already approved. Use execute instead.',\n blockedBy: 'already_approved',\n });\n } else {\n const wouldReachQuorum = tx.approvalCount + 1 >= tx.threshold;\n out.push({\n action: 'approveAndExecute',\n allowed: true,\n reason: !wouldReachQuorum\n ? `Your approval will be recorded, but execution needs ${tx.threshold} approvals ` +\n `(would be ${tx.approvalCount + 1}). The call returns without executing.`\n : timelockActive\n ? 'Your approval will be recorded and will start the timelock, but the call returns ' +\n 'without executing. Execute again after the delay elapses.'\n : 'Your approval meets the threshold and the transaction will execute in the same call.',\n });\n }\n\n // --- cancel (proposer-only, and permanently locked once quorum is ever reached)\n if (terminal) out.push(isTerminalBlocked('cancel'));\n else if (!isOwner) out.push(notOwner('cancel'));\n else if (!isProposer) {\n out.push({\n action: 'cancel',\n allowed: false,\n reason: 'Only the proposer can cancel directly. Others need a cancelByConsensus proposal.',\n blockedBy: 'not_proposer',\n });\n } else if (tx.approvedAt !== 0) {\n out.push({\n action: 'cancel',\n allowed: false,\n reason:\n 'This transaction reached quorum, which permanently blocks proposer-cancel — even though ' +\n 'approvals may since have been revoked. Use a cancelByConsensus proposal instead.',\n blockedBy: 'quorum_locked',\n });\n } else {\n out.push({ action: 'cancel', allowed: true, reason: 'You proposed this and can cancel it.' });\n }\n\n // --- expire (permissionless once past the deadline)\n if (tx.status === 'executed' || tx.status === 'failed' || tx.status === 'cancelled') {\n out.push(isTerminalBlocked('expire'));\n } else if (tx.expiration === 0) {\n out.push({\n action: 'expire',\n allowed: false,\n reason: 'This transaction has no expiration and can never be expired.',\n blockedBy: 'no_expiration',\n });\n } else if (at <= tx.expiration) {\n out.push({\n action: 'expire',\n allowed: false,\n reason: `Not expired yet. Expires at ${new Date(tx.expiration * 1000).toISOString()}.`,\n blockedBy: 'expired',\n availableAt: tx.expiration + 1,\n });\n } else {\n out.push({\n action: 'expire',\n allowed: true,\n reason: 'Past its expiration — anyone may close it out and reclaim approval storage.',\n });\n }\n\n // --- proposeCancelByConsensus: the post-quorum cancellation path\n if (terminal) out.push(isTerminalBlocked('proposeCancelByConsensus'));\n else if (!isOwner) out.push(notOwner('proposeCancelByConsensus'));\n else {\n out.push({\n action: 'proposeCancelByConsensus',\n allowed: true,\n reason:\n 'You can propose a cancelByConsensus self-call. It needs the same threshold as executing ' +\n 'the original transaction, but self-calls bypass the timelock, so it always resolves faster.',\n });\n }\n\n return out;\n}\n\n/** The subset of actions currently allowed. */\nexport function allowedActions(affordances: Affordance[]): Affordance[] {\n return affordances.filter((a) => a.allowed);\n}\n","import { Interface } from 'quais';\nimport { QuaiVaultAbi } from '../abi/index.js';\nimport { decodeRevert } from '../errors/decode.js';\nimport type { Bytes32, ExecuteResult, Hex } from '../types.js';\n\nconst vaultInterface = new Interface(QuaiVaultAbi);\n\nexport interface ReceiptLike {\n hash?: string;\n transactionHash?: string;\n blockNumber?: number | bigint | null;\n gasUsed?: bigint | number | null;\n status?: number | null;\n logs: ReadonlyArray<{ topics: ReadonlyArray<string>; data: string; address?: string }>;\n}\n\ninterface ParsedEvent {\n name: string;\n args: Record<string, unknown>;\n}\n\n/** Parse only the logs emitted by the vault itself; ignore everything else. */\nfunction parseVaultEvents(receipt: ReceiptLike, vault: string): ParsedEvent[] {\n const out: ParsedEvent[] = [];\n const target = vault.toLowerCase();\n\n for (const log of receipt.logs ?? []) {\n if (log.address && log.address.toLowerCase() !== target) continue;\n try {\n const parsed = vaultInterface.parseLog({\n topics: Array.from(log.topics),\n data: log.data,\n });\n if (!parsed) continue;\n const args: Record<string, unknown> = {};\n parsed.fragment.inputs.forEach((input, i) => {\n if (input.name) args[input.name] = parsed.args[i];\n });\n out.push({ name: parsed.name, args });\n } catch {\n // Not a vault event (token transfers from the executed call, etc.)\n }\n }\n return out;\n}\n\nfunction eventFor(events: ParsedEvent[], name: string, txHash: Bytes32): ParsedEvent | undefined {\n const wanted = txHash.toLowerCase();\n return events.find(\n (e) => e.name === name && String(e.args.txHash ?? '').toLowerCase() === wanted,\n );\n}\n\nfunction toNumber(value: unknown): number {\n if (typeof value === 'bigint') return Number(value);\n if (typeof value === 'number') return value;\n return Number(value ?? 0);\n}\n\n/**\n * Classify what actually happened to a vault transaction, from the receipt of the\n * Quai transaction that carried `execute` / `approveAndExecute`.\n *\n * This exists because `receipt.status === 1` does NOT mean the vault transaction ran.\n * Three cases produce a successful receipt with no execution:\n *\n * 1. **Lazy timelock clock** — `executeTransaction` on a timelocked transaction whose\n * `approvedAt` was never set (e.g. the threshold was lowered after owners approved)\n * sets `approvedAt`, emits `ThresholdReached`, and returns without executing. It\n * deliberately does not revert, because a revert would roll back the clock start.\n * 2. **`approveAndExecute` returned false** — the threshold is unmet, or the timelock\n * has not elapsed. A boolean return value is invisible in a receipt.\n * 3. **External call failure (Option B)** — the vault marks the transaction `executed`\n * permanently and emits `TransactionFailed` instead of reverting. The vault\n * transaction is dead; the receipt says success.\n */\nexport function classifyExecution(\n receipt: ReceiptLike,\n vault: string,\n txHash: Bytes32,\n): ExecuteResult {\n const chainTxHash = (receipt.hash ?? receipt.transactionHash ?? '') as Hex;\n const base = {\n txHash,\n chainTxHash,\n blockNumber: toNumber(receipt.blockNumber),\n gasUsed: BigInt(receipt.gasUsed ?? 0),\n };\n\n const events = parseVaultEvents(receipt, vault);\n\n const executed = eventFor(events, 'TransactionExecuted', txHash);\n if (executed) {\n return {\n ...base,\n outcome: 'executed',\n message: 'Transaction executed successfully.',\n };\n }\n\n const failed = eventFor(events, 'TransactionFailed', txHash);\n if (failed) {\n const returnData = String(failed.args.returnData ?? '0x') as Hex;\n const decodedRevert = decodeRevert(returnData);\n return {\n ...base,\n outcome: 'failed',\n returnData,\n decodedRevert,\n message:\n `The vault executed the transaction but the target call reverted` +\n (decodedRevert ? `: ${decodedRevert.message}` : '.') +\n ' This state is terminal — the transaction is permanently marked executed and cannot be retried.' +\n ' Propose a new transaction to try again.',\n };\n }\n\n // Threshold was reached during this call but nothing executed → the lazy clock\n // started. The caller must come back after the delay.\n const thresholdReached = eventFor(events, 'ThresholdReached', txHash);\n if (thresholdReached) {\n const executableAfter = toNumber(thresholdReached.args.executableAfter);\n // A zero delay reaching threshold without executing means approveAndExecute\n // recorded the final approval but the caller used the approve-only path.\n if (executableAfter > Math.floor(Date.now() / 1000)) {\n return {\n ...base,\n outcome: 'timelock_started',\n executableAfter,\n message:\n `Quorum was reached and the execution delay started. Nothing has executed yet. ` +\n `Call execute again after ${new Date(executableAfter * 1000).toISOString()}.`,\n };\n }\n return {\n ...base,\n outcome: 'approved_only',\n executableAfter,\n message:\n 'Quorum was reached but the transaction did not execute in this call. Call execute again.',\n };\n }\n\n const approved = eventFor(events, 'TransactionApproved', txHash);\n return {\n ...base,\n outcome: 'approved_only',\n message: approved\n ? 'Your approval was recorded, but the transaction did not execute — the threshold is not yet met.'\n : 'The transaction did not execute. It may be timelocked, or already approved by this owner ' +\n 'without the threshold being met.',\n };\n}\n\n/**\n * Pull the vault-transaction hash out of a `proposeTransaction` receipt.\n * The `TransactionProposed` event is the only reliable source — `proposeTransaction`\n * returns the hash, but return values are not available from a receipt.\n */\nexport function extractProposedTxHash(receipt: ReceiptLike, vault: string): Bytes32 | null {\n const events = parseVaultEvents(receipt, vault);\n const proposed = events.find((e) => e.name === 'TransactionProposed');\n const hash = proposed?.args.txHash;\n return typeof hash === 'string' ? hash : null;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA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A,QAAQ,OAAOA,aAAuC;AACpD,aAAO,KAAK,QAAQ,iBAAa,2BAAWA,QAAO,CAAC;AAAA,IACtD;AAAA,IAEA,KAAK,CAACA,aAA4B,KAAK,MAAMA,QAAO;AAAA,EACtD;AAAA,EAEQ,eAAe,WAAmC;AACxD,QAAI,CAAC,KAAK,QAAS,OAAM,IAAI,eAAe,SAAS;AACrD,WAAO,KAAK;AAAA,EACd;AAAA;AAAA,EAGA,MAAM,gBAAwC;AAC5C,QAAI,CAAC,KAAK,SAAS;AACjB,aAAO;AAAA,QACL,WAAW;AAAA,QACX,kBAAkB;AAAA,QAClB,WAAW;AAAA,QACX,OAAO;AAAA,MACT;AAAA,IACF;AACA,WAAO,KAAK,QAAQ,OAAO;AAAA,EAC7B;AACF;AAiBO,SAAS,QAAQ,UAAyB,CAAC,GAAoB;AACpE,SAAO,IAAI,gBAAgB,OAAO;AACpC;AAGO,IAAM,YAAY,EAAE,QAAQ;","names":["import_quais","address","import_quais","import_quais","import_quais","address","module","import_quais","import_quais","Operation","module","import_quais","import_quais","address","address","vault","address","address","vault","import_quais","import_quais","vault","vault","address","import_quais","vault","address","token","contract","balance","import_quais","vault","address","import_quais","address","vault","erc20","erc1155","erc721","terminalReason","import_quais","vaultInterface","vault","toNumber","address","vault","module","multiSend","address"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/client.ts","../src/chain/connection.ts","../src/abi/QuaiVault.json","../src/abi/QuaiVaultFactory.json","../src/abi/QuaiVaultProxy.json","../src/abi/SocialRecoveryModule.json","../src/abi/MultiSendCallOnly.json","../src/abi/index.ts","../src/errors/index.ts","../src/config/resolve.ts","../src/config/networks.ts","../src/factory.ts","../src/address.ts","../src/chain/retry.ts","../src/chain/vault-contract.ts","../src/errors/decode.ts","../src/text.ts","../src/encode/index.ts","../src/types.ts","../src/salt/mine.ts","../src/salt/predict.ts","../src/indexer/client.ts","../src/indexer/schemas.ts","../src/indexer/queries.ts","../src/vault.ts","../src/recovery.ts","../src/chain/recovery-contract.ts","../src/lifecycle/status.ts","../src/balances.ts","../src/chain/token-contract.ts","../src/pool.ts","../src/indexer/watch.ts","../src/decode/index.ts","../src/lifecycle/affordances.ts","../src/lifecycle/outcome.ts"],"sourcesContent":["/**\n * @quaivault/sdk — TypeScript SDK for QuaiVault multisig vaults on Quai Network.\n *\n * ```ts\n * import { connect } from '@quaivault/sdk';\n *\n * const qv = connect({ network: 'mainnet' });\n * const vault = qv.vault('0x00…');\n * console.log(await vault.info());\n * ```\n */\n\n// --- client\nexport { QuaiVault, QuaiVaultClient, connect } from './client.js';\nexport { Vault, type VaultContext, type VaultView } from './vault.js';\nexport { mapPooled, DEFAULT_CONCURRENCY } from './pool.js';\nexport { Factory, type CreateProgress, type FactoryContext } from './factory.js';\nexport { RecoveryModule, type RecoveryModuleContext } from './recovery.js';\nexport {\n loadBalances,\n type BalanceOptions,\n type TokenBalance,\n type VaultBalances,\n} from './balances.js';\nexport { Connection } from './chain/connection.js';\nexport { withRetry, isTransient, type RetryOptions } from './chain/retry.js';\nexport { VaultContract, FactoryContract, type RawTransactionStruct } from './chain/vault-contract.js';\nexport { TokenContract } from './chain/token-contract.js';\nexport {\n RecoveryContract,\n type RawRecovery,\n type RawRecoveryConfig,\n} from './chain/recovery-contract.js';\n\n// --- configuration\nexport { networks, mainnet, testnet, isNetworkName, type NetworkName } from './config/networks.js';\nexport { resolveConfig, ENV_VARS, type ResolvedConfig } from './config/resolve.js';\n\n// --- indexer\nexport { IndexerClient } from './indexer/client.js';\nexport { IndexerQueries } from './indexer/queries.js';\nexport {\n watchVault,\n type Subscription,\n type WatchEvent,\n type WatchOptions,\n type WatchTopic,\n} from './indexer/watch.js';\nexport * as indexerSchemas from './indexer/schemas.js';\n\n// --- encoding / decoding\nexport {\n selfCall,\n token as tokenCalls,\n recoveryCall,\n encodeMultiSend,\n encodeMultiSendPayload,\n minimumExpiration,\n interfaces,\n MAX_EXECUTION_DELAY,\n MAX_MODULES,\n MAX_OWNERS,\n SENTINEL_MODULES,\n ZERO_ADDRESS,\n type BatchCall,\n} from './encode/index.js';\nexport {\n decodeCall,\n decodeMultiSendPayload,\n type DecodeContext,\n type DecodeResult,\n type DecodedBatchCall,\n} from './decode/index.js';\n\n// --- lifecycle\nexport {\n classifyExecution,\n extractProposedTxHash,\n type ReceiptLike,\n} from './lifecycle/outcome.js';\nexport {\n deriveStatus,\n deriveRecoveryStatus,\n executableAfterOf,\n isTerminal,\n nowSeconds,\n type RawTransactionState,\n type RawRecoveryState,\n} from './lifecycle/status.js';\nexport {\n computeAffordances,\n allowedActions,\n type AffordanceContext,\n} from './lifecycle/affordances.js';\n\n// --- CREATE2 / salt mining\nexport {\n mineSalt,\n defaultStrategy,\n syncStrategy,\n workerThreadsStrategy,\n createWorkerThreadsStrategy,\n type MineSaltOptions,\n type MiningStrategy,\n type WorkerRuntime,\n} from './salt/mine.js';\nexport {\n predictVaultAddress,\n encodeInitData,\n computeBytecodeHash,\n computeFullSalt,\n shardPrefixOf,\n} from './salt/predict.js';\n\n// --- display sanitisation\nexport { sanitizeText, DEFAULT_TEXT_LIMIT } from './text.js';\n\n// --- address validation\nexport {\n assertQuaiAddress,\n assertQuaiAddresses,\n inspectAddress,\n isUsableQuaiAddress,\n type AddressCheck,\n type AddressLedger,\n} from './address.js';\n\n// --- errors\nexport {\n QuaiVaultError,\n AbortError,\n ConfigError,\n NoSignerError,\n NoIndexerError,\n IndexerQueryError,\n ValidationError,\n NotFoundError,\n PreconditionError,\n RevertError,\n SaltMiningError,\n StaleProposalError,\n type QuaiVaultErrorCode,\n} from './errors/index.js';\nexport { decodeRevert, decodeRevertFromError, knownErrorSelectors, remediationFor } from './errors/decode.js';\n\n// --- ABIs\nexport * from './abi/index.js';\n\n// --- types\nexport * from './types.js';\n","import { getAddress } from 'quais';\nimport type { Provider, Signer } from 'quais';\nimport { Connection } from './chain/connection.js';\nimport { redactConfig, resolveConfig, type PublicConfig, type ResolvedConfig } from './config/resolve.js';\nimport { Factory } from './factory.js';\nimport { IndexerClient } from './indexer/client.js';\nimport { IndexerQueries } from './indexer/queries.js';\nimport { NoIndexerError } from './errors/index.js';\nimport { Vault, type VaultContext } from './vault.js';\nimport type {\n Address,\n ClientOptions,\n IndexerHealth,\n NetworkConfig,\n Pagination,\n} from './types.js';\n\n/**\n * Entry point to the SDK.\n *\n * Construct with {@link connect}. Nothing here performs I/O until a method is\n * called, so building a client is cheap and safe at module scope.\n */\nexport class QuaiVaultClient {\n /**\n * Resolved configuration, with the private key stripped and the indexer key\n * masked — safe to log. The key itself is consumed once when building the signer.\n */\n readonly config: PublicConfig;\n readonly connection: Connection;\n readonly factory: Factory;\n readonly indexer: IndexerClient | null;\n readonly queries: IndexerQueries | null;\n\n constructor(options: ClientOptions = {}) {\n // `resolved` holds the secret and is never stored on the instance.\n const resolved: ResolvedConfig = resolveConfig(options);\n this.config = redactConfig(resolved);\n this.connection = new Connection(resolved, {\n ...(options.provider ? { provider: options.provider } : {}),\n ...(options.signer ? { signer: options.signer } : {}),\n });\n\n // Built from `resolved`, not `this.config` — the latter's indexer key is masked.\n this.indexer = resolved.indexer ? new IndexerClient(resolved.indexer) : null;\n this.queries = this.indexer ? new IndexerQueries(this.indexer) : null;\n\n this.factory = new Factory({\n connection: this.connection,\n contracts: this.config.contracts,\n });\n }\n\n get network(): NetworkConfig {\n return this.config.network;\n }\n\n get provider(): Provider {\n return this.connection.provider;\n }\n\n get signer(): Signer | null {\n return this.connection.signer;\n }\n\n /** The connected address, or null when read-only. */\n async address(): Promise<Address | null> {\n return this.connection.addressOrNull();\n }\n\n /** A handle to one vault. No I/O. */\n vault(address: Address): Vault {\n return new Vault(address, this.vaultContext());\n }\n\n private vaultContext(): VaultContext {\n return {\n connection: this.connection,\n indexer: this.indexer,\n queries: this.queries,\n contracts: this.config.contracts,\n consistency: this.config.consistency,\n maxIndexerLagBlocks: this.config.maxIndexerLagBlocks,\n };\n }\n\n /** Vault discovery. Requires the indexer — there is no on-chain reverse index. */\n readonly vaults = {\n /**\n * Vaults where `owner` is an active owner.\n *\n * Indexer-only: `factory.getWalletsByCreator` was removed from the contracts for\n * gas reasons, and the factory registry is not indexed by owner.\n */\n forOwner: async (owner: Address, options: Pagination = {}): Promise<Address[]> => {\n const queries = this.requireQueries('Looking up vaults by owner');\n const rows = await queries.vaultsForOwner(getAddress(owner), options);\n return rows.map((r) => getAddress(r.address));\n },\n\n /** Vaults where `guardian` is an active social-recovery guardian. */\n forGuardian: async (guardian: Address, options: Pagination = {}): Promise<Address[]> => {\n const queries = this.requireQueries('Looking up vaults by guardian');\n const rows = await queries.vaultsForGuardian(getAddress(guardian), options);\n return rows.map((r) => getAddress(r.address));\n },\n\n /** Whether an address is a vault this factory deployed or registered. */\n exists: async (address: Address): Promise<boolean> => {\n return this.factory.isRegistered(getAddress(address));\n },\n\n get: (address: Address): Vault => this.vault(address),\n };\n\n private requireQueries(operation: string): IndexerQueries {\n if (!this.queries) throw new NoIndexerError(operation);\n return this.queries;\n }\n\n /** Indexer liveness and lag. Reports unavailable when no indexer is configured. */\n async indexerHealth(): Promise<IndexerHealth> {\n if (!this.indexer) {\n return {\n available: false,\n lastIndexedBlock: 0,\n isSyncing: false,\n error: 'no indexer configured',\n };\n }\n return this.indexer.health();\n }\n}\n\n/**\n * Create a client.\n *\n * Configuration resolves in order of decreasing precedence: explicit options,\n * environment variables, then the network preset. With nothing supplied it targets\n * mainnet over the public RPC in read-only mode.\n *\n * ```ts\n * // read-only, from env (QUAIVAULT_NETWORK, QUAIVAULT_INDEXER_ANON_KEY, …)\n * const qv = connect();\n *\n * // read-write against testnet\n * const qv = connect({ network: 'testnet', privateKey: process.env.KEY });\n * ```\n */\nexport function connect(options: ClientOptions = {}): QuaiVaultClient {\n return new QuaiVaultClient(options);\n}\n\n/** Namespace form, for callers who prefer `QuaiVault.connect(…)`. */\nexport const QuaiVault = { connect };\n","import { Contract, JsonRpcProvider, Wallet, getZoneForAddress, isQuaiAddress } from 'quais';\nimport type { Provider, Signer } from 'quais';\nimport {\n Erc1155Abi,\n Erc20Abi,\n Erc721Abi,\n QuaiVaultAbi,\n QuaiVaultFactoryAbi,\n SocialRecoveryModuleAbi,\n} from '../abi/index.js';\nimport type { Address } from '../types.js';\nimport { ConfigError, NoSignerError, ValidationError } from '../errors/index.js';\nimport type { ResolvedConfig } from '../config/resolve.js';\nimport type { RetryOptions } from './retry.js';\n\n/**\n * Owns the provider/signer pair and hands out contract instances.\n *\n * Quai RPC endpoints are shard-pathed (`https://host/cyprus1`), which `quais`\n * handles via `usePathing: true` — the same setting the indexer uses.\n */\nexport class Connection {\n readonly provider: Provider;\n /** Retry policy for reads. Shared with every contract facade this hands out. */\n readonly retry: RetryOptions;\n private readonly _signer: Signer | null;\n\n constructor(config: ResolvedConfig, explicit: { provider?: Provider; signer?: Signer } = {}) {\n this.retry = config.retry ?? {};\n this.provider =\n explicit.provider ??\n (explicit.signer?.provider as Provider | undefined) ??\n new JsonRpcProvider(config.rpcUrl, undefined, { usePathing: true });\n\n if (explicit.signer) {\n this._signer = explicit.signer;\n } else if (config.privateKey) {\n this._signer = createPrivateKeySigner(config.privateKey, this.provider);\n } else {\n this._signer = null;\n }\n }\n\n get signer(): Signer | null {\n return this._signer;\n }\n\n hasSigner(): boolean {\n return this._signer !== null;\n }\n\n /** The signer, or a typed error naming the operation that needs one. */\n requireSigner(operation: string): Signer {\n if (!this._signer) throw new NoSignerError(operation);\n return this._signer;\n }\n\n async address(): Promise<Address> {\n return this.requireSigner('Reading the connected address').getAddress();\n }\n\n /** Connected address, or null when read-only. */\n async addressOrNull(): Promise<Address | null> {\n return this._signer ? this._signer.getAddress() : null;\n }\n\n vault(address: Address, write = false): Contract {\n return new Contract(\n address,\n QuaiVaultAbi,\n write ? this.requireSigner('This vault write') : this.provider,\n );\n }\n\n factory(address: Address, write = false): Contract {\n return new Contract(\n address,\n QuaiVaultFactoryAbi,\n write ? this.requireSigner('This factory write') : this.provider,\n );\n }\n\n socialRecovery(address: Address, write = false): Contract {\n return new Contract(\n address,\n SocialRecoveryModuleAbi,\n write ? this.requireSigner('This recovery write') : this.provider,\n );\n }\n\n /**\n * Read-only handle to a token contract.\n *\n * No write variant: the SDK never calls a token directly. Moving tokens goes\n * through the vault's proposal flow, which encodes the transfer as calldata.\n */\n token(address: Address, standard: 'ERC20' | 'ERC721' | 'ERC1155'): Contract {\n const abi =\n standard === 'ERC20' ? Erc20Abi : standard === 'ERC721' ? Erc721Abi : Erc1155Abi;\n return new Contract(address, abi as unknown as string[], this.provider);\n }\n}\n\nfunction createPrivateKeySigner(privateKey: string, provider: Provider): Signer {\n const normalized = privateKey.startsWith('0x') ? privateKey : `0x${privateKey}`;\n if (!/^0x[0-9a-fA-F]{64}$/.test(normalized)) {\n throw new ConfigError(\n 'Invalid private key: expected 32 bytes of hex (64 characters, with or without a 0x prefix).',\n 'Check QUAIVAULT_PRIVATE_KEY. Never commit a private key or pass one on the command line.',\n );\n }\n try {\n const wallet = new Wallet(normalized, provider);\n\n // A usable key must satisfy two independent constraints, and an arbitrary\n // secp256k1 key generally satisfies neither:\n //\n // 1. its address falls inside a real shard prefix (`getZoneForAddress`), and\n // 2. it is on the Quai ledger rather than Qi (`isQuaiAddress`).\n //\n // These are genuinely separate: 0x7E5F… passes `isQuaiAddress` but maps to no\n // zone. Checking only the ledger bit would let such a key through, and the\n // failure would surface much later as an opaque RPC error on the first\n // transaction. Quai HD derivation scans for keys meeting both.\n const zone = getZoneForAddress(wallet.address);\n if (!zone) {\n throw new ConfigError(\n `The supplied private key derives ${wallet.address}, which does not fall within any ` +\n 'Quai shard prefix, so it cannot hold funds or transact.',\n 'Use a key from a Quai wallet — quais HD derivation scans for shard-valid addresses. ' +\n 'An arbitrary Ethereum key will not work.',\n );\n }\n if (!isQuaiAddress(wallet.address)) {\n throw new ConfigError(\n `The supplied private key derives ${wallet.address}, which is a Qi-ledger address. ` +\n 'QuaiVault operates on the Quai ledger.',\n 'Use a Quai-ledger key.',\n );\n }\n return wallet as unknown as Signer;\n } catch (cause) {\n if (cause instanceof ConfigError) throw cause;\n throw new ConfigError(\n `Could not build a signer from the supplied private key: ${\n cause instanceof Error ? cause.message : String(cause)\n }`,\n );\n }\n}\n\n/** Assert a value is a 32-byte hex string, returning it lowercased. */\nexport function normalizeTxHash(value: unknown, label = 'transaction hash'): string {\n if (typeof value !== 'string' || !/^0x[0-9a-fA-F]{64}$/.test(value)) {\n throw new ValidationError(`Invalid ${label}: expected a 0x-prefixed 32-byte hex string.`);\n }\n return value.toLowerCase();\n}\n","{\n \"contractName\": \"QuaiVault\",\n \"abi\": [\n {\n \"inputs\": [],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"constructor\"\n },\n {\n \"inputs\": [],\n \"name\": \"AlreadyAnOwner\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"AlreadyApproved\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"CalldataTooShort\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"CannotCancelApprovedTransaction\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"CannotRemoveOwnerWouldFallBelowThreshold\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"target\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"DelegateCallNotAllowed\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"target\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"DelegatecallTargetAlreadyAllowed\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"target\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"DelegatecallTargetNotAllowed\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"DuplicateOwner\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"ExecutionDelayTooLong\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"uint256\",\n \"name\": \"minimumExpiration\",\n \"type\": \"uint256\"\n }\n ],\n \"name\": \"ExpirationTooSoon\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"ImplementationSlotTampered\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"InvalidDestinationAddress\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"InvalidInitialization\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"module\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"InvalidModule\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"InvalidOwnerAddress\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"prevModule\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"InvalidPrevModule\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"InvalidThreshold\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"MaxModulesReached\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"MaxOwnersReached\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"MessageNotSigned\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"ModuleAlreadyEnabled\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"ModuleNotEnabled\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"NotAnAuthorizedModule\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"NotAnOwner\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"NotApproved\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"NotEnoughApprovals\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"NotInitializing\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"NotProposer\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"OnlySelf\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"OwnersRequired\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"ReentrancyGuardReentrantCall\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"SelfCallCannotHaveValue\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"uint256\",\n \"name\": \"executableAfter\",\n \"type\": \"uint256\"\n }\n ],\n \"name\": \"TimelockNotElapsed\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"TooManyOwners\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"TransactionAlreadyCancelled\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"TransactionAlreadyExecuted\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"TransactionAlreadyExists\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"TransactionDoesNotExist\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"TransactionIsExpired\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"TransactionNotExpired\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"bytes4\",\n \"name\": \"selector\",\n \"type\": \"bytes4\"\n }\n ],\n \"name\": \"UnrecognizedSelfCall\",\n \"type\": \"error\"\n },\n {\n \"anonymous\": false,\n \"inputs\": [\n {\n \"indexed\": true,\n \"internalType\": \"bytes32\",\n \"name\": \"txHash\",\n \"type\": \"bytes32\"\n },\n {\n \"indexed\": true,\n \"internalType\": \"address\",\n \"name\": \"owner\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"ApprovalRevoked\",\n \"type\": \"event\"\n },\n {\n \"anonymous\": false,\n \"inputs\": [\n {\n \"indexed\": true,\n \"internalType\": \"address\",\n \"name\": \"target\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"DelegatecallTargetAdded\",\n \"type\": \"event\"\n },\n {\n \"anonymous\": false,\n \"inputs\": [\n {\n \"indexed\": true,\n \"internalType\": \"address\",\n \"name\": \"target\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"DelegatecallTargetRemoved\",\n \"type\": \"event\"\n },\n {\n \"anonymous\": false,\n \"inputs\": [\n {\n \"indexed\": true,\n \"internalType\": \"address\",\n \"name\": \"module\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"DisabledModule\",\n \"type\": \"event\"\n },\n {\n \"anonymous\": false,\n \"inputs\": [\n {\n \"indexed\": true,\n \"internalType\": \"address\",\n \"name\": \"module\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"EnabledModule\",\n \"type\": \"event\"\n },\n {\n \"anonymous\": false,\n \"inputs\": [\n {\n \"indexed\": true,\n \"internalType\": \"address\",\n \"name\": \"module\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"ExecutionFromModuleFailure\",\n \"type\": \"event\"\n },\n {\n \"anonymous\": false,\n \"inputs\": [\n {\n \"indexed\": true,\n \"internalType\": \"address\",\n \"name\": \"module\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"ExecutionFromModuleSuccess\",\n \"type\": \"event\"\n },\n {\n \"anonymous\": false,\n \"inputs\": [\n {\n \"indexed\": false,\n \"internalType\": \"uint64\",\n \"name\": \"version\",\n \"type\": \"uint64\"\n }\n ],\n \"name\": \"Initialized\",\n \"type\": \"event\"\n },\n {\n \"anonymous\": false,\n \"inputs\": [\n {\n \"indexed\": true,\n \"internalType\": \"bytes32\",\n \"name\": \"msgHash\",\n \"type\": \"bytes32\"\n },\n {\n \"indexed\": false,\n \"internalType\": \"bytes\",\n \"name\": \"data\",\n \"type\": \"bytes\"\n }\n ],\n \"name\": \"MessageSigned\",\n \"type\": \"event\"\n },\n {\n \"anonymous\": false,\n \"inputs\": [\n {\n \"indexed\": true,\n \"internalType\": \"bytes32\",\n \"name\": \"msgHash\",\n \"type\": \"bytes32\"\n },\n {\n \"indexed\": false,\n \"internalType\": \"bytes\",\n \"name\": \"data\",\n \"type\": \"bytes\"\n }\n ],\n \"name\": \"MessageUnsigned\",\n \"type\": \"event\"\n },\n {\n \"anonymous\": false,\n \"inputs\": [\n {\n \"indexed\": false,\n \"internalType\": \"uint32\",\n \"name\": \"oldDelay\",\n \"type\": \"uint32\"\n },\n {\n \"indexed\": false,\n \"internalType\": \"uint32\",\n \"name\": \"newDelay\",\n \"type\": \"uint32\"\n }\n ],\n \"name\": \"MinExecutionDelayChanged\",\n \"type\": \"event\"\n },\n {\n \"anonymous\": false,\n \"inputs\": [\n {\n \"indexed\": true,\n \"internalType\": \"address\",\n \"name\": \"owner\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"OwnerAdded\",\n \"type\": \"event\"\n },\n {\n \"anonymous\": false,\n \"inputs\": [\n {\n \"indexed\": true,\n \"internalType\": \"address\",\n \"name\": \"owner\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"OwnerRemoved\",\n \"type\": \"event\"\n },\n {\n \"anonymous\": false,\n \"inputs\": [\n {\n \"indexed\": true,\n \"internalType\": \"address\",\n \"name\": \"sender\",\n \"type\": \"address\"\n },\n {\n \"indexed\": false,\n \"internalType\": \"uint256\",\n \"name\": \"amount\",\n \"type\": \"uint256\"\n }\n ],\n \"name\": \"Received\",\n \"type\": \"event\"\n },\n {\n \"anonymous\": false,\n \"inputs\": [\n {\n \"indexed\": false,\n \"internalType\": \"uint256\",\n \"name\": \"threshold\",\n \"type\": \"uint256\"\n }\n ],\n \"name\": \"ThresholdChanged\",\n \"type\": \"event\"\n },\n {\n \"anonymous\": false,\n \"inputs\": [\n {\n \"indexed\": true,\n \"internalType\": \"bytes32\",\n \"name\": \"txHash\",\n \"type\": \"bytes32\"\n },\n {\n \"indexed\": false,\n \"internalType\": \"uint48\",\n \"name\": \"approvedAt\",\n \"type\": \"uint48\"\n },\n {\n \"indexed\": false,\n \"internalType\": \"uint256\",\n \"name\": \"executableAfter\",\n \"type\": \"uint256\"\n }\n ],\n \"name\": \"ThresholdReached\",\n \"type\": \"event\"\n },\n {\n \"anonymous\": false,\n \"inputs\": [\n {\n \"indexed\": true,\n \"internalType\": \"bytes32\",\n \"name\": \"txHash\",\n \"type\": \"bytes32\"\n },\n {\n \"indexed\": true,\n \"internalType\": \"address\",\n \"name\": \"approver\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"TransactionApproved\",\n \"type\": \"event\"\n },\n {\n \"anonymous\": false,\n \"inputs\": [\n {\n \"indexed\": true,\n \"internalType\": \"bytes32\",\n \"name\": \"txHash\",\n \"type\": \"bytes32\"\n },\n {\n \"indexed\": true,\n \"internalType\": \"address\",\n \"name\": \"canceller\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"TransactionCancelled\",\n \"type\": \"event\"\n },\n {\n \"anonymous\": false,\n \"inputs\": [\n {\n \"indexed\": true,\n \"internalType\": \"bytes32\",\n \"name\": \"txHash\",\n \"type\": \"bytes32\"\n },\n {\n \"indexed\": true,\n \"internalType\": \"address\",\n \"name\": \"executor\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"TransactionExecuted\",\n \"type\": \"event\"\n },\n {\n \"anonymous\": false,\n \"inputs\": [\n {\n \"indexed\": true,\n \"internalType\": \"bytes32\",\n \"name\": \"txHash\",\n \"type\": \"bytes32\"\n }\n ],\n \"name\": \"TransactionExpired\",\n \"type\": \"event\"\n },\n {\n \"anonymous\": false,\n \"inputs\": [\n {\n \"indexed\": true,\n \"internalType\": \"bytes32\",\n \"name\": \"txHash\",\n \"type\": \"bytes32\"\n },\n {\n \"indexed\": true,\n \"internalType\": \"address\",\n \"name\": \"executor\",\n \"type\": \"address\"\n },\n {\n \"indexed\": false,\n \"internalType\": \"bytes\",\n \"name\": \"returnData\",\n \"type\": \"bytes\"\n }\n ],\n \"name\": \"TransactionFailed\",\n \"type\": \"event\"\n },\n {\n \"anonymous\": false,\n \"inputs\": [\n {\n \"indexed\": true,\n \"internalType\": \"bytes32\",\n \"name\": \"txHash\",\n \"type\": \"bytes32\"\n },\n {\n \"indexed\": true,\n \"internalType\": \"address\",\n \"name\": \"proposer\",\n \"type\": \"address\"\n },\n {\n \"indexed\": true,\n \"internalType\": \"address\",\n \"name\": \"to\",\n \"type\": \"address\"\n },\n {\n \"indexed\": false,\n \"internalType\": \"uint256\",\n \"name\": \"value\",\n \"type\": \"uint256\"\n },\n {\n \"indexed\": false,\n \"internalType\": \"bytes\",\n \"name\": \"data\",\n \"type\": \"bytes\"\n },\n {\n \"indexed\": false,\n \"internalType\": \"uint48\",\n \"name\": \"expiration\",\n \"type\": \"uint48\"\n },\n {\n \"indexed\": false,\n \"internalType\": \"uint32\",\n \"name\": \"executionDelay\",\n \"type\": \"uint32\"\n }\n ],\n \"name\": \"TransactionProposed\",\n \"type\": \"event\"\n },\n {\n \"stateMutability\": \"payable\",\n \"type\": \"fallback\"\n },\n {\n \"inputs\": [],\n \"name\": \"MAX_EXECUTION_DELAY\",\n \"outputs\": [\n {\n \"internalType\": \"uint32\",\n \"name\": \"\",\n \"type\": \"uint32\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [],\n \"name\": \"MAX_MODULES\",\n \"outputs\": [\n {\n \"internalType\": \"uint256\",\n \"name\": \"\",\n \"type\": \"uint256\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [],\n \"name\": \"MAX_OWNERS\",\n \"outputs\": [\n {\n \"internalType\": \"uint256\",\n \"name\": \"\",\n \"type\": \"uint256\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"target\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"addDelegatecallTarget\",\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"owner\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"addOwner\",\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"bytes32\",\n \"name\": \"txHash\",\n \"type\": \"bytes32\"\n }\n ],\n \"name\": \"approveAndExecute\",\n \"outputs\": [\n {\n \"internalType\": \"bool\",\n \"name\": \"executed\",\n \"type\": \"bool\"\n }\n ],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"bytes32\",\n \"name\": \"txHash\",\n \"type\": \"bytes32\"\n }\n ],\n \"name\": \"approveTransaction\",\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"bytes32\",\n \"name\": \"txHash\",\n \"type\": \"bytes32\"\n }\n ],\n \"name\": \"cancelByConsensus\",\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"bytes32\",\n \"name\": \"txHash\",\n \"type\": \"bytes32\"\n }\n ],\n \"name\": \"cancelTransaction\",\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"uint256\",\n \"name\": \"_threshold\",\n \"type\": \"uint256\"\n }\n ],\n \"name\": \"changeThreshold\",\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"delegatecallAllowed\",\n \"outputs\": [\n {\n \"internalType\": \"bool\",\n \"name\": \"\",\n \"type\": \"bool\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"prevModule\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"address\",\n \"name\": \"module\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"disableModule\",\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [],\n \"name\": \"domainSeparator\",\n \"outputs\": [\n {\n \"internalType\": \"bytes32\",\n \"name\": \"\",\n \"type\": \"bytes32\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"module\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"enableModule\",\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"bytes\",\n \"name\": \"message\",\n \"type\": \"bytes\"\n }\n ],\n \"name\": \"encodeMessageData\",\n \"outputs\": [\n {\n \"internalType\": \"bytes\",\n \"name\": \"\",\n \"type\": \"bytes\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"to\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"value\",\n \"type\": \"uint256\"\n },\n {\n \"internalType\": \"bytes\",\n \"name\": \"data\",\n \"type\": \"bytes\"\n }\n ],\n \"name\": \"execTransactionFromModule\",\n \"outputs\": [\n {\n \"internalType\": \"bool\",\n \"name\": \"success\",\n \"type\": \"bool\"\n }\n ],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"to\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"value\",\n \"type\": \"uint256\"\n },\n {\n \"internalType\": \"bytes\",\n \"name\": \"data\",\n \"type\": \"bytes\"\n },\n {\n \"internalType\": \"enum Enum.Operation\",\n \"name\": \"operation\",\n \"type\": \"uint8\"\n }\n ],\n \"name\": \"execTransactionFromModule\",\n \"outputs\": [\n {\n \"internalType\": \"bool\",\n \"name\": \"success\",\n \"type\": \"bool\"\n }\n ],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"to\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"value\",\n \"type\": \"uint256\"\n },\n {\n \"internalType\": \"bytes\",\n \"name\": \"data\",\n \"type\": \"bytes\"\n },\n {\n \"internalType\": \"enum Enum.Operation\",\n \"name\": \"operation\",\n \"type\": \"uint8\"\n }\n ],\n \"name\": \"execTransactionFromModuleReturnData\",\n \"outputs\": [\n {\n \"internalType\": \"bool\",\n \"name\": \"success\",\n \"type\": \"bool\"\n },\n {\n \"internalType\": \"bytes\",\n \"name\": \"returnData\",\n \"type\": \"bytes\"\n }\n ],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"bytes32\",\n \"name\": \"txHash\",\n \"type\": \"bytes32\"\n }\n ],\n \"name\": \"executeTransaction\",\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"bytes32\",\n \"name\": \"txHash\",\n \"type\": \"bytes32\"\n }\n ],\n \"name\": \"expireTransaction\",\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"bytes32\",\n \"name\": \"\",\n \"type\": \"bytes32\"\n }\n ],\n \"name\": \"expiredTxs\",\n \"outputs\": [\n {\n \"internalType\": \"bool\",\n \"name\": \"\",\n \"type\": \"bool\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"bytes\",\n \"name\": \"message\",\n \"type\": \"bytes\"\n }\n ],\n \"name\": \"getMessageHash\",\n \"outputs\": [\n {\n \"internalType\": \"bytes32\",\n \"name\": \"\",\n \"type\": \"bytes32\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [],\n \"name\": \"getModules\",\n \"outputs\": [\n {\n \"internalType\": \"address[]\",\n \"name\": \"\",\n \"type\": \"address[]\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"start\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"pageSize\",\n \"type\": \"uint256\"\n }\n ],\n \"name\": \"getModulesPaginated\",\n \"outputs\": [\n {\n \"internalType\": \"address[]\",\n \"name\": \"array\",\n \"type\": \"address[]\"\n },\n {\n \"internalType\": \"address\",\n \"name\": \"next\",\n \"type\": \"address\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [],\n \"name\": \"getOwnerCount\",\n \"outputs\": [\n {\n \"internalType\": \"uint256\",\n \"name\": \"\",\n \"type\": \"uint256\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [],\n \"name\": \"getOwners\",\n \"outputs\": [\n {\n \"internalType\": \"address[]\",\n \"name\": \"\",\n \"type\": \"address[]\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"bytes32\",\n \"name\": \"txHash\",\n \"type\": \"bytes32\"\n }\n ],\n \"name\": \"getTransaction\",\n \"outputs\": [\n {\n \"components\": [\n {\n \"internalType\": \"address\",\n \"name\": \"to\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"uint48\",\n \"name\": \"timestamp\",\n \"type\": \"uint48\"\n },\n {\n \"internalType\": \"uint48\",\n \"name\": \"expiration\",\n \"type\": \"uint48\"\n },\n {\n \"internalType\": \"address\",\n \"name\": \"proposer\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"bool\",\n \"name\": \"executed\",\n \"type\": \"bool\"\n },\n {\n \"internalType\": \"bool\",\n \"name\": \"cancelled\",\n \"type\": \"bool\"\n },\n {\n \"internalType\": \"uint48\",\n \"name\": \"approvedAt\",\n \"type\": \"uint48\"\n },\n {\n \"internalType\": \"uint32\",\n \"name\": \"executionDelay\",\n \"type\": \"uint32\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"value\",\n \"type\": \"uint256\"\n },\n {\n \"internalType\": \"bytes\",\n \"name\": \"data\",\n \"type\": \"bytes\"\n }\n ],\n \"internalType\": \"struct QuaiVault.Transaction\",\n \"name\": \"\",\n \"type\": \"tuple\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"to\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"value\",\n \"type\": \"uint256\"\n },\n {\n \"internalType\": \"bytes\",\n \"name\": \"data\",\n \"type\": \"bytes\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"_nonce\",\n \"type\": \"uint256\"\n }\n ],\n \"name\": \"getTransactionHash\",\n \"outputs\": [\n {\n \"internalType\": \"bytes32\",\n \"name\": \"\",\n \"type\": \"bytes32\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"bytes32\",\n \"name\": \"txHash\",\n \"type\": \"bytes32\"\n },\n {\n \"internalType\": \"address\",\n \"name\": \"owner\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"hasApproved\",\n \"outputs\": [\n {\n \"internalType\": \"bool\",\n \"name\": \"\",\n \"type\": \"bool\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address[]\",\n \"name\": \"_owners\",\n \"type\": \"address[]\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"_threshold\",\n \"type\": \"uint256\"\n },\n {\n \"internalType\": \"uint32\",\n \"name\": \"_minExecutionDelay\",\n \"type\": \"uint32\"\n },\n {\n \"internalType\": \"address[]\",\n \"name\": \"_initialModules\",\n \"type\": \"address[]\"\n },\n {\n \"internalType\": \"address[]\",\n \"name\": \"_initialDelegatecallTargets\",\n \"type\": \"address[]\"\n }\n ],\n \"name\": \"initialize\",\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"module\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"isModuleEnabled\",\n \"outputs\": [\n {\n \"internalType\": \"bool\",\n \"name\": \"\",\n \"type\": \"bool\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"isOwner\",\n \"outputs\": [\n {\n \"internalType\": \"bool\",\n \"name\": \"\",\n \"type\": \"bool\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"bytes32\",\n \"name\": \"_dataHash\",\n \"type\": \"bytes32\"\n },\n {\n \"internalType\": \"bytes\",\n \"name\": \"\",\n \"type\": \"bytes\"\n }\n ],\n \"name\": \"isValidSignature\",\n \"outputs\": [\n {\n \"internalType\": \"bytes4\",\n \"name\": \"\",\n \"type\": \"bytes4\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [],\n \"name\": \"minExecutionDelay\",\n \"outputs\": [\n {\n \"internalType\": \"uint32\",\n \"name\": \"\",\n \"type\": \"uint32\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [],\n \"name\": \"moduleCount\",\n \"outputs\": [\n {\n \"internalType\": \"uint256\",\n \"name\": \"\",\n \"type\": \"uint256\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [],\n \"name\": \"nonce\",\n \"outputs\": [\n {\n \"internalType\": \"uint256\",\n \"name\": \"\",\n \"type\": \"uint256\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"address\",\n \"name\": \"\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"uint256[]\",\n \"name\": \"\",\n \"type\": \"uint256[]\"\n },\n {\n \"internalType\": \"uint256[]\",\n \"name\": \"\",\n \"type\": \"uint256[]\"\n },\n {\n \"internalType\": \"bytes\",\n \"name\": \"\",\n \"type\": \"bytes\"\n }\n ],\n \"name\": \"onERC1155BatchReceived\",\n \"outputs\": [\n {\n \"internalType\": \"bytes4\",\n \"name\": \"\",\n \"type\": \"bytes4\"\n }\n ],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"address\",\n \"name\": \"\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"\",\n \"type\": \"uint256\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"\",\n \"type\": \"uint256\"\n },\n {\n \"internalType\": \"bytes\",\n \"name\": \"\",\n \"type\": \"bytes\"\n }\n ],\n \"name\": \"onERC1155Received\",\n \"outputs\": [\n {\n \"internalType\": \"bytes4\",\n \"name\": \"\",\n \"type\": \"bytes4\"\n }\n ],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"address\",\n \"name\": \"\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"\",\n \"type\": \"uint256\"\n },\n {\n \"internalType\": \"bytes\",\n \"name\": \"\",\n \"type\": \"bytes\"\n }\n ],\n \"name\": \"onERC721Received\",\n \"outputs\": [\n {\n \"internalType\": \"bytes4\",\n \"name\": \"\",\n \"type\": \"bytes4\"\n }\n ],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"ownerVersions\",\n \"outputs\": [\n {\n \"internalType\": \"uint256\",\n \"name\": \"\",\n \"type\": \"uint256\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"uint256\",\n \"name\": \"\",\n \"type\": \"uint256\"\n }\n ],\n \"name\": \"owners\",\n \"outputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"\",\n \"type\": \"address\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"to\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"value\",\n \"type\": \"uint256\"\n },\n {\n \"internalType\": \"bytes\",\n \"name\": \"data\",\n \"type\": \"bytes\"\n },\n {\n \"internalType\": \"uint48\",\n \"name\": \"expiration\",\n \"type\": \"uint48\"\n }\n ],\n \"name\": \"proposeTransaction\",\n \"outputs\": [\n {\n \"internalType\": \"bytes32\",\n \"name\": \"\",\n \"type\": \"bytes32\"\n }\n ],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"to\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"value\",\n \"type\": \"uint256\"\n },\n {\n \"internalType\": \"bytes\",\n \"name\": \"data\",\n \"type\": \"bytes\"\n },\n {\n \"internalType\": \"uint48\",\n \"name\": \"expiration\",\n \"type\": \"uint48\"\n },\n {\n \"internalType\": \"uint32\",\n \"name\": \"requestedDelay\",\n \"type\": \"uint32\"\n }\n ],\n \"name\": \"proposeTransaction\",\n \"outputs\": [\n {\n \"internalType\": \"bytes32\",\n \"name\": \"\",\n \"type\": \"bytes32\"\n }\n ],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"to\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"value\",\n \"type\": \"uint256\"\n },\n {\n \"internalType\": \"bytes\",\n \"name\": \"data\",\n \"type\": \"bytes\"\n }\n ],\n \"name\": \"proposeTransaction\",\n \"outputs\": [\n {\n \"internalType\": \"bytes32\",\n \"name\": \"\",\n \"type\": \"bytes32\"\n }\n ],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"target\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"removeDelegatecallTarget\",\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"owner\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"removeOwner\",\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"bytes32\",\n \"name\": \"txHash\",\n \"type\": \"bytes32\"\n }\n ],\n \"name\": \"revokeApproval\",\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"uint32\",\n \"name\": \"delay\",\n \"type\": \"uint32\"\n }\n ],\n \"name\": \"setMinExecutionDelay\",\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"bytes\",\n \"name\": \"data\",\n \"type\": \"bytes\"\n }\n ],\n \"name\": \"signMessage\",\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"bytes32\",\n \"name\": \"\",\n \"type\": \"bytes32\"\n }\n ],\n \"name\": \"signedMessages\",\n \"outputs\": [\n {\n \"internalType\": \"bool\",\n \"name\": \"\",\n \"type\": \"bool\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"bytes4\",\n \"name\": \"interfaceId\",\n \"type\": \"bytes4\"\n }\n ],\n \"name\": \"supportsInterface\",\n \"outputs\": [\n {\n \"internalType\": \"bool\",\n \"name\": \"\",\n \"type\": \"bool\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [],\n \"name\": \"threshold\",\n \"outputs\": [\n {\n \"internalType\": \"uint256\",\n \"name\": \"\",\n \"type\": \"uint256\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"bytes32\",\n \"name\": \"\",\n \"type\": \"bytes32\"\n }\n ],\n \"name\": \"transactions\",\n \"outputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"to\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"uint48\",\n \"name\": \"timestamp\",\n \"type\": \"uint48\"\n },\n {\n \"internalType\": \"uint48\",\n \"name\": \"expiration\",\n \"type\": \"uint48\"\n },\n {\n \"internalType\": \"address\",\n \"name\": \"proposer\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"bool\",\n \"name\": \"executed\",\n \"type\": \"bool\"\n },\n {\n \"internalType\": \"bool\",\n \"name\": \"cancelled\",\n \"type\": \"bool\"\n },\n {\n \"internalType\": \"uint48\",\n \"name\": \"approvedAt\",\n \"type\": \"uint48\"\n },\n {\n \"internalType\": \"uint32\",\n \"name\": \"executionDelay\",\n \"type\": \"uint32\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"value\",\n \"type\": \"uint256\"\n },\n {\n \"internalType\": \"bytes\",\n \"name\": \"data\",\n \"type\": \"bytes\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"bytes\",\n \"name\": \"data\",\n \"type\": \"bytes\"\n }\n ],\n \"name\": \"unsignMessage\",\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"stateMutability\": \"payable\",\n \"type\": \"receive\"\n }\n ]\n}\n","{\n \"contractName\": \"QuaiVaultFactory\",\n \"abi\": [\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"_implementation\",\n \"type\": \"address\"\n }\n ],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"constructor\"\n },\n {\n \"inputs\": [],\n \"name\": \"CallerIsNotAnOwner\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"DuplicateOwner\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"ExecutionDelayTooLong\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"InvalidImplementationAddress\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"InvalidOwnerAddress\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"InvalidThreshold\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"InvalidWalletAddress\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"InvalidWalletImplementation\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"OwnersRequired\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"TooManyOwners\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"WalletAlreadyRegistered\",\n \"type\": \"error\"\n },\n {\n \"anonymous\": false,\n \"inputs\": [\n {\n \"indexed\": true,\n \"internalType\": \"address\",\n \"name\": \"wallet\",\n \"type\": \"address\"\n },\n {\n \"indexed\": false,\n \"internalType\": \"address[]\",\n \"name\": \"owners\",\n \"type\": \"address[]\"\n },\n {\n \"indexed\": false,\n \"internalType\": \"uint256\",\n \"name\": \"threshold\",\n \"type\": \"uint256\"\n },\n {\n \"indexed\": true,\n \"internalType\": \"address\",\n \"name\": \"creator\",\n \"type\": \"address\"\n },\n {\n \"indexed\": false,\n \"internalType\": \"bytes32\",\n \"name\": \"salt\",\n \"type\": \"bytes32\"\n }\n ],\n \"name\": \"WalletCreated\",\n \"type\": \"event\"\n },\n {\n \"anonymous\": false,\n \"inputs\": [\n {\n \"indexed\": true,\n \"internalType\": \"address\",\n \"name\": \"wallet\",\n \"type\": \"address\"\n },\n {\n \"indexed\": true,\n \"internalType\": \"address\",\n \"name\": \"registrar\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"WalletRegistered\",\n \"type\": \"event\"\n },\n {\n \"inputs\": [],\n \"name\": \"MAX_EXECUTION_DELAY\",\n \"outputs\": [\n {\n \"internalType\": \"uint32\",\n \"name\": \"\",\n \"type\": \"uint32\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address[]\",\n \"name\": \"owners\",\n \"type\": \"address[]\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"threshold\",\n \"type\": \"uint256\"\n },\n {\n \"internalType\": \"bytes32\",\n \"name\": \"salt\",\n \"type\": \"bytes32\"\n }\n ],\n \"name\": \"createWallet\",\n \"outputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"wallet\",\n \"type\": \"address\"\n }\n ],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address[]\",\n \"name\": \"owners\",\n \"type\": \"address[]\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"threshold\",\n \"type\": \"uint256\"\n },\n {\n \"internalType\": \"bytes32\",\n \"name\": \"salt\",\n \"type\": \"bytes32\"\n },\n {\n \"internalType\": \"uint32\",\n \"name\": \"minExecutionDelay\",\n \"type\": \"uint32\"\n },\n {\n \"internalType\": \"address[]\",\n \"name\": \"initialModules\",\n \"type\": \"address[]\"\n }\n ],\n \"name\": \"createWallet\",\n \"outputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"wallet\",\n \"type\": \"address\"\n }\n ],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address[]\",\n \"name\": \"owners\",\n \"type\": \"address[]\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"threshold\",\n \"type\": \"uint256\"\n },\n {\n \"internalType\": \"bytes32\",\n \"name\": \"salt\",\n \"type\": \"bytes32\"\n },\n {\n \"internalType\": \"uint32\",\n \"name\": \"minExecutionDelay\",\n \"type\": \"uint32\"\n },\n {\n \"internalType\": \"address[]\",\n \"name\": \"initialModules\",\n \"type\": \"address[]\"\n },\n {\n \"internalType\": \"address[]\",\n \"name\": \"initialDelegatecallTargets\",\n \"type\": \"address[]\"\n }\n ],\n \"name\": \"createWallet\",\n \"outputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"wallet\",\n \"type\": \"address\"\n }\n ],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address[]\",\n \"name\": \"owners\",\n \"type\": \"address[]\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"threshold\",\n \"type\": \"uint256\"\n },\n {\n \"internalType\": \"bytes32\",\n \"name\": \"salt\",\n \"type\": \"bytes32\"\n },\n {\n \"internalType\": \"uint32\",\n \"name\": \"minExecutionDelay\",\n \"type\": \"uint32\"\n }\n ],\n \"name\": \"createWallet\",\n \"outputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"wallet\",\n \"type\": \"address\"\n }\n ],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"uint256\",\n \"name\": \"\",\n \"type\": \"uint256\"\n }\n ],\n \"name\": \"deployedWallets\",\n \"outputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"\",\n \"type\": \"address\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [],\n \"name\": \"getWalletCount\",\n \"outputs\": [\n {\n \"internalType\": \"uint256\",\n \"name\": \"\",\n \"type\": \"uint256\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [],\n \"name\": \"implementation\",\n \"outputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"\",\n \"type\": \"address\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"isWallet\",\n \"outputs\": [\n {\n \"internalType\": \"bool\",\n \"name\": \"\",\n \"type\": \"bool\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"deployer\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"bytes32\",\n \"name\": \"salt\",\n \"type\": \"bytes32\"\n },\n {\n \"internalType\": \"address[]\",\n \"name\": \"owners\",\n \"type\": \"address[]\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"threshold\",\n \"type\": \"uint256\"\n },\n {\n \"internalType\": \"uint32\",\n \"name\": \"minExecutionDelay\",\n \"type\": \"uint32\"\n },\n {\n \"internalType\": \"address[]\",\n \"name\": \"initialModules\",\n \"type\": \"address[]\"\n },\n {\n \"internalType\": \"address[]\",\n \"name\": \"initialDelegatecallTargets\",\n \"type\": \"address[]\"\n }\n ],\n \"name\": \"predictWalletAddress\",\n \"outputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"\",\n \"type\": \"address\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [],\n \"name\": \"proxyCodeHash\",\n \"outputs\": [\n {\n \"internalType\": \"bytes32\",\n \"name\": \"\",\n \"type\": \"bytes32\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"wallet\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"registerWallet\",\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n }\n ]\n}\n","{\n \"contractName\": \"QuaiVaultProxy\",\n \"abi\": [\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"implementation\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"bytes\",\n \"name\": \"data\",\n \"type\": \"bytes\"\n }\n ],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"constructor\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"target\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"AddressEmptyCode\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"implementation\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"ERC1967InvalidImplementation\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"ERC1967NonPayable\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"FailedCall\",\n \"type\": \"error\"\n },\n {\n \"anonymous\": false,\n \"inputs\": [\n {\n \"indexed\": true,\n \"internalType\": \"address\",\n \"name\": \"sender\",\n \"type\": \"address\"\n },\n {\n \"indexed\": false,\n \"internalType\": \"uint256\",\n \"name\": \"value\",\n \"type\": \"uint256\"\n }\n ],\n \"name\": \"Received\",\n \"type\": \"event\"\n },\n {\n \"anonymous\": false,\n \"inputs\": [\n {\n \"indexed\": true,\n \"internalType\": \"address\",\n \"name\": \"implementation\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"Upgraded\",\n \"type\": \"event\"\n },\n {\n \"stateMutability\": \"payable\",\n \"type\": \"fallback\"\n },\n {\n \"inputs\": [],\n \"name\": \"getImplementation\",\n \"outputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"\",\n \"type\": \"address\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"stateMutability\": \"payable\",\n \"type\": \"receive\"\n }\n ],\n \"bytecode\": \"0x608060405234801561001057600080fd5b506040516104d23803806104d283398101604081905261002f91610278565b818161003b8282610044565b50505050610362565b61004d826100a3565b6040516001600160a01b038316907fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b90600090a280511561009757610092828261011f565b505050565b61009f610196565b5050565b806001600160a01b03163b6000036100de57604051634c9c8ce360e01b81526001600160a01b03821660048201526024015b60405180910390fd5b7f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc80546001600160a01b0319166001600160a01b0392909216919091179055565b6060600080846001600160a01b03168460405161013c9190610346565b600060405180830381855af49150503d8060008114610177576040519150601f19603f3d011682016040523d82523d6000602084013e61017c565b606091505b50909250905061018d8583836101b7565b95945050505050565b34156101b55760405163b398979f60e01b815260040160405180910390fd5b565b6060826101cc576101c782610216565b61020f565b81511580156101e357506001600160a01b0384163b155b1561020c57604051639996b31560e01b81526001600160a01b03851660048201526024016100d5565b50805b9392505050565b80511561022557805160208201fd5b60405163d6bda27560e01b815260040160405180910390fd5b634e487b7160e01b600052604160045260246000fd5b60005b8381101561026f578181015183820152602001610257565b50506000910152565b6000806040838503121561028b57600080fd5b82516001600160a01b03811681146102a257600080fd5b60208401519092506001600160401b03808211156102bf57600080fd5b818501915085601f8301126102d357600080fd5b8151818111156102e5576102e561023e565b604051601f8201601f19908116603f0116810190838211818310171561030d5761030d61023e565b8160405282815288602084870101111561032657600080fd5b610337836020830160208801610254565b80955050505050509250929050565b60008251610358818460208701610254565b9190910192915050565b610161806103716000396000f3fe6080604052600436106100225760003560e01c8063aaf10f42146100685761005e565b3661005e5760405134815233907f88a5966d370b9919b20f3e2c13ff65706f196a4e32cc2c12bf57088f885258749060200160405180910390a2005b6100666100a6565b005b34801561007457600080fd5b5061007d6100b8565b60405173ffffffffffffffffffffffffffffffffffffffff909116815260200160405180910390f35b6100b66100b16100c7565b610107565b565b60006100c26100c7565b905090565b60006100c27f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc5473ffffffffffffffffffffffffffffffffffffffff1690565b3660008037600080366000845af43d6000803e808015610126573d6000f35b3d6000fdfea264697066735822122037ca1a4579066f991b4af91a998ae015900bb0abdc8be6637c4258d053f5f1d864736f6c63430008160033\"\n}\n","{\n \"contractName\": \"SocialRecoveryModule\",\n \"abi\": [\n {\n \"inputs\": [],\n \"name\": \"AlreadyApproved\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"CannotUpdateConfigWhileRecoveriesPending\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"DuplicateGuardian\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"DuplicateNewOwner\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"GuardiansRequired\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"InvalidGuardianAddress\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"InvalidNewOwnerAddress\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"InvalidThreshold\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"ModuleNotEnabled\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"MustBeCalledByWallet\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"NewOwnersRequired\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"NotAGuardian\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"NotAnOwner\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"NotApproved\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"NotEnoughApprovals\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"RecoveryAlreadyExecuted\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"RecoveryAlreadyInitiated\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"RecoveryExceedsMaxOwners\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"RecoveryExpired\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"RecoveryNotConfigured\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"RecoveryNotExpired\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"RecoveryNotInitiated\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"RecoveryPeriodNotElapsed\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"RecoveryPeriodTooShort\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"RecoveryStepFailed\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"ReentrancyGuardReentrantCall\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"TooManyGuardians\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"TooManyNewOwners\",\n \"type\": \"error\"\n },\n {\n \"inputs\": [],\n \"name\": \"TooManyPendingRecoveries\",\n \"type\": \"error\"\n },\n {\n \"anonymous\": false,\n \"inputs\": [\n {\n \"indexed\": true,\n \"internalType\": \"address\",\n \"name\": \"wallet\",\n \"type\": \"address\"\n },\n {\n \"indexed\": true,\n \"internalType\": \"bytes32\",\n \"name\": \"recoveryHash\",\n \"type\": \"bytes32\"\n },\n {\n \"indexed\": true,\n \"internalType\": \"address\",\n \"name\": \"guardian\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"RecoveryApprovalRevoked\",\n \"type\": \"event\"\n },\n {\n \"anonymous\": false,\n \"inputs\": [\n {\n \"indexed\": true,\n \"internalType\": \"address\",\n \"name\": \"wallet\",\n \"type\": \"address\"\n },\n {\n \"indexed\": true,\n \"internalType\": \"bytes32\",\n \"name\": \"recoveryHash\",\n \"type\": \"bytes32\"\n },\n {\n \"indexed\": true,\n \"internalType\": \"address\",\n \"name\": \"guardian\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"RecoveryApproved\",\n \"type\": \"event\"\n },\n {\n \"anonymous\": false,\n \"inputs\": [\n {\n \"indexed\": true,\n \"internalType\": \"address\",\n \"name\": \"wallet\",\n \"type\": \"address\"\n },\n {\n \"indexed\": true,\n \"internalType\": \"bytes32\",\n \"name\": \"recoveryHash\",\n \"type\": \"bytes32\"\n }\n ],\n \"name\": \"RecoveryCancelled\",\n \"type\": \"event\"\n },\n {\n \"anonymous\": false,\n \"inputs\": [\n {\n \"indexed\": true,\n \"internalType\": \"address\",\n \"name\": \"wallet\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"RecoveryConfigCleared\",\n \"type\": \"event\"\n },\n {\n \"anonymous\": false,\n \"inputs\": [\n {\n \"indexed\": true,\n \"internalType\": \"address\",\n \"name\": \"wallet\",\n \"type\": \"address\"\n },\n {\n \"indexed\": true,\n \"internalType\": \"bytes32\",\n \"name\": \"recoveryHash\",\n \"type\": \"bytes32\"\n }\n ],\n \"name\": \"RecoveryExecuted\",\n \"type\": \"event\"\n },\n {\n \"anonymous\": false,\n \"inputs\": [\n {\n \"indexed\": true,\n \"internalType\": \"address\",\n \"name\": \"wallet\",\n \"type\": \"address\"\n },\n {\n \"indexed\": true,\n \"internalType\": \"bytes32\",\n \"name\": \"recoveryHash\",\n \"type\": \"bytes32\"\n }\n ],\n \"name\": \"RecoveryExpiredEvent\",\n \"type\": \"event\"\n },\n {\n \"anonymous\": false,\n \"inputs\": [\n {\n \"indexed\": true,\n \"internalType\": \"address\",\n \"name\": \"wallet\",\n \"type\": \"address\"\n },\n {\n \"indexed\": true,\n \"internalType\": \"bytes32\",\n \"name\": \"recoveryHash\",\n \"type\": \"bytes32\"\n },\n {\n \"indexed\": false,\n \"internalType\": \"address[]\",\n \"name\": \"newOwners\",\n \"type\": \"address[]\"\n },\n {\n \"indexed\": false,\n \"internalType\": \"uint256\",\n \"name\": \"newThreshold\",\n \"type\": \"uint256\"\n },\n {\n \"indexed\": true,\n \"internalType\": \"address\",\n \"name\": \"initiator\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"RecoveryInitiated\",\n \"type\": \"event\"\n },\n {\n \"anonymous\": false,\n \"inputs\": [\n {\n \"indexed\": true,\n \"internalType\": \"address\",\n \"name\": \"wallet\",\n \"type\": \"address\"\n },\n {\n \"indexed\": true,\n \"internalType\": \"bytes32\",\n \"name\": \"recoveryHash\",\n \"type\": \"bytes32\"\n }\n ],\n \"name\": \"RecoveryInvalidated\",\n \"type\": \"event\"\n },\n {\n \"anonymous\": false,\n \"inputs\": [\n {\n \"indexed\": true,\n \"internalType\": \"address\",\n \"name\": \"wallet\",\n \"type\": \"address\"\n },\n {\n \"indexed\": false,\n \"internalType\": \"address[]\",\n \"name\": \"guardians\",\n \"type\": \"address[]\"\n },\n {\n \"indexed\": false,\n \"internalType\": \"uint256\",\n \"name\": \"threshold\",\n \"type\": \"uint256\"\n },\n {\n \"indexed\": false,\n \"internalType\": \"uint256\",\n \"name\": \"recoveryPeriod\",\n \"type\": \"uint256\"\n }\n ],\n \"name\": \"RecoverySetup\",\n \"type\": \"event\"\n },\n {\n \"inputs\": [],\n \"name\": \"MAX_GUARDIANS\",\n \"outputs\": [\n {\n \"internalType\": \"uint256\",\n \"name\": \"\",\n \"type\": \"uint256\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"wallet\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"bytes32\",\n \"name\": \"recoveryHash\",\n \"type\": \"bytes32\"\n }\n ],\n \"name\": \"approveRecovery\",\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"wallet\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"bytes32\",\n \"name\": \"recoveryHash\",\n \"type\": \"bytes32\"\n }\n ],\n \"name\": \"cancelRecovery\",\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"wallet\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"bytes32\",\n \"name\": \"recoveryHash\",\n \"type\": \"bytes32\"\n }\n ],\n \"name\": \"executeRecovery\",\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"wallet\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"bytes32\",\n \"name\": \"recoveryHash\",\n \"type\": \"bytes32\"\n }\n ],\n \"name\": \"expireRecovery\",\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"wallet\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"getPendingRecoveryHashes\",\n \"outputs\": [\n {\n \"internalType\": \"bytes32[]\",\n \"name\": \"\",\n \"type\": \"bytes32[]\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"wallet\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"bytes32\",\n \"name\": \"recoveryHash\",\n \"type\": \"bytes32\"\n }\n ],\n \"name\": \"getRecovery\",\n \"outputs\": [\n {\n \"components\": [\n {\n \"internalType\": \"address[]\",\n \"name\": \"newOwners\",\n \"type\": \"address[]\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"newThreshold\",\n \"type\": \"uint256\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"approvalCount\",\n \"type\": \"uint256\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"executionTime\",\n \"type\": \"uint256\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"expiration\",\n \"type\": \"uint256\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"requiredThreshold\",\n \"type\": \"uint256\"\n },\n {\n \"internalType\": \"bool\",\n \"name\": \"executed\",\n \"type\": \"bool\"\n }\n ],\n \"internalType\": \"struct SocialRecoveryModule.Recovery\",\n \"name\": \"\",\n \"type\": \"tuple\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"wallet\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"getRecoveryConfig\",\n \"outputs\": [\n {\n \"components\": [\n {\n \"internalType\": \"address[]\",\n \"name\": \"guardians\",\n \"type\": \"address[]\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"threshold\",\n \"type\": \"uint256\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"recoveryPeriod\",\n \"type\": \"uint256\"\n }\n ],\n \"internalType\": \"struct SocialRecoveryModule.RecoveryConfig\",\n \"name\": \"\",\n \"type\": \"tuple\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"wallet\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"address[]\",\n \"name\": \"newOwners\",\n \"type\": \"address[]\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"newThreshold\",\n \"type\": \"uint256\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"nonce\",\n \"type\": \"uint256\"\n }\n ],\n \"name\": \"getRecoveryHash\",\n \"outputs\": [\n {\n \"internalType\": \"bytes32\",\n \"name\": \"\",\n \"type\": \"bytes32\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"wallet\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"hasPendingRecoveries\",\n \"outputs\": [\n {\n \"internalType\": \"bool\",\n \"name\": \"\",\n \"type\": \"bool\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"wallet\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"address[]\",\n \"name\": \"newOwners\",\n \"type\": \"address[]\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"newThreshold\",\n \"type\": \"uint256\"\n }\n ],\n \"name\": \"initiateRecovery\",\n \"outputs\": [\n {\n \"internalType\": \"bytes32\",\n \"name\": \"\",\n \"type\": \"bytes32\"\n }\n ],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"wallet\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"address\",\n \"name\": \"guardian\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"isGuardian\",\n \"outputs\": [\n {\n \"internalType\": \"bool\",\n \"name\": \"\",\n \"type\": \"bool\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"\",\n \"type\": \"uint256\"\n }\n ],\n \"name\": \"pendingRecoveryHashes\",\n \"outputs\": [\n {\n \"internalType\": \"bytes32\",\n \"name\": \"\",\n \"type\": \"bytes32\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"wallet\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"address[]\",\n \"name\": \"newOwners\",\n \"type\": \"address[]\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"newThreshold\",\n \"type\": \"uint256\"\n }\n ],\n \"name\": \"predictNextRecoveryHash\",\n \"outputs\": [\n {\n \"internalType\": \"bytes32\",\n \"name\": \"\",\n \"type\": \"bytes32\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"bytes32\",\n \"name\": \"\",\n \"type\": \"bytes32\"\n }\n ],\n \"name\": \"recoveries\",\n \"outputs\": [\n {\n \"internalType\": \"uint256\",\n \"name\": \"newThreshold\",\n \"type\": \"uint256\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"approvalCount\",\n \"type\": \"uint256\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"executionTime\",\n \"type\": \"uint256\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"expiration\",\n \"type\": \"uint256\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"requiredThreshold\",\n \"type\": \"uint256\"\n },\n {\n \"internalType\": \"bool\",\n \"name\": \"executed\",\n \"type\": \"bool\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"bytes32\",\n \"name\": \"\",\n \"type\": \"bytes32\"\n },\n {\n \"internalType\": \"address\",\n \"name\": \"\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"recoveryApprovals\",\n \"outputs\": [\n {\n \"internalType\": \"bool\",\n \"name\": \"\",\n \"type\": \"bool\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"recoveryConfigs\",\n \"outputs\": [\n {\n \"internalType\": \"uint256\",\n \"name\": \"threshold\",\n \"type\": \"uint256\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"recoveryPeriod\",\n \"type\": \"uint256\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"recoveryNonces\",\n \"outputs\": [\n {\n \"internalType\": \"uint256\",\n \"name\": \"\",\n \"type\": \"uint256\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"wallet\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"bytes32\",\n \"name\": \"recoveryHash\",\n \"type\": \"bytes32\"\n }\n ],\n \"name\": \"revokeRecoveryApproval\",\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"wallet\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"address[]\",\n \"name\": \"guardians\",\n \"type\": \"address[]\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"threshold\",\n \"type\": \"uint256\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"recoveryPeriod\",\n \"type\": \"uint256\"\n }\n ],\n \"name\": \"setupRecovery\",\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n }\n ]\n}\n","{\n \"contractName\": \"MultiSendCallOnly\",\n \"abi\": [\n {\n \"inputs\": [],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"constructor\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"bytes\",\n \"name\": \"transactions\",\n \"type\": \"bytes\"\n }\n ],\n \"name\": \"multiSend\",\n \"outputs\": [],\n \"stateMutability\": \"payable\",\n \"type\": \"function\"\n }\n ]\n}\n","/**\n * QuaiVault contract ABIs.\n *\n * Generated from quaivault-contracts hardhat artifacts by `npm run sync-abis`.\n * Do not edit the JSON files by hand — CI checks them for drift.\n */\nimport QuaiVaultArtifact from './QuaiVault.json' with { type: 'json' };\nimport QuaiVaultFactoryArtifact from './QuaiVaultFactory.json' with { type: 'json' };\nimport QuaiVaultProxyArtifact from './QuaiVaultProxy.json' with { type: 'json' };\nimport SocialRecoveryModuleArtifact from './SocialRecoveryModule.json' with { type: 'json' };\nimport MultiSendCallOnlyArtifact from './MultiSendCallOnly.json' with { type: 'json' };\n\nimport type { InterfaceAbi } from 'quais';\n\nexport const QuaiVaultAbi = QuaiVaultArtifact.abi as InterfaceAbi;\nexport const QuaiVaultFactoryAbi = QuaiVaultFactoryArtifact.abi as InterfaceAbi;\nexport const QuaiVaultProxyAbi = QuaiVaultProxyArtifact.abi as InterfaceAbi;\nexport const SocialRecoveryModuleAbi = SocialRecoveryModuleArtifact.abi as InterfaceAbi;\nexport const MultiSendCallOnlyAbi = MultiSendCallOnlyArtifact.abi as InterfaceAbi;\n\n/**\n * QuaiVaultProxy creation bytecode.\n * Required to reproduce `QuaiVaultFactory.predictWalletAddress` off-chain, which\n * is what makes CREATE2 salt mining possible without an RPC round-trip per attempt.\n */\nexport const QuaiVaultProxyBytecode = QuaiVaultProxyArtifact.bytecode as string;\n\n/** Minimal ERC20 fragments used for balance reads and transfer encoding. */\nexport const Erc20Abi = [\n 'function name() view returns (string)',\n 'function symbol() view returns (string)',\n 'function decimals() view returns (uint8)',\n 'function balanceOf(address owner) view returns (uint256)',\n 'function allowance(address owner, address spender) view returns (uint256)',\n 'function transfer(address to, uint256 amount) returns (bool)',\n 'function approve(address spender, uint256 amount) returns (bool)',\n 'function transferFrom(address from, address to, uint256 amount) returns (bool)',\n] as const;\n\n/** Minimal ERC721 fragments. */\nexport const Erc721Abi = [\n 'function name() view returns (string)',\n 'function symbol() view returns (string)',\n 'function ownerOf(uint256 tokenId) view returns (address)',\n 'function balanceOf(address owner) view returns (uint256)',\n 'function tokenURI(uint256 tokenId) view returns (string)',\n 'function safeTransferFrom(address from, address to, uint256 tokenId)',\n 'function safeTransferFrom(address from, address to, uint256 tokenId, bytes data)',\n 'function setApprovalForAll(address operator, bool approved)',\n] as const;\n\n/** Minimal ERC1155 fragments. */\nexport const Erc1155Abi = [\n 'function balanceOf(address account, uint256 id) view returns (uint256)',\n 'function balanceOfBatch(address[] accounts, uint256[] ids) view returns (uint256[])',\n 'function uri(uint256 id) view returns (string)',\n 'function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes data)',\n 'function safeBatchTransferFrom(address from, address to, uint256[] ids, uint256[] amounts, bytes data)',\n 'function setApprovalForAll(address operator, bool approved)',\n] as const;\n","import type { DecodedRevert } from '../types.js';\n\n/** Machine-readable error codes. Stable across releases. */\nexport type QuaiVaultErrorCode =\n | 'ABORTED'\n | 'CONFIG'\n | 'NOT_CONNECTED'\n | 'NO_SIGNER'\n | 'NO_INDEXER'\n | 'INDEXER_QUERY'\n | 'INDEXER_STALE'\n | 'VALIDATION'\n | 'NOT_FOUND'\n | 'PRECONDITION'\n | 'REVERT'\n | 'SALT_MINING'\n | 'STALE_PROPOSAL'\n | 'UNSUPPORTED';\n\nexport class QuaiVaultError extends Error {\n readonly code: QuaiVaultErrorCode;\n /** What the caller can do about it, in plain language. */\n readonly remediation?: string;\n /** Unix seconds after which retrying could succeed. */\n readonly retryableAt?: number;\n override readonly cause?: unknown;\n\n constructor(\n code: QuaiVaultErrorCode,\n message: string,\n options: { remediation?: string; retryableAt?: number; cause?: unknown } = {},\n ) {\n super(message);\n this.name = new.target.name;\n this.code = code;\n this.remediation = options.remediation;\n this.retryableAt = options.retryableAt;\n this.cause = options.cause;\n }\n\n /** Structured form, for logs and machine consumers. */\n toJSON(): Record<string, unknown> {\n return {\n name: this.name,\n code: this.code,\n message: this.message,\n remediation: this.remediation,\n retryableAt: this.retryableAt,\n };\n }\n}\n\n/**\n * A caller-supplied `AbortSignal` fired.\n *\n * Every long-running operation the SDK exposes — retries, indexer polling, salt\n * mining, waiting for a timelock — accepts a signal, and each used to report abort\n * differently: a bare `Error('Aborted')` in two places, a `PreconditionError` in a\n * third. Consumers switching on `err.code` to distinguish \"the user pressed Ctrl-C\"\n * from \"this genuinely failed\" could not do so. They can now.\n */\nexport class AbortError extends QuaiVaultError {\n constructor(operation = 'The operation') {\n super('ABORTED', `${operation} was aborted.`);\n }\n}\n\nexport class ConfigError extends QuaiVaultError {\n constructor(message: string, remediation?: string) {\n super('CONFIG', message, { remediation });\n }\n}\n\nexport class NoSignerError extends QuaiVaultError {\n constructor(operation: string) {\n super('NO_SIGNER', `${operation} requires a signer.`, {\n remediation:\n 'Pass connect({ privateKey }) or connect({ signer }), or set QUAIVAULT_PRIVATE_KEY.',\n });\n }\n}\n\nexport class NoIndexerError extends QuaiVaultError {\n constructor(operation: string) {\n super('NO_INDEXER', `${operation} requires the indexer, which is not configured.`, {\n remediation:\n 'Set QUAIVAULT_INDEXER_URL, QUAIVAULT_INDEXER_ANON_KEY and QUAIVAULT_INDEXER_SCHEMA.',\n });\n }\n}\n\nexport class IndexerQueryError extends QuaiVaultError {\n constructor(message: string, cause?: unknown) {\n super('INDEXER_QUERY', message, { cause });\n }\n}\n\nexport class ValidationError extends QuaiVaultError {\n constructor(message: string, remediation?: string) {\n super('VALIDATION', message, { remediation });\n }\n}\n\nexport class NotFoundError extends QuaiVaultError {\n constructor(message: string) {\n super('NOT_FOUND', message);\n }\n}\n\n/** A precondition the contract enforces would fail — checked before signing. */\nexport class PreconditionError extends QuaiVaultError {\n constructor(message: string, options: { remediation?: string; retryableAt?: number } = {}) {\n super('PRECONDITION', message, options);\n }\n}\n\n/** A contract call reverted. Carries the decoded custom error when resolvable. */\nexport class RevertError extends QuaiVaultError {\n readonly revert?: DecodedRevert;\n\n constructor(message: string, revert?: DecodedRevert, options: { remediation?: string; cause?: unknown } = {}) {\n super('REVERT', message, options);\n this.revert = revert;\n }\n\n override toJSON(): Record<string, unknown> {\n return { ...super.toJSON(), revert: this.revert };\n }\n}\n\nexport class SaltMiningError extends QuaiVaultError {\n constructor(message: string, remediation?: string) {\n super('SALT_MINING', message, { remediation });\n }\n}\n\n/**\n * A `disableModule` proposal whose baked-in `prevModule` no longer matches the\n * live linked list. The proposal can never execute and must be replaced.\n */\nexport class StaleProposalError extends QuaiVaultError {\n constructor(message: string) {\n super('STALE_PROPOSAL', message, {\n remediation: 'Cancel this proposal and create a new one against the current module list.',\n });\n }\n}\n","import { isAddress } from 'quais';\nimport type {\n ClientOptions,\n Consistency,\n ContractAddresses,\n IndexerConfig,\n NetworkConfig,\n} from '../types.js';\nimport { ConfigError } from '../errors/index.js';\nimport type { RetryOptions } from '../chain/retry.js';\nimport { isNetworkName, networks } from './networks.js';\n\n/**\n * Environment variables read when `useEnv` is not disabled.\n *\n * Explicit `ClientOptions` always win over the environment; the environment always\n * wins over the network preset. Nothing here is read at module load — resolution\n * happens inside `connect()`, so importing the SDK never touches `process.env`.\n */\nexport const ENV_VARS = {\n network: 'QUAIVAULT_NETWORK',\n rpcUrl: 'QUAIVAULT_RPC_URL',\n privateKey: 'QUAIVAULT_PRIVATE_KEY',\n indexerUrl: 'QUAIVAULT_INDEXER_URL',\n indexerAnonKey: 'QUAIVAULT_INDEXER_ANON_KEY',\n indexerSchema: 'QUAIVAULT_INDEXER_SCHEMA',\n indexerHealthUrl: 'QUAIVAULT_INDEXER_HEALTH_URL',\n factory: 'QUAIVAULT_FACTORY',\n implementation: 'QUAIVAULT_IMPLEMENTATION',\n socialRecovery: 'QUAIVAULT_SOCIAL_RECOVERY_MODULE',\n multiSendCallOnly: 'QUAIVAULT_MULTISEND_CALL_ONLY',\n consistency: 'QUAIVAULT_CONSISTENCY',\n maxIndexerLagBlocks: 'QUAIVAULT_MAX_INDEXER_LAG_BLOCKS',\n} as const;\n\nexport interface ResolvedConfig {\n network: NetworkConfig;\n contracts: ContractAddresses;\n indexer?: IndexerConfig;\n rpcUrl: string;\n /**\n * ⚠️ Secret. Consumed once to build a signer and never retained afterwards.\n *\n * Never log or serialise a `ResolvedConfig` that still carries this — use\n * {@link redactConfig}, which is what `QuaiVaultClient.config` exposes.\n */\n privateKey?: string;\n consistency: Consistency;\n maxIndexerLagBlocks: number;\n retry: RetryOptions;\n}\n\n/** A `ResolvedConfig` with the private key removed. Safe to log. */\nexport type PublicConfig = Omit<ResolvedConfig, 'privateKey'> & { privateKey?: never };\n\n/**\n * Strip the private key so the config can be logged or serialised.\n *\n * Also masks the indexer key — it is public by design, but a full dump in logs\n * invites confusion about which credentials are sensitive.\n */\nexport function redactConfig(config: ResolvedConfig): PublicConfig {\n const { privateKey: _omitted, ...rest } = config;\n return {\n ...rest,\n ...(rest.indexer\n ? { indexer: { ...rest.indexer, anonKey: maskKey(rest.indexer.anonKey) } }\n : {}),\n // `network` carries its own copy of the indexer block; mask that one as well or\n // a config dump still prints the key in full.\n network: rest.network.indexer\n ? {\n ...rest.network,\n indexer: { ...rest.network.indexer, anonKey: maskKey(rest.network.indexer.anonKey) },\n }\n : rest.network,\n } as PublicConfig;\n}\n\nfunction maskKey(key: string): string {\n return key.length <= 12 ? '***' : `${key.slice(0, 8)}…${key.slice(-4)}`;\n}\n\ntype Env = Record<string, string | undefined>;\n\nfunction readEnv(useEnv: boolean): Env {\n if (!useEnv) return {};\n // `process` is absent in browsers and some edge runtimes — degrade to no env\n // rather than throwing, so the SDK stays isomorphic.\n const proc = (globalThis as { process?: { env?: Env } }).process;\n return proc?.env ?? {};\n}\n\nfunction pick<T>(...values: Array<T | undefined | ''>): T | undefined {\n for (const v of values) {\n if (v !== undefined && v !== '') return v as T;\n }\n return undefined;\n}\n\nfunction requireAddress(value: string | undefined, label: string, envVar: string): string {\n if (!value) {\n throw new ConfigError(\n `Missing ${label}. Set ${envVar} or pass it via connect({ contracts: { … } }).`,\n );\n }\n if (!isAddress(value)) {\n throw new ConfigError(`Invalid ${label}: \"${value}\" is not a valid address.`);\n }\n return value;\n}\n\nfunction optionalAddress(value: string | undefined, label: string): string | undefined {\n if (!value) return undefined;\n if (!isAddress(value)) {\n throw new ConfigError(`Invalid ${label}: \"${value}\" is not a valid address.`);\n }\n return value;\n}\n\nfunction parseConsistency(value: string | undefined): Consistency | undefined {\n if (value === undefined) return undefined;\n if (value === 'auto' || value === 'indexed' || value === 'chain') return value;\n throw new ConfigError(\n `Invalid consistency \"${value}\". Expected one of: auto, indexed, chain.`,\n );\n}\n\nfunction parseLag(value: string | undefined): number | undefined {\n if (value === undefined) return undefined;\n const n = Number(value);\n if (!Number.isFinite(n) || n < 0) {\n throw new ConfigError(`Invalid ${ENV_VARS.maxIndexerLagBlocks}: \"${value}\". Expected a non-negative number.`);\n }\n return n;\n}\n\n/**\n * Merge, in order of decreasing precedence: explicit options → environment →\n * network preset defaults.\n */\nexport function resolveConfig(options: ClientOptions = {}): ResolvedConfig {\n const env = readEnv(options.useEnv !== false);\n\n // --- network preset\n const networkInput = options.network ?? env[ENV_VARS.network] ?? 'mainnet';\n let base: NetworkConfig;\n if (typeof networkInput === 'string') {\n if (!isNetworkName(networkInput)) {\n throw new ConfigError(\n `Unknown network \"${networkInput}\". Built-in networks: ${Object.keys(networks).join(', ')}. ` +\n `Pass a full NetworkConfig object for a custom deployment.`,\n );\n }\n base = networks[networkInput];\n } else {\n base = networkInput;\n }\n\n // --- rpc\n const rpcUrl = pick(options.rpcUrl, env[ENV_VARS.rpcUrl], base.rpcUrl);\n if (!rpcUrl) {\n throw new ConfigError(`Missing RPC URL. Set ${ENV_VARS.rpcUrl} or pass connect({ rpcUrl }).`);\n }\n\n // --- contracts\n const contracts: ContractAddresses = {\n factory: requireAddress(\n pick(options.contracts?.factory, env[ENV_VARS.factory], base.contracts.factory),\n 'factory address',\n ENV_VARS.factory,\n ),\n implementation: requireAddress(\n pick(\n options.contracts?.implementation,\n env[ENV_VARS.implementation],\n base.contracts.implementation,\n ),\n 'implementation address',\n ENV_VARS.implementation,\n ),\n socialRecovery: optionalAddress(\n pick(options.contracts?.socialRecovery, env[ENV_VARS.socialRecovery], base.contracts.socialRecovery),\n 'social recovery module address',\n ),\n multiSendCallOnly: optionalAddress(\n pick(\n options.contracts?.multiSendCallOnly,\n env[ENV_VARS.multiSendCallOnly],\n base.contracts.multiSendCallOnly,\n ),\n 'MultiSendCallOnly address',\n ),\n };\n\n // --- indexer (optional: the SDK is fully usable chain-only)\n const indexerUrl = pick(options.indexer?.url, env[ENV_VARS.indexerUrl], base.indexer?.url);\n const anonKey = pick(options.indexer?.anonKey, env[ENV_VARS.indexerAnonKey], base.indexer?.anonKey);\n const schema = pick(options.indexer?.schema, env[ENV_VARS.indexerSchema], base.indexer?.schema);\n\n let indexer: IndexerConfig | undefined;\n if (indexerUrl && anonKey && schema) {\n indexer = {\n url: indexerUrl,\n anonKey,\n schema,\n healthUrl: pick(\n options.indexer?.healthUrl,\n env[ENV_VARS.indexerHealthUrl],\n base.indexer?.healthUrl,\n ),\n };\n }\n\n const consistency =\n options.consistency ?? parseConsistency(env[ENV_VARS.consistency]) ?? 'auto';\n\n // Without an indexer, 'auto' degrades to chain-only reads; 'indexed' is a\n // configuration error the caller should hear about now rather than at first query.\n if (!indexer && consistency === 'indexed') {\n throw new ConfigError(\n `consistency: 'indexed' requires indexer configuration. ` +\n `Set ${ENV_VARS.indexerUrl}, ${ENV_VARS.indexerAnonKey} and ${ENV_VARS.indexerSchema}.`,\n );\n }\n\n return {\n network: { ...base, rpcUrl, contracts, ...(indexer ? { indexer } : {}) },\n contracts,\n indexer,\n rpcUrl,\n // An explicit signer wins outright in `Connection`, so resolving a key here would\n // only pull a secret into memory that nothing can use. Skip it.\n privateKey: options.signer ? undefined : pick(options.privateKey, env[ENV_VARS.privateKey]),\n consistency,\n maxIndexerLagBlocks:\n options.maxIndexerLagBlocks ?? parseLag(env[ENV_VARS.maxIndexerLagBlocks]) ?? 50,\n retry: {\n ...(options.retry?.maxAttempts != null ? { maxAttempts: options.retry.maxAttempts } : {}),\n ...(options.retry?.baseDelayMs != null ? { baseDelayMs: options.retry.baseDelayMs } : {}),\n ...(options.retry?.maxDelayMs != null ? { maxDelayMs: options.retry.maxDelayMs } : {}),\n ...(options.retry?.onRetry ? { onRetry: options.retry.onRetry } : {}),\n },\n };\n}\n","import type { NetworkConfig } from '../types.js';\n\n/**\n * Built-in network presets.\n *\n * Contract addresses track the deployments recorded in quaivault-www/contracts.md.\n *\n * The indexer credentials ship with the SDK so it works out of the box. The\n * publishable key is a public, read-only credential: the indexer's RLS grants the\n * `anon` role `SELECT` on every table and nothing else, with all writes reserved for\n * `service_role`. It exposes only chain data that is already public.\n *\n * Override any of it with `QUAIVAULT_INDEXER_URL` / `_ANON_KEY` / `_SCHEMA`, or with\n * `connect({ indexer: { … } })` — needed if the key is ever rotated ahead of an SDK\n * release, or to point at a self-hosted indexer.\n */\n\nconst INDEXER_URL = 'https://xbftgyuxaxagptudledv.supabase.co';\n\n/** Public, read-only Supabase publishable key. Safe to distribute — see above. */\nconst INDEXER_PUBLISHABLE_KEY = 'sb_publishable_EO-sTB-jqUzlsiugOEks-Q_qRtHDaHU';\n\nexport const mainnet: NetworkConfig = {\n name: 'mainnet',\n chainId: 9,\n rpcUrl: 'https://rpc.quai.network',\n explorerUrl: 'https://quaiscan.io',\n contracts: {\n implementation: '0x0038E6d84412A10CdcE41b0f62A05350023f1fb6',\n factory: '0x003613aC5FFd45bFF7B2F0210DA2fF660908c488',\n socialRecovery: '0x000dbc29Bdd311C29a4008164052fc2E67c0D937',\n multiSendCallOnly: '0x003f62e6a7f2EB6b94345a9A41671888eC4A3ebA',\n },\n indexer: {\n url: INDEXER_URL,\n anonKey: INDEXER_PUBLISHABLE_KEY,\n schema: 'mainnet',\n healthUrl: 'https://index.quaivault.org',\n },\n};\n\nexport const testnet: NetworkConfig = {\n name: 'testnet',\n chainId: 15000,\n // Orchard moved from rpc.orchard.quai.network (now NXDOMAIN) to this hostname.\n rpcUrl: 'https://orchard.rpc.quai.network',\n explorerUrl: 'https://orchard.quaiscan.io',\n contracts: {\n implementation: '0x004E539Cf477A5Cb456A56023f083cD91Bc4934e',\n factory: '0x002d1305D597c157bB975967FA2e5337674b0E5F',\n socialRecovery: '0x003a465e661D0E44C1e78b7B256D8C37f699E61e',\n multiSendCallOnly: '0x002ae8A47C2da497fe569AfCF0486410aA1093E0',\n },\n indexer: {\n url: INDEXER_URL,\n anonKey: INDEXER_PUBLISHABLE_KEY,\n schema: 'testnet',\n healthUrl: 'https://index.devnet.quaivault.org',\n },\n};\n\nexport const networks = { mainnet, testnet } as const;\n\nexport type NetworkName = keyof typeof networks;\n\nexport function isNetworkName(value: unknown): value is NetworkName {\n return typeof value === 'string' && value in networks;\n}\n","import { Interface, getAddress } from 'quais';\nimport { assertQuaiAddress, assertQuaiAddresses } from './address.js';\nimport { QuaiVaultFactoryAbi } from './abi/index.js';\nimport type { Connection } from './chain/connection.js';\nimport { FactoryContract } from './chain/vault-contract.js';\nimport { PreconditionError, RevertError, ValidationError } from './errors/index.js';\nimport { decodeRevertFromError } from './errors/decode.js';\nimport {\n MAX_EXECUTION_DELAY,\n MAX_MODULES,\n MAX_OWNERS,\n SENTINEL_MODULES,\n ZERO_ADDRESS,\n} from './encode/index.js';\nimport type { ReceiptLike } from './lifecycle/outcome.js';\nimport { mineSalt, type MineSaltOptions, type MiningStrategy } from './salt/mine.js';\nimport { predictVaultAddress } from './salt/predict.js';\nimport type {\n Address,\n Bytes32,\n ContractAddresses,\n CreateVaultParams,\n CreateVaultResult,\n Hex,\n MinedSalt,\n} from './types.js';\n\nconst factoryInterface = new Interface(QuaiVaultFactoryAbi);\n\nexport interface CreateProgress {\n step: 'validating' | 'mining' | 'deploying' | 'confirming' | 'done';\n message: string;\n attempts?: number;\n predictedAddress?: Address;\n chainTxHash?: Hex;\n}\n\nexport interface FactoryContext {\n connection: Connection;\n contracts: ContractAddresses;\n}\n\n/** Deploy and look up vaults through `QuaiVaultFactory`. */\nexport class Factory {\n constructor(private readonly ctx: FactoryContext) {}\n\n get address(): Address {\n return this.ctx.contracts.factory;\n }\n\n private contract(write = false): FactoryContract {\n return new FactoryContract(this.ctx.connection.factory(this.address, write), this.ctx.connection.retry);\n }\n\n /** The implementation every proxy from this factory delegates to. */\n async implementation(): Promise<Address> {\n return getAddress(await this.contract().implementation());\n }\n\n /** Whether the factory has this vault in its registry. */\n async isRegistered(vault: Address): Promise<boolean> {\n return this.contract().isWallet(getAddress(vault));\n }\n\n async vaultCount(): Promise<number> {\n return Number(await this.contract().getWalletCount());\n }\n\n async vaultAt(index: number): Promise<Address> {\n return getAddress(await this.contract().deployedWallets(index));\n }\n\n /**\n * Verify the configured implementation address matches what the factory reports.\n *\n * A mismatch means salt mining will predict addresses the factory will not deploy\n * to, so it is worth catching before a deployment rather than after.\n */\n async verify(): Promise<{ valid: boolean; errors: string[] }> {\n const errors: string[] = [];\n try {\n const onChain = await this.implementation();\n if (onChain.toLowerCase() !== this.ctx.contracts.implementation.toLowerCase()) {\n errors.push(\n `Configured implementation ${this.ctx.contracts.implementation} does not match the ` +\n `factory's ${onChain}. Address prediction and salt mining will be wrong.`,\n );\n }\n const code = await this.ctx.connection.provider.getCode(onChain);\n if (code === '0x') errors.push(`No contract code at implementation ${onChain}.`);\n } catch (err) {\n errors.push(\n `Could not reach the factory at ${this.address}: ` +\n (err instanceof Error ? err.message : String(err)),\n );\n }\n return { valid: errors.length === 0, errors };\n }\n\n /** Off-chain CREATE2 prediction. Identical to `factory.predictWalletAddress`. */\n predictAddress(deployer: Address, salt: Bytes32, params: CreateVaultParams): Address {\n validateCreateParams(params);\n return predictVaultAddress({\n factory: this.address,\n implementation: this.ctx.contracts.implementation,\n deployer: getAddress(deployer),\n salt,\n params,\n });\n }\n\n /**\n * Mine a CREATE2 salt placing the vault on the deployer's shard.\n *\n * Quai addresses are shard-scoped, so an arbitrary salt usually produces a vault\n * the deployer cannot reach. The mined salt is only valid for these exact create\n * params — changing owners, threshold, delay, modules or delegatecall targets\n * changes the predicted address.\n */\n async mineSalt(\n params: CreateVaultParams,\n options: Partial<Omit<MineSaltOptions, 'factory' | 'implementation' | 'params'>> = {},\n strategy?: MiningStrategy,\n ): Promise<MinedSalt> {\n validateCreateParams(params);\n const deployer = options.deployer ?? (await this.ctx.connection.address());\n return mineSalt(\n {\n factory: this.address,\n implementation: this.ctx.contracts.implementation,\n deployer: getAddress(deployer),\n params,\n ...options,\n },\n strategy,\n );\n }\n\n /**\n * Deploy a vault, mining a salt first when one is not supplied.\n *\n * Always uses the 6-argument `createWallet` overload so the deployed bytecode\n * matches what mining predicted, whatever combination of modules and delegatecall\n * targets is requested.\n */\n async create(\n params: CreateVaultParams,\n options: {\n onProgress?: (progress: CreateProgress) => void;\n miningStrategy?: MiningStrategy;\n maxAttempts?: number;\n timeoutMs?: number;\n } = {},\n ): Promise<CreateVaultResult> {\n const { onProgress } = options;\n validateCreateParams(params);\n\n onProgress?.({ step: 'validating', message: 'Checking factory configuration…' });\n const verification = await this.verify();\n if (!verification.valid) {\n throw new PreconditionError(verification.errors.join(' '), {\n remediation: 'Check the configured factory and implementation addresses for this network.',\n });\n }\n\n const deployer = getAddress(await this.ctx.connection.address());\n\n let salt = params.salt;\n let predictedAddress: Address | undefined;\n\n if (salt) {\n predictedAddress = this.predictAddress(deployer, salt, params);\n } else {\n onProgress?.({ step: 'mining', message: 'Mining a salt for your shard…' });\n const mined = await this.mineSalt(\n params,\n {\n deployer,\n ...(options.maxAttempts != null ? { maxAttempts: options.maxAttempts } : {}),\n ...(options.timeoutMs != null ? { timeoutMs: options.timeoutMs } : {}),\n onProgress: (attempts) =>\n onProgress?.({ step: 'mining', message: `Mining… ${attempts} attempts`, attempts }),\n },\n options.miningStrategy,\n );\n salt = mined.salt;\n predictedAddress = mined.predictedAddress;\n onProgress?.({\n step: 'mining',\n message: `Found ${mined.predictedAddress} after ${mined.attempts} attempts`,\n attempts: mined.attempts,\n predictedAddress: mined.predictedAddress,\n });\n }\n\n onProgress?.({ step: 'deploying', message: 'Submitting the deployment…', predictedAddress });\n\n const factory = this.contract(true);\n let receipt: ReceiptLike;\n let chainTxHash: Hex;\n try {\n const sent = await factory.createWallet(\n params.owners.map((o) => getAddress(o)),\n params.threshold,\n salt,\n params.minExecutionDelay ?? 0,\n (params.initialModules ?? []).map((m) => getAddress(m)),\n (params.initialDelegatecallTargets ?? []).map((t) => getAddress(t)),\n );\n chainTxHash = sent.hash as Hex;\n onProgress?.({ step: 'confirming', message: 'Waiting for confirmation…', chainTxHash });\n receipt = (await sent.wait()) as ReceiptLike;\n } catch (err) {\n const decoded = decodeRevertFromError(err);\n throw new RevertError(\n `Vault creation failed${decoded ? `: ${decoded.message}` : ''}`,\n decoded,\n { cause: err },\n );\n }\n\n if (!receipt || receipt.status === 0) {\n throw new RevertError('The deployment transaction reverted.');\n }\n\n const address = extractCreatedVault(receipt, this.address);\n if (!address) {\n throw new RevertError(\n 'The deployment was mined but no WalletCreated event was found.',\n );\n }\n\n onProgress?.({ step: 'done', message: `Vault deployed at ${address}`, chainTxHash });\n\n return {\n address,\n chainTxHash,\n salt,\n predictionMatched:\n predictedAddress !== undefined &&\n predictedAddress.toLowerCase() === address.toLowerCase(),\n };\n }\n\n /** Register an externally deployed proxy. Callable only by one of its owners. */\n async register(vault: Address): Promise<{ chainTxHash: Hex }> {\n const factory = this.contract(true);\n try {\n const sent = await factory.registerWallet(getAddress(vault));\n const receipt = (await sent.wait()) as ReceiptLike;\n if (!receipt || receipt.status === 0) {\n throw new RevertError('Registration reverted.');\n }\n return { chainTxHash: (receipt.hash ?? receipt.transactionHash ?? '') as Hex };\n } catch (err) {\n if (err instanceof RevertError) throw err;\n const decoded = decodeRevertFromError(err);\n throw new RevertError(\n `Registering the vault failed${decoded ? `: ${decoded.message}` : ''}`,\n decoded,\n { cause: err },\n );\n }\n }\n}\n\nfunction validateCreateParams(params: CreateVaultParams): void {\n const { owners, threshold } = params;\n\n if (!Array.isArray(owners) || owners.length === 0) {\n throw new ValidationError('At least one owner is required.');\n }\n if (owners.length > MAX_OWNERS) {\n throw new ValidationError(`A vault may have at most ${MAX_OWNERS} owners (got ${owners.length}).`);\n }\n const seen = new Set<string>();\n owners.forEach((owner, i) => {\n // Rejects Qi-ledger and zone-less addresses: an owner that cannot sign is dead\n // weight against the threshold, and enough of them brick the vault. The contract\n // only guards the zero address, the vault itself and the module sentinel.\n assertQuaiAddress(owner, `owner[${i}]`);\n const key = owner.toLowerCase();\n if (key === ZERO_ADDRESS || key === SENTINEL_MODULES) {\n throw new ValidationError(\n `Owner ${owner} is reserved — the zero address and the module sentinel 0x…01 are rejected.`,\n );\n }\n if (seen.has(key)) throw new ValidationError(`Duplicate owner: ${owner}.`);\n seen.add(key);\n });\n\n if (params.initialModules?.length) {\n if (params.initialModules.length > MAX_MODULES) {\n throw new ValidationError(\n `A vault may have at most ${MAX_MODULES} modules (got ${params.initialModules.length}).`,\n );\n }\n assertQuaiAddresses(params.initialModules, 'initialModules');\n }\n if (params.initialDelegatecallTargets?.length) {\n assertQuaiAddresses(params.initialDelegatecallTargets, 'initialDelegatecallTargets');\n }\n if (!Number.isInteger(threshold) || threshold < 1 || threshold > owners.length) {\n throw new ValidationError(\n `Invalid threshold ${threshold}: must be an integer between 1 and ${owners.length}.`,\n );\n }\n const delay = params.minExecutionDelay ?? 0;\n if (!Number.isInteger(delay) || delay < 0 || delay > MAX_EXECUTION_DELAY) {\n throw new ValidationError(\n `Invalid minExecutionDelay ${delay}: must be between 0 and ${MAX_EXECUTION_DELAY} seconds (30 days).`,\n );\n }\n}\n\n/** Pull the vault address out of the factory's `WalletCreated` event. */\nfunction extractCreatedVault(receipt: ReceiptLike, factoryAddress: string): Address | null {\n const target = factoryAddress.toLowerCase();\n for (const log of receipt.logs ?? []) {\n if (log.address && log.address.toLowerCase() !== target) continue;\n try {\n const parsed = factoryInterface.parseLog({\n topics: Array.from(log.topics),\n data: log.data,\n });\n if (parsed?.name === 'WalletCreated') {\n return getAddress(String(parsed.args[0]));\n }\n } catch {\n continue;\n }\n }\n return null;\n}\n","import { getAddress, getZoneForAddress, isAddress, isQiAddress } from 'quais';\nimport { ValidationError } from './errors/index.js';\nimport type { Address } from './types.js';\n\n/**\n * Address validation for Quai's dual-ledger, sharded address space.\n *\n * Two independent properties are encoded in a Quai address:\n *\n * - **Zone** — the first byte (`0x00`–`0x02`, `0x10`–`0x12`, `0x20`–`0x22`). An address\n * outside those ranges belongs to no shard and cannot hold state.\n * - **Ledger** — the 9th bit, i.e. the high bit of the *second* byte. Set means Qi (the\n * UTXO ledger); clear means Quai (the EVM account ledger).\n *\n * They are genuinely orthogonal: `0x008111…` sits in zone `0x00` yet is a Qi address, so\n * a zone check alone is not enough.\n *\n * **Qi addresses cannot interact with smart contracts.** A Qi owner could never sign a\n * vault transaction, a Qi guardian could never approve a recovery, and native value sent\n * to one leaves the Quai ledger. The contracts do not check for this — `_addOwner` only\n * rejects the zero address, the vault itself and the module sentinel — so admitting one\n * permanently reduces the number of addresses able to reach the threshold, and enough of\n * them bricks the vault. The SDK therefore rejects Qi addresses wherever an address is\n * committed to a role or receives value.\n */\n\nexport type AddressLedger = 'quai' | 'qi';\n\nexport interface AddressCheck {\n valid: boolean;\n checksummed?: Address;\n /** Zone prefix, e.g. `0x00`. Absent when the address belongs to no shard. */\n zone?: string;\n ledger?: AddressLedger;\n reason?: string;\n}\n\n/** Inspect an address without throwing. */\nexport function inspectAddress(value: unknown): AddressCheck {\n if (typeof value !== 'string' || !isAddress(value)) {\n return { valid: false, reason: 'not a valid address' };\n }\n const checksummed = getAddress(value);\n const zone = getZoneForAddress(checksummed);\n const ledger: AddressLedger = isQiAddress(checksummed) ? 'qi' : 'quai';\n\n if (!zone) {\n return {\n valid: false,\n checksummed,\n ledger,\n reason: 'belongs to no Quai shard (its leading byte is not a valid zone prefix)',\n };\n }\n if (ledger === 'qi') {\n return {\n valid: false,\n checksummed,\n zone,\n ledger,\n reason: 'is a Qi-ledger address, which cannot interact with smart contracts on Quai',\n };\n }\n return { valid: true, checksummed, zone, ledger };\n}\n\n/** Whether an address is shard-valid and on the Quai ledger. */\nexport function isUsableQuaiAddress(value: unknown): boolean {\n return inspectAddress(value).valid;\n}\n\n/**\n * Assert an address can participate in Quai smart-contract calls, returning it\n * checksummed.\n *\n * Use for any address being committed to a role (owner, guardian, module, delegatecall\n * target) or receiving value. Do **not** use it for addresses being *removed* — a Qi\n * address that predates this check must still be removable — nor for read-only lookups,\n * where rejecting the query is less useful than answering it.\n */\nexport function assertQuaiAddress(value: unknown, label = 'address'): Address {\n const check = inspectAddress(value);\n if (check.valid) return check.checksummed as Address;\n\n const shown = typeof value === 'string' ? value : String(value);\n const remediation =\n check.ledger === 'qi'\n ? 'Qi is the UTXO ledger and has no contract execution. Use a Quai-ledger address ' +\n '(the 9th bit of the address — the high bit of its second byte — must be clear).'\n : 'Quai addresses must begin with a valid zone prefix: 0x00–0x02, 0x10–0x12, or 0x20–0x22.';\n\n throw new ValidationError(`Invalid ${label} \"${shown}\": it ${check.reason}.`, remediation);\n}\n\n/** Assert every address in a list, reporting the offending index. */\nexport function assertQuaiAddresses(values: readonly unknown[], label: string): Address[] {\n return values.map((value, i) => assertQuaiAddress(value, `${label}[${i}]`));\n}\n","/**\n * Retry policy for transient RPC and indexer failures.\n *\n * Scoped deliberately to **reads**. Retrying a write risks broadcasting the same\n * transaction twice — a resubmit that looks like a timeout to the client may already\n * be in the mempool — so every write path in this SDK calls through unretried.\n */\nimport { AbortError } from '../errors/index.js';\n\nexport interface RetryOptions {\n /** Total attempts including the first. Default 3. */\n maxAttempts?: number;\n /** First backoff delay. Doubles each attempt. Default 250ms. */\n baseDelayMs?: number;\n /** Ceiling on any single backoff. Default 4000ms. */\n maxDelayMs?: number;\n signal?: AbortSignal;\n onRetry?: (info: { attempt: number; delayMs: number; error: unknown }) => void;\n}\n\nconst DEFAULTS = {\n maxAttempts: 3,\n baseDelayMs: 250,\n maxDelayMs: 4_000,\n} as const;\n\n/**\n * Error codes `quais` raises that reflect a deterministic outcome, not a blip.\n * Retrying these can only produce the same answer more slowly.\n */\nconst PERMANENT_CODES = new Set([\n 'CALL_EXCEPTION', // the call reverted — deterministic\n 'INVALID_ARGUMENT',\n 'MISSING_ARGUMENT',\n 'UNEXPECTED_ARGUMENT',\n 'NOT_IMPLEMENTED',\n 'UNSUPPORTED_OPERATION',\n 'ACTION_REJECTED', // the user declined in their wallet\n 'NONCE_EXPIRED',\n 'INSUFFICIENT_FUNDS',\n 'REPLACEMENT_UNDERPRICED',\n 'TRANSACTION_REPLACED',\n 'VALUE_MISMATCH',\n]);\n\n/** Codes that usually clear on their own. */\nconst TRANSIENT_CODES = new Set(['NETWORK_ERROR', 'SERVER_ERROR', 'TIMEOUT', 'BAD_DATA']);\n\n/** Substrings seen in raw transport failures that carry no structured code. */\nconst TRANSIENT_PATTERNS = [\n 'fetch failed',\n 'econnreset',\n 'econnrefused',\n 'etimedout',\n 'epipe',\n 'socket hang up',\n 'network error',\n 'timeout',\n 'timed out',\n 'rate limit',\n 'too many requests',\n 'service unavailable',\n 'bad gateway',\n 'gateway timeout',\n 'temporarily unavailable',\n 'connection terminated',\n 'server error',\n];\n\n/** HTTP statuses worth another attempt. */\nconst TRANSIENT_STATUS = new Set([408, 425, 429, 500, 502, 503, 504]);\n\nfunction statusOf(error: unknown): number | undefined {\n if (typeof error !== 'object' || error === null) return undefined;\n const e = error as Record<string, unknown>;\n for (const key of ['status', 'statusCode']) {\n const value = e[key];\n if (typeof value === 'number') return value;\n }\n // quais nests the transport response under `info`\n const info = e.info as Record<string, unknown> | undefined;\n const response = info?.response as Record<string, unknown> | undefined;\n if (typeof response?.status === 'number') return response.status;\n return undefined;\n}\n\n/**\n * Whether an error is worth retrying.\n *\n * Errs toward *not* retrying: an unrecognised error is treated as permanent, so a\n * genuine bug surfaces immediately instead of being masked by three slow attempts.\n */\nexport function isTransient(error: unknown): boolean {\n if (error === null || error === undefined) return false;\n\n const code = (error as { code?: unknown }).code;\n if (typeof code === 'string') {\n if (PERMANENT_CODES.has(code)) return false;\n if (TRANSIENT_CODES.has(code)) return true;\n }\n\n const status = statusOf(error);\n if (status !== undefined) return TRANSIENT_STATUS.has(status);\n\n const message = error instanceof Error ? error.message : String(error);\n const haystack = message.toLowerCase();\n if (TRANSIENT_PATTERNS.some((p) => haystack.includes(p))) return true;\n\n // Unwrap one level — quais commonly wraps the transport error.\n const cause = (error as { cause?: unknown }).cause;\n if (cause && cause !== error) return isTransient(cause);\n\n return false;\n}\n\nconst sleep = (ms: number, signal?: AbortSignal): Promise<void> =>\n new Promise((resolve, reject) => {\n if (signal?.aborted) {\n reject(new AbortError('Waiting to retry'));\n return;\n }\n const timer = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort);\n resolve();\n }, ms);\n const onAbort = () => {\n clearTimeout(timer);\n reject(new AbortError('Waiting to retry'));\n };\n signal?.addEventListener('abort', onAbort, { once: true });\n });\n\n/**\n * Run `fn`, retrying transient failures with exponential backoff and full jitter.\n *\n * Jitter matters more than usual here: several vaults refreshing on the same tick\n * would otherwise retry in lockstep and hammer a rate-limited endpoint in waves.\n */\nexport async function withRetry<T>(fn: () => Promise<T>, options: RetryOptions = {}): Promise<T> {\n const maxAttempts = options.maxAttempts ?? DEFAULTS.maxAttempts;\n const baseDelayMs = options.baseDelayMs ?? DEFAULTS.baseDelayMs;\n const maxDelayMs = options.maxDelayMs ?? DEFAULTS.maxDelayMs;\n\n let lastError: unknown;\n\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n if (options.signal?.aborted) throw new AbortError('The retried operation');\n try {\n return await fn();\n } catch (error) {\n lastError = error;\n if (attempt === maxAttempts || !isTransient(error)) throw error;\n\n const ceiling = Math.min(baseDelayMs * 2 ** (attempt - 1), maxDelayMs);\n const delayMs = Math.round(Math.random() * ceiling);\n options.onRetry?.({ attempt, delayMs, error });\n await sleep(delayMs, options.signal);\n }\n }\n\n throw lastError;\n}\n","import type { Contract } from 'quais';\nimport { withRetry, type RetryOptions } from './retry.js';\nimport type { Address, Bytes32, Hex } from '../types.js';\n\n/**\n * Raw `Transaction` struct as returned by `QuaiVault.transactions(bytes32)`.\n * Field names match the Solidity struct.\n */\nexport interface RawTransactionStruct {\n to: string;\n timestamp: bigint;\n expiration: bigint;\n proposer: string;\n executed: boolean;\n cancelled: boolean;\n approvedAt: bigint;\n executionDelay: bigint;\n value: bigint;\n data: string;\n}\n\n/**\n * Typed facade over the generated `Contract`.\n *\n * `quais` types its dynamic method accessor as possibly-undefined and cannot\n * disambiguate overloads by arity, so every call here goes through `getFunction`\n * with an explicit signature. Keeping that in one place means callers get real\n * types and overload selection is stated once, next to the ABI it depends on.\n */\nexport class VaultContract {\n constructor(\n readonly contract: Contract,\n private readonly retry: RetryOptions = {},\n ) {}\n\n private fn(signature: string) {\n return this.contract.getFunction(signature);\n }\n\n /**\n * Reads retry transient RPC failures (see {@link withRetry}); writes never do,\n * because a resubmit that looks like a timeout may already be in the mempool.\n */\n private read<T>(signature: string, ...args: unknown[]): Promise<T> {\n return withRetry(() => this.fn(signature)(...args) as Promise<T>, this.retry);\n }\n\n get interface() {\n return this.contract.interface;\n }\n\n // ---- reads ---------------------------------------------------------------\n\n getOwners(): Promise<string[]> {\n return this.read<string[]>('getOwners()');\n }\n\n isOwner(address: Address): Promise<boolean> {\n return this.read<boolean>('isOwner(address)', address);\n }\n\n threshold(): Promise<bigint> {\n return this.read<bigint>('threshold()');\n }\n\n nonce(): Promise<bigint> {\n return this.read<bigint>('nonce()');\n }\n\n minExecutionDelay(): Promise<bigint> {\n return this.read<bigint>('minExecutionDelay()');\n }\n\n moduleCount(): Promise<bigint> {\n return this.read<bigint>('moduleCount()');\n }\n\n getModules(): Promise<string[]> {\n return this.read<string[]>('getModules()');\n }\n\n isModuleEnabled(module: Address): Promise<boolean> {\n return this.read<boolean>('isModuleEnabled(address)', module);\n }\n\n delegatecallAllowed(target: Address): Promise<boolean> {\n return this.read<boolean>('delegatecallAllowed(address)', target);\n }\n\n transactions(txHash: Bytes32): Promise<RawTransactionStruct> {\n return this.read<RawTransactionStruct>('transactions(bytes32)', txHash);\n }\n\n /**\n * Whether an owner's approval currently counts toward the threshold.\n * Accounts for approval-epoch invalidation from owner removal.\n */\n hasApproved(txHash: Bytes32, owner: Address): Promise<boolean> {\n return this.read<boolean>('hasApproved(bytes32,address)', txHash, owner);\n }\n\n /** True when the transaction was closed by `expireTransaction`, not cancelled. */\n expiredTxs(txHash: Bytes32): Promise<boolean> {\n return this.read<boolean>('expiredTxs(bytes32)', txHash);\n }\n\n getTransactionHash(to: Address, value: bigint, data: Hex, nonce: number | bigint): Promise<Bytes32> {\n return this.read<Bytes32>(\n 'getTransactionHash(address,uint256,bytes,uint256)',\n to, value, data, nonce,\n );\n }\n\n isValidSignature(hash: Bytes32, signature: Hex): Promise<string> {\n return this.read<string>('isValidSignature(bytes32,bytes)', hash, signature);\n }\n\n // ---- writes --------------------------------------------------------------\n\n /**\n * Overload with expiration and delay. The 3-argument overload is used when\n * neither is supplied, so a caller that wants no expiry never has to pass 0.\n */\n proposeTransactionFull(\n to: Address,\n value: bigint,\n data: Hex,\n expiration: number,\n executionDelay: number,\n ): Promise<ContractTransactionResponse> {\n return this.fn('proposeTransaction(address,uint256,bytes,uint48,uint32)')(\n to,\n value,\n data,\n expiration,\n executionDelay,\n ) as Promise<ContractTransactionResponse>;\n }\n\n proposeTransactionSimple(\n to: Address,\n value: bigint,\n data: Hex,\n ): Promise<ContractTransactionResponse> {\n return this.fn('proposeTransaction(address,uint256,bytes)')(\n to,\n value,\n data,\n ) as Promise<ContractTransactionResponse>;\n }\n\n approveTransaction(txHash: Bytes32): Promise<ContractTransactionResponse> {\n return this.fn('approveTransaction(bytes32)')(txHash) as Promise<ContractTransactionResponse>;\n }\n\n approveAndExecute(txHash: Bytes32): Promise<ContractTransactionResponse> {\n return this.fn('approveAndExecute(bytes32)')(txHash) as Promise<ContractTransactionResponse>;\n }\n\n executeTransaction(txHash: Bytes32): Promise<ContractTransactionResponse> {\n return this.fn('executeTransaction(bytes32)')(txHash) as Promise<ContractTransactionResponse>;\n }\n\n revokeApproval(txHash: Bytes32): Promise<ContractTransactionResponse> {\n return this.fn('revokeApproval(bytes32)')(txHash) as Promise<ContractTransactionResponse>;\n }\n\n cancelTransaction(txHash: Bytes32): Promise<ContractTransactionResponse> {\n return this.fn('cancelTransaction(bytes32)')(txHash) as Promise<ContractTransactionResponse>;\n }\n\n expireTransaction(txHash: Bytes32): Promise<ContractTransactionResponse> {\n return this.fn('expireTransaction(bytes32)')(txHash) as Promise<ContractTransactionResponse>;\n }\n\n encode(signature: string, args: unknown[]): Hex {\n return this.contract.interface.encodeFunctionData(signature, args) as Hex;\n }\n}\n\n/** Minimal shape of a sent transaction — enough to await a receipt. */\nexport interface ContractTransactionResponse {\n hash: string;\n wait(confirmations?: number): Promise<unknown>;\n}\n\n/** Typed facade over `QuaiVaultFactory`. */\nexport class FactoryContract {\n constructor(\n readonly contract: Contract,\n private readonly retry: RetryOptions = {},\n ) {}\n\n private fn(signature: string) {\n return this.contract.getFunction(signature);\n }\n\n /**\n * Reads retry transient RPC failures (see {@link withRetry}); writes never do,\n * because a resubmit that looks like a timeout may already be in the mempool.\n */\n private read<T>(signature: string, ...args: unknown[]): Promise<T> {\n return withRetry(() => this.fn(signature)(...args) as Promise<T>, this.retry);\n }\n\n get interface() {\n return this.contract.interface;\n }\n\n implementation(): Promise<string> {\n return this.read<string>('implementation()');\n }\n\n isWallet(address: Address): Promise<boolean> {\n return this.read<boolean>('isWallet(address)', address);\n }\n\n getWalletCount(): Promise<bigint> {\n return this.read<bigint>('getWalletCount()');\n }\n\n deployedWallets(index: number | bigint): Promise<string> {\n return this.read<string>('deployedWallets(uint256)', index);\n }\n\n predictWalletAddress(\n deployer: Address,\n salt: Bytes32,\n owners: Address[],\n threshold: number,\n minExecutionDelay: number,\n initialModules: Address[],\n initialDelegatecallTargets: Address[],\n ): Promise<string> {\n return this.read<string>(\n 'predictWalletAddress(address,bytes32,address[],uint256,uint32,address[],address[])',\n deployer,\n salt,\n owners,\n threshold,\n minExecutionDelay,\n initialModules,\n initialDelegatecallTargets,\n );\n }\n\n /** Full 6-argument overload. The SDK always uses it so mining stays consistent. */\n createWallet(\n owners: Address[],\n threshold: number,\n salt: Bytes32,\n minExecutionDelay: number,\n initialModules: Address[],\n initialDelegatecallTargets: Address[],\n ): Promise<ContractTransactionResponse> {\n return this.fn('createWallet(address[],uint256,bytes32,uint32,address[],address[])')(\n owners,\n threshold,\n salt,\n minExecutionDelay,\n initialModules,\n initialDelegatecallTargets,\n ) as Promise<ContractTransactionResponse>;\n }\n\n registerWallet(wallet: Address): Promise<ContractTransactionResponse> {\n return this.fn('registerWallet(address)')(wallet) as Promise<ContractTransactionResponse>;\n }\n}\n","import { Interface, AbiCoder } from 'quais';\nimport type { ErrorFragment } from 'quais';\nimport {\n QuaiVaultAbi,\n QuaiVaultFactoryAbi,\n SocialRecoveryModuleAbi,\n QuaiVaultProxyAbi,\n} from '../abi/index.js';\nimport { sanitizeText } from '../text.js';\nimport type { DecodedRevert, Hex } from '../types.js';\n\nconst SOLIDITY_ERROR_SELECTOR = '0x08c379a0'; // Error(string)\nconst SOLIDITY_PANIC_SELECTOR = '0x4e487b71'; // Panic(uint256)\n\n/**\n * Cap for revert text rendered into {@link DecodedRevert.message}.\n *\n * Revert data comes from whatever contract the vault called, which for an external\n * call is an address the proposer chose — so it is as untrusted as token metadata and\n * gets the same treatment. `args` keeps the raw values; only `message` is scrubbed,\n * because that is the field meant for a human.\n */\nconst REVERT_TEXT_LIMIT = 256;\n\ninterface ErrorEntry {\n fragment: ErrorFragment;\n iface: Interface;\n}\n\n/** selector -> fragment, built once across every ABI the SDK knows about. */\nlet registry: Map<string, ErrorEntry> | null = null;\n\nfunction buildRegistry(): Map<string, ErrorEntry> {\n const map = new Map<string, ErrorEntry>();\n for (const abi of [QuaiVaultAbi, QuaiVaultFactoryAbi, SocialRecoveryModuleAbi, QuaiVaultProxyAbi]) {\n const iface = new Interface(abi);\n iface.forEachError((fragment) => {\n // First ABI wins; collisions across our own contracts are same-signature by construction.\n if (!map.has(fragment.selector)) map.set(fragment.selector, { fragment, iface });\n });\n }\n return map;\n}\n\nfunction getRegistry(): Map<string, ErrorEntry> {\n if (!registry) registry = buildRegistry();\n return registry;\n}\n\n/**\n * Guidance keyed by custom error name. This is the difference between\n * \"execution reverted (unknown custom error)\" and something a caller can act on.\n */\nconst REMEDIATION: Record<string, string> = {\n // --- QuaiVault: authorisation\n NotAnOwner: 'The calling address is not an owner of this vault.',\n OnlySelf:\n 'This function can only be invoked as a vault self-call. Propose a transaction targeting the vault itself.',\n NotAnAuthorizedModule: 'The caller is not an enabled module on this vault.',\n NotProposer: 'Only the address that proposed a transaction may cancel it directly.',\n\n // --- QuaiVault: transaction lifecycle\n TransactionDoesNotExist: 'No transaction with that hash exists on this vault.',\n TransactionAlreadyExecuted: 'This transaction has already been executed and is terminal.',\n TransactionAlreadyCancelled: 'This transaction has already been cancelled or expired.',\n TransactionAlreadyExists:\n 'An identical transaction (same target, value, data and nonce) is already pending.',\n AlreadyApproved: 'This owner has already approved the transaction.',\n NotApproved: 'This owner has no active approval to revoke.',\n NotEnoughApprovals: 'The approval threshold has not been reached yet.',\n CannotCancelApprovedTransaction:\n 'The transaction reached quorum, which permanently locks proposer-cancel. Propose a cancelByConsensus self-call instead.',\n TransactionIsExpired: 'The transaction passed its expiration timestamp and can no longer execute.',\n TransactionNotExpired: 'The transaction has not passed its expiration timestamp yet.',\n TimelockNotElapsed: 'The execution delay has not elapsed. Retry after the timelock expires.',\n ExpirationTooSoon:\n 'The expiration must be later than now plus the execution delay, so at least one execution attempt is possible.',\n SelfCallCannotHaveValue: 'Self-calls must have value 0.',\n InvalidDestinationAddress: 'The destination address is the zero address.',\n CalldataTooShort: 'Self-call data must contain at least a 4-byte function selector.',\n UnrecognizedSelfCall:\n 'The self-call selector is not one the vault dispatches. Check the encoded function against the QuaiVault ABI.',\n\n // --- QuaiVault: owners and threshold\n OwnersRequired: 'At least one owner is required.',\n TooManyOwners: 'A vault may have at most 20 owners.',\n MaxOwnersReached: 'This vault already has the maximum of 20 owners.',\n InvalidThreshold: 'The threshold must be between 1 and the number of owners.',\n InvalidOwnerAddress:\n 'Owner addresses cannot be the zero address, the vault itself, or the sentinel 0x…01.',\n DuplicateOwner: 'The owner list contains a duplicate address.',\n AlreadyAnOwner: 'That address is already an owner.',\n CannotRemoveOwnerWouldFallBelowThreshold:\n 'Removing this owner would leave fewer owners than the threshold. Lower the threshold first.',\n\n // --- QuaiVault: modules and delegatecall\n ModuleAlreadyEnabled: 'That module is already enabled.',\n ModuleNotEnabled: 'That module is not enabled on this vault.',\n InvalidModule: 'Module addresses cannot be the zero address or the sentinel 0x…01.',\n InvalidPrevModule:\n 'The predecessor in the module linked list is stale — the module list changed since the proposal was created.',\n MaxModulesReached: 'This vault already has the maximum of 50 modules.',\n DelegateCallNotAllowed:\n 'DelegateCall targets must be explicitly whitelisted. Propose addDelegatecallTarget for this address first.',\n DelegatecallTargetAlreadyAllowed: 'That address is already on the DelegateCall whitelist.',\n DelegatecallTargetNotAllowed: 'That address is not on the DelegateCall whitelist.',\n ImplementationSlotTampered:\n 'A DelegateCall overwrote the ERC1967 implementation slot and was reverted. The target contract is hostile or buggy.',\n\n // --- QuaiVault: misc\n ExecutionDelayTooLong: 'The execution delay may not exceed 30 days (2,592,000 seconds).',\n MessageNotSigned: 'That message hash is not currently signed by the vault.',\n\n // --- Factory\n InvalidImplementationAddress: 'The implementation address is the zero address.',\n InvalidWalletAddress: 'The vault address is the zero address.',\n WalletAlreadyRegistered: 'That vault is already registered with the factory.',\n CallerIsNotAnOwner: 'Only an owner of the vault may register it with the factory.',\n InvalidWalletImplementation:\n 'The address is not a QuaiVaultProxy pointing at this factory’s implementation.',\n\n // --- SocialRecoveryModule\n GuardiansRequired: 'At least one guardian is required.',\n TooManyGuardians: 'Too many guardians for the recovery configuration.',\n RecoveryPeriodTooShort: 'The recovery period is below the module minimum.',\n CannotUpdateConfigWhileRecoveriesPending:\n 'Cancel or resolve all pending recoveries before changing the guardian configuration.',\n InvalidGuardianAddress: 'A guardian address is invalid.',\n DuplicateGuardian: 'The guardian list contains a duplicate address.',\n RecoveryNotConfigured: 'This vault has no social recovery configuration.',\n NotAGuardian: 'The calling address is not a guardian of this vault.',\n RecoveryAlreadyInitiated: 'An identical recovery is already pending.',\n RecoveryNotInitiated: 'No recovery with that hash exists.',\n RecoveryAlreadyExecuted: 'That recovery has already been executed.',\n RecoveryPeriodNotElapsed: 'The recovery time lock has not elapsed yet.',\n RecoveryExpired: 'The recovery passed its expiration deadline.',\n RecoveryNotExpired: 'The recovery has not expired yet.',\n TooManyPendingRecoveries: 'This vault has reached its cap on concurrent pending recoveries.',\n RecoveryExceedsMaxOwners:\n 'Applying this recovery would temporarily exceed the 20-owner maximum during the add-before-remove sequence.',\n MustBeCalledByWallet: 'This function must be called by the vault itself.',\n};\n\nfunction formatArgs(fragment: ErrorFragment, args: readonly unknown[]): string {\n if (args.length === 0) return '';\n const parts = fragment.inputs.map((input, i) => {\n const value = args[i];\n // A custom error may declare a `string` parameter, which puts contract-supplied\n // text into this rendering. Scrub it like any other display string.\n const rendered =\n typeof value === 'bigint'\n ? value.toString()\n : typeof value === 'string'\n ? sanitizeText(value, REVERT_TEXT_LIMIT)\n : String(value);\n return input.name ? `${input.name}: ${rendered}` : rendered;\n });\n return `(${parts.join(', ')})`;\n}\n\n/**\n * Decode revert data against every QuaiVault ABI, plus the two Solidity builtins.\n * Returns `undefined` for empty data or an unrecognised selector.\n */\nexport function decodeRevert(data: unknown): DecodedRevert | undefined {\n if (typeof data !== 'string' || !data.startsWith('0x') || data.length < 10) return undefined;\n\n const selector = data.slice(0, 10).toLowerCase();\n const coder = AbiCoder.defaultAbiCoder();\n\n if (selector === SOLIDITY_ERROR_SELECTOR) {\n try {\n const [reason] = coder.decode(['string'], '0x' + data.slice(10));\n return {\n name: 'Error',\n args: [reason],\n selector,\n message: sanitizeText(reason, REVERT_TEXT_LIMIT),\n };\n } catch {\n return undefined;\n }\n }\n\n if (selector === SOLIDITY_PANIC_SELECTOR) {\n try {\n const [code] = coder.decode(['uint256'], '0x' + data.slice(10));\n return {\n name: 'Panic',\n args: [code],\n selector,\n message: `Panic(0x${BigInt(code).toString(16)}) — arithmetic or assertion failure in the target contract`,\n };\n } catch {\n return undefined;\n }\n }\n\n const entry = getRegistry().get(selector);\n if (!entry) return undefined;\n\n let args: unknown[] = [];\n try {\n args = Array.from(entry.iface.decodeErrorResult(entry.fragment, data));\n } catch {\n // Selector matched but the payload did not — report the name without args.\n }\n\n const name = entry.fragment.name;\n const remediation = REMEDIATION[name];\n const rendered = `${name}${formatArgs(entry.fragment, args)}`;\n\n return {\n name,\n args,\n selector,\n message: remediation ? `${rendered} — ${remediation}` : rendered,\n };\n}\n\n/** Remediation text for a custom error name, if the SDK knows one. */\nexport function remediationFor(errorName: string): string | undefined {\n return REMEDIATION[errorName];\n}\n\n/**\n * Pull revert data out of the many shapes providers use, then decode it.\n * Handles quais/ethers `CALL_EXCEPTION` errors, raw RPC error bodies and nested causes.\n */\nexport function decodeRevertFromError(error: unknown): DecodedRevert | undefined {\n const seen = new Set<unknown>();\n\n const walk = (node: unknown, depth: number): DecodedRevert | undefined => {\n if (node == null || depth > 6 || seen.has(node)) return undefined;\n if (typeof node === 'string') return decodeRevert(node);\n if (typeof node !== 'object') return undefined;\n seen.add(node);\n\n const obj = node as Record<string, unknown>;\n for (const key of ['data', 'errorData', 'return', 'returnData']) {\n const decoded = decodeRevert(obj[key]);\n if (decoded) return decoded;\n }\n for (const key of ['error', 'cause', 'info', 'body', 'value']) {\n const decoded = walk(obj[key], depth + 1);\n if (decoded) return decoded;\n }\n return undefined;\n };\n\n return walk(error, 0);\n}\n\n/** All known custom error selectors. Exposed for tooling and tests. */\nexport function knownErrorSelectors(): Array<{ selector: Hex; signature: string }> {\n return Array.from(getRegistry().entries()).map(([selector, { fragment }]) => ({\n selector,\n signature: fragment.format('sighash'),\n }));\n}\n","/**\n * Display sanitisation for attacker-controlled strings.\n *\n * Two values reach a consumer's screen without ever having been vetted by anyone:\n *\n * - **Token metadata.** `symbol()` and `name()` are whatever the token's deployer\n * chose. Getting one indexed against a vault costs one transfer of one unit.\n * - **Revert reasons.** `Error(string)` data comes from the contract a vault called,\n * which for an external call is an arbitrary address the proposer picked.\n *\n * In a browser both are inert — the DOM escapes them. In a terminal they are not. An\n * ANSI escape can move the cursor up and overwrite lines the SDK already printed, so\n * a token named `\"\\x1b[2A\\x1b[KAll checks passed\"` can forge SDK output. Bidi\n * overrides can reverse a rendered address while leaving the underlying bytes intact,\n * which is the same trick that makes malicious source look benign.\n *\n * Sanitising here rather than in each consumer means a CLI, a TUI and a log pipeline\n * all inherit it, and none of them has to remember. Only human-facing fields are\n * scrubbed — machine-readable ones (`DecodedRevert.args`) keep the raw bytes, because\n * a consumer comparing against an expected value needs exactly what was on chain.\n */\n\n/**\n * Characters removed outright: C0 and C1 controls (including ESC, which starts every\n * ANSI sequence), DEL, the bidirectional embedding and override marks, the invisible\n * word joiners, and the zero-width space family used for homoglyph padding.\n */\nconst UNSAFE_CHARS = new RegExp(\n [\n '[\\\\u0000-\\\\u001F', // C0 controls, incl. ESC (0x1B) — the head of every ANSI sequence\n '\\\\u007F-\\\\u009F', // DEL and the C1 controls\n '\\\\u200B-\\\\u200F', // zero-width space/joiners, LRM, RLM\n '\\\\u202A-\\\\u202E', // bidi embeddings and overrides\n '\\\\u2060-\\\\u2064', // word joiner and the invisible operators\n '\\\\u2066-\\\\u2069', // bidi isolates\n '\\\\uFEFF]', // zero-width no-break space / BOM\n ].join(''),\n 'g',\n);\n\n/** Default cap. Long enough for any legitimate token name, short enough to not wrap. */\nexport const DEFAULT_TEXT_LIMIT = 128;\n\n/**\n * Strip control and direction-manipulating characters, collapse surrounding\n * whitespace, and cap the length.\n *\n * Returns `''` for a non-string or for input that was entirely unsafe, so callers can\n * `sanitizeText(x) || fallback`.\n */\nexport function sanitizeText(value: unknown, maxLength: number = DEFAULT_TEXT_LIMIT): string {\n if (typeof value !== 'string') return '';\n\n const cleaned = value.replace(UNSAFE_CHARS, '').trim();\n if (cleaned.length <= maxLength) return cleaned;\n\n // Truncate to the cap *including* the ellipsis, so the result never exceeds what\n // the caller budgeted for.\n return `${cleaned.slice(0, Math.max(0, maxLength - 1))}…`;\n}\n","import { AbiCoder, Interface, concat, getBytes, solidityPacked } from 'quais';\nimport {\n Erc1155Abi,\n Erc20Abi,\n Erc721Abi,\n MultiSendCallOnlyAbi,\n QuaiVaultAbi,\n SocialRecoveryModuleAbi,\n} from '../abi/index.js';\nimport type { Address, Hex } from '../types.js';\nimport { Operation } from '../types.js';\nimport { ValidationError } from '../errors/index.js';\n\nconst vault = new Interface(QuaiVaultAbi);\nconst recovery = new Interface(SocialRecoveryModuleAbi);\nconst multiSend = new Interface(MultiSendCallOnlyAbi);\nconst erc20 = new Interface(Erc20Abi as unknown as string[]);\nconst erc721 = new Interface(Erc721Abi as unknown as string[]);\nconst erc1155 = new Interface(Erc1155Abi as unknown as string[]);\n\nexport const interfaces = { vault, recovery, multiSend, erc20, erc721, erc1155 };\n\n/** Max value the contracts accept for `minExecutionDelay` / `requestedDelay` (30 days). */\nexport const MAX_EXECUTION_DELAY = 30 * 24 * 60 * 60;\nexport const MAX_OWNERS = 20;\nexport const MAX_MODULES = 50;\n/** Head of the Zodiac module linked list. Never valid as an owner, module or guardian. */\nexport const SENTINEL_MODULES = '0x0000000000000000000000000000000000000001';\n/** Rejected everywhere an address is committed to a role. */\nexport const ZERO_ADDRESS = '0x0000000000000000000000000000000000000000';\n\n// ---------------------------------------------------------------------------\n// Vault self-calls\n//\n// Every one of these must be delivered as a proposed transaction whose `to` is the\n// vault itself. The vault's `_executeSelfCall` dispatcher rejects any selector it\n// does not recognise, so encoding must come from this ABI.\n// ---------------------------------------------------------------------------\n\nexport const selfCall = {\n addOwner: (owner: Address): Hex => vault.encodeFunctionData('addOwner', [owner]),\n\n removeOwner: (owner: Address): Hex => vault.encodeFunctionData('removeOwner', [owner]),\n\n changeThreshold: (threshold: number): Hex => {\n if (!Number.isInteger(threshold) || threshold < 1) {\n throw new ValidationError(`Invalid threshold ${threshold}: must be an integer >= 1.`);\n }\n return vault.encodeFunctionData('changeThreshold', [threshold]);\n },\n\n enableModule: (module: Address): Hex => vault.encodeFunctionData('enableModule', [module]),\n\n /**\n * Disable a module.\n *\n * `prevModule` is the predecessor in the Zodiac linked list and must be resolved\n * against the live list — a proposal built against a stale list can never execute.\n * Prefer `Vault.propose.disableModule`, which resolves it for you.\n */\n disableModule: (prevModule: Address, module: Address): Hex =>\n vault.encodeFunctionData('disableModule', [prevModule, module]),\n\n setMinExecutionDelay: (seconds: number): Hex => {\n if (!Number.isInteger(seconds) || seconds < 0 || seconds > MAX_EXECUTION_DELAY) {\n throw new ValidationError(\n `Invalid execution delay ${seconds}: must be an integer between 0 and ${MAX_EXECUTION_DELAY} (30 days).`,\n );\n }\n return vault.encodeFunctionData('setMinExecutionDelay', [seconds]);\n },\n\n addDelegatecallTarget: (target: Address): Hex =>\n vault.encodeFunctionData('addDelegatecallTarget', [target]),\n\n removeDelegatecallTarget: (target: Address): Hex =>\n vault.encodeFunctionData('removeDelegatecallTarget', [target]),\n\n cancelByConsensus: (txHash: Hex): Hex => vault.encodeFunctionData('cancelByConsensus', [txHash]),\n\n /** Sign arbitrary bytes. For EIP-1271 hash pre-approval use {@link approveHashForEip1271}. */\n signMessage: (data: Hex): Hex => vault.encodeFunctionData('signMessage', [data]),\n\n unsignMessage: (data: Hex): Hex => vault.encodeFunctionData('unsignMessage', [data]),\n\n /**\n * Pre-approve a hash so `isValidSignature(hash, …)` returns the EIP-1271 magic value.\n *\n * `isValidSignature(h)` checks `signedMessages[getMessageHash(abi.encode(h))]`, while\n * `signMessage(data)` stores `getMessageHash(data)`. Because `abi.encode` of a static\n * `bytes32` is the identity on its 32 bytes, this produces calldata identical to\n * `signMessage(hash)` — the encoding step is a no-op for a well-formed hash.\n *\n * It is a separate helper because the *length* is what matters: signing an\n * arbitrary-length message `M` does NOT make `isValidSignature(keccak256(M))`\n * validate, since EIP-1271 hashes the 32-byte dataHash, not `M`. This entry point\n * enforces the 32-byte precondition and states the intent, so that mistake is\n * caught here rather than discovered when a counterparty's check silently fails.\n */\n approveHashForEip1271: (hash: Hex): Hex => {\n if (!/^0x[0-9a-fA-F]{64}$/.test(hash)) {\n throw new ValidationError('approveHashForEip1271 expects a 32-byte hash.');\n }\n const encoded = AbiCoder.defaultAbiCoder().encode(['bytes32'], [hash]);\n return vault.encodeFunctionData('signMessage', [encoded]);\n },\n\n /** Revoke a hash previously approved via {@link approveHashForEip1271}. */\n revokeHashForEip1271: (hash: Hex): Hex => {\n if (!/^0x[0-9a-fA-F]{64}$/.test(hash)) {\n throw new ValidationError('revokeHashForEip1271 expects a 32-byte hash.');\n }\n const encoded = AbiCoder.defaultAbiCoder().encode(['bytes32'], [hash]);\n return vault.encodeFunctionData('unsignMessage', [encoded]);\n },\n};\n\n// ---------------------------------------------------------------------------\n// Token calls\n// ---------------------------------------------------------------------------\n\nexport const token = {\n erc20Transfer: (to: Address, amount: bigint): Hex =>\n erc20.encodeFunctionData('transfer', [to, amount]),\n erc20Approve: (spender: Address, amount: bigint): Hex =>\n erc20.encodeFunctionData('approve', [spender, amount]),\n erc721Transfer: (from: Address, to: Address, tokenId: bigint): Hex =>\n erc721.encodeFunctionData('safeTransferFrom(address,address,uint256)', [from, to, tokenId]),\n erc1155Transfer: (from: Address, to: Address, id: bigint, amount: bigint, data: Hex = '0x'): Hex =>\n erc1155.encodeFunctionData('safeTransferFrom', [from, to, id, amount, data]),\n erc1155BatchTransfer: (\n from: Address,\n to: Address,\n ids: bigint[],\n amounts: bigint[],\n data: Hex = '0x',\n ): Hex => {\n if (ids.length !== amounts.length) {\n throw new ValidationError('erc1155BatchTransfer: ids and amounts must be the same length.');\n }\n return erc1155.encodeFunctionData('safeBatchTransferFrom', [from, to, ids, amounts, data]);\n },\n};\n\n// ---------------------------------------------------------------------------\n// Social recovery\n// ---------------------------------------------------------------------------\n\nexport const recoveryCall = {\n /** Encoded for a vault-proposed call to the module (not a self-call). */\n setupRecovery: (\n vaultAddress: Address,\n guardians: Address[],\n threshold: number,\n recoveryPeriodSeconds: number,\n ): Hex => {\n if (guardians.length === 0) throw new ValidationError('At least one guardian is required.');\n if (!Number.isInteger(threshold) || threshold < 1 || threshold > guardians.length) {\n throw new ValidationError(\n `Invalid guardian threshold ${threshold}: must be between 1 and ${guardians.length}.`,\n );\n }\n return recovery.encodeFunctionData('setupRecovery', [\n vaultAddress,\n guardians,\n threshold,\n recoveryPeriodSeconds,\n ]);\n },\n};\n\n// ---------------------------------------------------------------------------\n// MultiSend batching\n// ---------------------------------------------------------------------------\n\nexport interface BatchCall {\n to: Address;\n value?: bigint;\n data?: Hex;\n}\n\n/**\n * Pack calls into MultiSendCallOnly's transaction blob:\n * `operation(1) ‖ to(20) ‖ value(32) ‖ dataLength(32) ‖ data`, concatenated.\n *\n * `MultiSendCallOnly` rejects nested DelegateCall, so operation is always 0.\n */\nexport function encodeMultiSendPayload(calls: BatchCall[]): Hex {\n if (calls.length === 0) throw new ValidationError('encodeMultiSendPayload: no calls supplied.');\n\n const parts = calls.map((call) => {\n const data = call.data ?? '0x';\n const bytes = getBytes(data);\n return solidityPacked(\n ['uint8', 'address', 'uint256', 'uint256', 'bytes'],\n [Operation.Call, call.to, call.value ?? 0n, bytes.length, bytes],\n );\n });\n\n return concat(parts);\n}\n\n/** Full `multiSend(bytes)` calldata for a batch of calls. */\nexport function encodeMultiSend(calls: BatchCall[]): Hex {\n return multiSend.encodeFunctionData('multiSend', [encodeMultiSendPayload(calls)]);\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Smallest expiration the contract will accept for a given delay.\n *\n * `_proposeTransaction` rejects `expiration <= block.timestamp + effectiveDelay` with\n * `ExpirationTooSoon`, so a proposal must leave at least one execution opportunity\n * after the timelock elapses. The margin absorbs the gap between building the\n * proposal and it being mined.\n */\nexport function minimumExpiration(\n effectiveDelaySeconds: number,\n marginSeconds = 300,\n at: number = Math.floor(Date.now() / 1000),\n): number {\n return at + effectiveDelaySeconds + marginSeconds;\n}\n","import type { Provider, Signer } from 'quais';\n// Type-only, and `verbatimModuleSyntax` erases it, so the cycle with config/networks.ts\n// exists in the type graph and never in the emitted module graph.\nimport type { NetworkName } from './config/networks.js';\n\nexport type Address = string;\nexport type Hex = string;\nexport type Bytes32 = string;\n\nexport type { Provider, Signer };\n\n/** Zodiac IAvatar operation type. Mirrors `Enum.Operation` in the contracts. */\nexport enum Operation {\n Call = 0,\n DelegateCall = 1,\n}\n\n// ---------------------------------------------------------------------------\n// Configuration\n// ---------------------------------------------------------------------------\n\nexport interface ContractAddresses {\n implementation: Address;\n factory: Address;\n socialRecovery?: Address;\n multiSendCallOnly?: Address;\n}\n\nexport interface IndexerConfig {\n /** Supabase project URL. */\n url: string;\n /** Public anon key. Read-only by RLS policy — safe to distribute. */\n anonKey: string;\n /** Postgres schema for this network (`mainnet`, `testnet`, `dev`). */\n schema: string;\n /** Base URL of the indexer health server, used for lag/liveness checks. */\n healthUrl?: string;\n}\n\nexport interface NetworkConfig {\n name: string;\n chainId: number;\n rpcUrl: string;\n explorerUrl?: string;\n contracts: ContractAddresses;\n indexer?: IndexerConfig;\n}\n\n/**\n * How reads resolve between the indexer and the chain.\n *\n * - `indexed` — indexer only. Fastest; may be stale; fails if the indexer is down.\n * - `chain` — RPC only. Authoritative; slower; some history queries are unavailable.\n * - `auto` — indexer when it is fresh enough (see {@link ClientOptions.maxIndexerLagBlocks}),\n * otherwise the chain. This is the default.\n *\n * Write paths always re-validate preconditions against the chain regardless of this\n * setting — indexed approval counts can diverge from on-chain reality after an owner\n * is removed (approval epochs), so they must never gate a signature.\n */\nexport type Consistency = 'auto' | 'indexed' | 'chain';\n\nexport interface ClientOptions {\n network?: NetworkConfig | NetworkName;\n provider?: Provider;\n signer?: Signer;\n /** Private key for a local signer. Prefer the `QUAIVAULT_PRIVATE_KEY` env var. */\n privateKey?: string;\n rpcUrl?: string;\n indexer?: Partial<IndexerConfig>;\n contracts?: Partial<ContractAddresses>;\n consistency?: Consistency;\n /** Beyond this many blocks behind, `auto` reads fall through to the chain. Default 50. */\n maxIndexerLagBlocks?: number;\n /** Read env vars for anything not passed explicitly. Default true. */\n useEnv?: boolean;\n /**\n * Retry policy for transient RPC and indexer failures. Applies to reads only —\n * writes are never retried, since a resubmit risks a double broadcast.\n */\n retry?: {\n maxAttempts?: number;\n baseDelayMs?: number;\n maxDelayMs?: number;\n onRetry?: (info: { attempt: number; delayMs: number; error: unknown }) => void;\n };\n}\n\n// ---------------------------------------------------------------------------\n// Vault domain model\n// ---------------------------------------------------------------------------\n\nexport interface VaultInfo {\n address: Address;\n owners: Address[];\n threshold: number;\n /** Vault-level minimum timelock for external calls, in seconds. 0 = simple quorum. */\n minExecutionDelay: number;\n nonce: number;\n balance: bigint;\n moduleCount: number;\n}\n\nexport type TransactionKind =\n | 'transfer'\n | 'erc20_transfer'\n | 'erc721_transfer'\n | 'erc1155_transfer'\n | 'wallet_admin'\n | 'module_config'\n | 'module_execution'\n | 'message_signing'\n | 'recovery_setup'\n | 'batched_call'\n | 'external_call'\n | 'unknown';\n\n/**\n * Lifecycle state of a vault transaction.\n *\n * `ready` and `timelocked` are SDK-derived refinements of the contract's \"pending\":\n * both mean not-yet-executed with quorum reached, differing only on whether the\n * execution delay has elapsed.\n */\nexport type TransactionStatus =\n | 'pending' // awaiting approvals\n | 'timelocked' // quorum reached, execution delay not yet elapsed\n | 'ready' // quorum reached, executable now\n | 'executed'\n | 'failed' // executed, but the external call reverted (terminal)\n | 'cancelled'\n | 'expired';\n\nexport interface ApprovalRecord {\n owner: Address;\n /** Whether this approval currently counts toward the threshold. */\n active: boolean;\n}\n\nexport interface DecodedCall {\n /** Function name, e.g. `addOwner`. */\n name: string;\n signature: string;\n args: Record<string, unknown>;\n /** Contract the selector was resolved against. */\n target: 'vault' | 'socialRecovery' | 'multiSend' | 'erc20' | 'erc721' | 'erc1155';\n}\n\nexport interface VaultTransaction {\n hash: Bytes32;\n vault: Address;\n to: Address;\n value: bigint;\n data: Hex;\n\n proposer: Address;\n /**\n * Unix seconds when the proposal was recorded on chain, or 0 when unknown.\n *\n * Only chain reads carry a timestamp: the vault stores one in the transaction\n * struct, but the indexer records the *block* instead. On an indexed read this is 0\n * and {@link proposedAtBlock} carries the position. Never render 0 as a date.\n */\n proposedAt: number;\n /** Block the proposal was recorded in. Only populated on indexer reads. */\n proposedAtBlock?: number;\n\n kind: TransactionKind;\n decoded?: DecodedCall;\n /** One-line human-readable description. */\n summary: string;\n\n status: TransactionStatus;\n approvals: ApprovalRecord[];\n /** Count of approvals that currently count toward the threshold. */\n approvalCount: number;\n threshold: number;\n\n /** Unix seconds after which the tx can no longer execute. 0 = never expires. */\n expiration: number;\n /** Seconds of timelock locked in at proposal time. */\n executionDelay: number;\n /** Unix seconds when quorum was first reached. 0 = never reached. */\n approvedAt: number;\n /** `approvedAt + executionDelay`, or 0 if the clock has not started. */\n executableAfter: number;\n\n /** Raw revert data from a `TransactionFailed` event. */\n failedReturnData?: Hex;\n decodedRevert?: DecodedRevert;\n\n /** Where this record came from. */\n source: 'indexer' | 'chain';\n /** Indexer head at read time; absent for chain reads. */\n indexedAtBlock?: number;\n}\n\nexport interface DecodedRevert {\n /** Custom error name, or `Error` / `Panic` for the builtins. */\n name: string;\n args: unknown[];\n selector: Hex;\n /** Human-readable rendering. */\n message: string;\n}\n\n// ---------------------------------------------------------------------------\n// Writes\n// ---------------------------------------------------------------------------\n\nexport interface ProposeOptions {\n /** Unix seconds after which the tx can no longer execute. 0 / omitted = no expiry. */\n expiration?: number;\n /** Extra delay beyond the vault floor, in seconds. */\n executionDelay?: number;\n /** Build and return the call without signing. */\n dryRun?: boolean;\n}\n\nexport interface ProposeResult {\n /** The vault-transaction hash (bytes32), not the Quai transaction hash. */\n txHash: Bytes32;\n /** The on-chain Quai transaction hash that carried the proposal. */\n chainTxHash: Hex;\n to: Address;\n value: bigint;\n data: Hex;\n}\n\n/** Result of a dry-run write: everything needed to inspect or submit later. */\nexport interface DryRunResult {\n dryRun: true;\n to: Address;\n data: Hex;\n value: bigint;\n /** Estimated gas, or null if estimation reverted. */\n gasEstimate: bigint | null;\n /** Decoded revert if estimation failed. */\n wouldRevert?: DecodedRevert;\n description: string;\n}\n\n/**\n * Outcome of an execute attempt.\n *\n * A successful Quai transaction receipt does NOT imply the vault transaction ran.\n * See `docs/execution-outcomes.md`.\n */\nexport type ExecuteOutcome =\n | 'executed' // TransactionExecuted emitted — the target call succeeded\n | 'failed' // TransactionFailed emitted — target reverted; vault tx is terminal\n | 'timelock_started' // lazy clock: approvedAt was set, nothing executed; retry after the delay\n | 'approved_only'; // approveAndExecute recorded an approval but could not execute\n\nexport interface ExecuteResult {\n outcome: ExecuteOutcome;\n txHash: Bytes32;\n chainTxHash: Hex;\n blockNumber: number;\n gasUsed: bigint;\n /** Set when `outcome === 'failed'`. */\n returnData?: Hex;\n decodedRevert?: DecodedRevert;\n /** Set when `outcome === 'timelock_started'`. Unix seconds. */\n executableAfter?: number;\n /** Set when `outcome === 'approved_only'`. */\n approvalsNeeded?: number;\n /** Human-readable explanation of what happened and what to do next. */\n message: string;\n}\n\n// ---------------------------------------------------------------------------\n// Affordances\n// ---------------------------------------------------------------------------\n\nexport type VaultAction =\n | 'approve'\n | 'revokeApproval'\n | 'execute'\n | 'approveAndExecute'\n | 'cancel'\n | 'expire'\n | 'proposeCancelByConsensus';\n\nexport type AffordanceBlocker =\n | 'not_owner'\n | 'already_approved'\n | 'not_approved'\n | 'threshold'\n | 'timelock'\n | 'expired'\n | 'terminal_state'\n | 'quorum_locked'\n | 'not_proposer'\n | 'no_expiration';\n\nexport interface Affordance {\n action: VaultAction;\n allowed: boolean;\n /** Plain-language explanation, suitable for surfacing directly to a user. */\n reason: string;\n /** Unix seconds when a time gate lifts, if the only blocker is time. */\n availableAt?: number;\n blockedBy?: AffordanceBlocker;\n}\n\n// ---------------------------------------------------------------------------\n// Deployment\n// ---------------------------------------------------------------------------\n\nexport interface CreateVaultParams {\n owners: Address[];\n threshold: number;\n /** Vault-level minimum timelock in seconds. Max 30 days. Default 0. */\n minExecutionDelay?: number;\n /** Modules enabled at deploy time. */\n initialModules?: Address[];\n /** DelegateCall whitelist entries. Empty (default) means DelegateCall is disabled. */\n initialDelegatecallTargets?: Address[];\n /** Pre-mined salt. Omit to mine one automatically. */\n salt?: Bytes32;\n}\n\nexport interface MinedSalt {\n salt: Bytes32;\n predictedAddress: Address;\n attempts: number;\n durationMs: number;\n}\n\nexport interface CreateVaultResult {\n address: Address;\n chainTxHash: Hex;\n salt: Bytes32;\n /** Whether the deployed address matched the mined prediction. */\n predictionMatched: boolean;\n}\n\n// ---------------------------------------------------------------------------\n// Social recovery\n// ---------------------------------------------------------------------------\n\nexport interface RecoveryConfig {\n guardians: Address[];\n /** Guardian approvals required to execute a recovery. */\n threshold: number;\n /** Delay in seconds between initiation and executability. */\n recoveryPeriod: number;\n /** False when the vault has no recovery configured. */\n configured: boolean;\n}\n\n/**\n * Lifecycle state of a recovery request.\n *\n * `cancelled` is only ever reported from the indexer: `cancelRecovery` deletes the\n * on-chain struct, so a chain read cannot distinguish a cancelled recovery from one\n * that never existed.\n */\nexport type RecoveryStatus =\n | 'pending' // awaiting guardian approvals\n | 'timelocked' // approved, waiting out the recovery period\n | 'ready' // approved and executable now\n | 'executed'\n | 'cancelled'\n | 'expired';\n\nexport interface RecoveryRequest {\n hash: Bytes32;\n vault: Address;\n newOwners: Address[];\n newThreshold: number;\n approvalCount: number;\n /** Threshold captured at initiation — config changes mid-recovery do not move it. */\n requiredThreshold: number;\n /** Unix seconds after which execution is permitted. */\n executionTime: number;\n /** Unix seconds after which the recovery is dead and can be cleaned up. */\n expiration: number;\n status: RecoveryStatus;\n executed: boolean;\n /**\n * Who initiated the recovery. Only populated on indexer reads — the module's struct\n * does not retain it.\n */\n initiator?: Address;\n source: 'indexer' | 'chain';\n}\n\nexport type RecoveryAction =\n | 'approve'\n | 'revokeApproval'\n | 'execute'\n | 'cancel'\n | 'expire';\n\nexport interface RecoveryAffordance {\n action: RecoveryAction;\n allowed: boolean;\n reason: string;\n availableAt?: number;\n blockedBy?:\n | 'not_guardian'\n | 'not_owner'\n | 'already_approved'\n | 'not_approved'\n | 'threshold'\n | 'timelock'\n | 'expired'\n | 'not_expired'\n | 'terminal_state'\n | 'module_disabled';\n}\n\n// ---------------------------------------------------------------------------\n// Indexer\n// ---------------------------------------------------------------------------\n\nexport interface Pagination {\n limit?: number;\n offset?: number;\n}\n\nexport interface Page<T> {\n data: T[];\n /**\n * Approximate size of the full result set.\n *\n * Taken from the query planner rather than a full scan, so it is exact on small\n * tables and an estimate on large ones. Use it to size a progress bar, not to decide\n * whether to keep paging — {@link hasMore} is what answers that.\n */\n total: number;\n /** Whether another page exists. Always exact. */\n hasMore: boolean;\n}\n\nexport interface IndexerHealth {\n available: boolean;\n lastIndexedBlock: number;\n chainHead?: number;\n blocksBehind?: number;\n isSyncing: boolean;\n /** Reason the indexer was judged unavailable. */\n error?: string;\n}\n","import { getCreate2Address, hexlify, isQuaiAddress, keccak256, randomBytes, solidityPacked } from 'quais';\nimport type { Address, Bytes32, CreateVaultParams, MinedSalt } from '../types.js';\nimport { AbortError, SaltMiningError } from '../errors/index.js';\nimport { computeBytecodeHash, encodeInitData, shardPrefixOf } from './predict.js';\n\nexport interface MineSaltOptions {\n factory: Address;\n implementation: Address;\n /** Address that will call `createWallet`. The mined address lands on its shard. */\n deployer: Address;\n params: CreateVaultParams;\n /** Override the target shard prefix. Defaults to the deployer's. */\n targetPrefix?: string;\n maxAttempts?: number;\n /** Abort after this long. Default 120_000 ms. */\n timeoutMs?: number;\n /** Called roughly every 1000 attempts. */\n onProgress?: (attempts: number) => void;\n signal?: AbortSignal;\n}\n\nexport interface MiningStrategy {\n readonly name: string;\n mine(options: Required<Pick<MineSaltOptions, 'factory' | 'deployer'>> & ResolvedMineJob): Promise<MinedSalt>;\n}\n\n/** Everything the inner loop needs, precomputed once. */\nexport interface ResolvedMineJob {\n bytecodeHash: Bytes32;\n targetPrefix: string;\n maxAttempts: number;\n timeoutMs: number;\n onProgress?: (attempts: number) => void;\n signal?: AbortSignal;\n}\n\nconst DEFAULT_MAX_ATTEMPTS = 500_000;\nconst DEFAULT_TIMEOUT_MS = 120_000;\nconst PROGRESS_INTERVAL = 1_000;\n/** Attempts per synchronous chunk before yielding to the event loop. */\nconst CHUNK = 250;\n\nfunction tryOne(\n factory: Address,\n deployer: Address,\n bytecodeHash: Bytes32,\n targetPrefix: string,\n): { salt: Bytes32; address: Address } | null {\n const salt = hexlify(randomBytes(32));\n const fullSalt = keccak256(solidityPacked(['address', 'bytes32'], [deployer, salt]));\n const address = getCreate2Address(factory, fullSalt, bytecodeHash);\n\n if (address.toLowerCase().startsWith(targetPrefix) && isQuaiAddress(address)) {\n return { salt, address };\n }\n return null;\n}\n\n/**\n * Chunked single-threaded miner. Yields to the event loop between chunks so it does\n * not block a browser UI thread or a Node server's other work.\n *\n * Works everywhere, which makes it the safe default.\n */\nexport const syncStrategy: MiningStrategy = {\n name: 'sync',\n async mine({ factory, deployer, bytecodeHash, targetPrefix, maxAttempts, timeoutMs, onProgress, signal }) {\n const startedAt = Date.now();\n\n for (let attempts = 0; attempts < maxAttempts; ) {\n if (signal?.aborted) throw new AbortError('Salt mining');\n if (Date.now() - startedAt > timeoutMs) {\n throw new SaltMiningError(\n `Salt mining timed out after ${timeoutMs} ms (${attempts} attempts).`,\n 'Raise timeoutMs, or use the worker_threads strategy on Node for more throughput.',\n );\n }\n\n const chunkEnd = Math.min(attempts + CHUNK, maxAttempts);\n for (; attempts < chunkEnd; attempts++) {\n const hit = tryOne(factory, deployer, bytecodeHash, targetPrefix);\n if (hit) {\n return {\n salt: hit.salt,\n predictedAddress: hit.address,\n attempts: attempts + 1,\n durationMs: Date.now() - startedAt,\n };\n }\n if ((attempts + 1) % PROGRESS_INTERVAL === 0) onProgress?.(attempts + 1);\n }\n\n await new Promise((resolve) => setTimeout(resolve, 0));\n }\n\n throw new SaltMiningError(\n `No valid salt found for prefix ${targetPrefix} after ${maxAttempts} attempts.`,\n 'Raise maxAttempts, or confirm the deployer address is on the shard you expect.',\n );\n },\n};\n\n/**\n * A worker could not be started or died before producing a result.\n *\n * Module-private, and never surfaced to a caller: it exists only to tell the \"this\n * environment cannot run workers\" case apart from a real mining outcome (timeout,\n * exhaustion, abort), so the former can retreat to {@link syncStrategy} while the\n * latter propagate.\n */\nclass WorkersUnavailable extends Error {}\n\n/**\n * Node-only multi-core miner, degrading to {@link syncStrategy} whenever workers turn\n * out not to be usable.\n *\n * Two distinct failures land here. `node:worker_threads` may not exist at all\n * (browsers, restricted runtimes). Or it exists, but the worker cannot boot — the\n * source below is inlined as a string and resolves `quais` with a bare `require`,\n * which no bundler traces, so a packaged consumer's worker dies on its first line.\n *\n * Both retreat to the sync miner rather than failing, and that retreat is always safe:\n * mining is pure computation over random salts with no side effects and no on-chain\n * state, so re-running it in process yields an equally valid answer. Deployment\n * getting slower is a far better outcome than deployment becoming impossible.\n */\nexport interface WorkerRuntime {\n Worker: typeof import('node:worker_threads').Worker;\n parallelism: number;\n}\n\n/** Resolve Node's worker primitives, or `null` where they do not exist. */\nasync function loadNodeWorkers(): Promise<WorkerRuntime | null> {\n try {\n const { Worker } = await import('node:worker_threads');\n const os = await import('node:os');\n return { Worker, parallelism: (os.availableParallelism ?? (() => os.cpus().length))() };\n } catch {\n return null;\n }\n}\n\n/**\n * Build the strategy over an injectable worker runtime.\n *\n * The injection point exists so the retreat path can be tested: a worker that dies on\n * its first line is the single most likely failure in a packaged consumer, and a\n * fallback nothing exercises is a fallback nobody can trust.\n */\nexport function createWorkerThreadsStrategy(\n load: () => Promise<WorkerRuntime | null> = loadNodeWorkers,\n): MiningStrategy {\n return {\n name: 'worker_threads',\n async mine(job) {\n const runtime = await load();\n if (!runtime) return syncStrategy.mine(job);\n\n try {\n return await mineInWorkers(runtime.Worker, runtime.parallelism, job);\n } catch (err) {\n if (err instanceof WorkersUnavailable) return syncStrategy.mine(job);\n // A timeout, an exhausted search or an abort are real answers about this job.\n // Re-running them single-threaded would only be slower.\n throw err;\n }\n },\n };\n}\n\nexport const workerThreadsStrategy: MiningStrategy = createWorkerThreadsStrategy();\n\nfunction mineInWorkers(\n Worker: typeof import('node:worker_threads').Worker,\n parallelism: number,\n job: ResolvedMineJob & Required<Pick<MineSaltOptions, 'factory' | 'deployer'>>,\n): Promise<MinedSalt> {\n const { factory, deployer, bytecodeHash, targetPrefix, maxAttempts, timeoutMs, onProgress, signal } = job;\n const workerCount = Math.max(1, Math.min(8, parallelism - 1));\n const perWorker = Math.ceil(maxAttempts / workerCount);\n const startedAt = Date.now();\n\n // Inlined worker source keeps the package free of a separate entry file. Note the\n // bare `require('quais')`: it resolves under plain Node, but no bundler traces a\n // string, so a packaged consumer's worker fails here — which is what the\n // `WorkersUnavailable` retreat exists to absorb.\n const workerSource = `\n const { parentPort, workerData } = require('node:worker_threads');\n const { getCreate2Address, hexlify, isQuaiAddress, keccak256, randomBytes, solidityPacked } = require('quais');\n const { factory, deployer, bytecodeHash, targetPrefix, maxAttempts } = workerData;\n for (let i = 0; i < maxAttempts; i++) {\n const salt = hexlify(randomBytes(32));\n const fullSalt = keccak256(solidityPacked(['address', 'bytes32'], [deployer, salt]));\n const address = getCreate2Address(factory, fullSalt, bytecodeHash);\n if (address.toLowerCase().startsWith(targetPrefix) && isQuaiAddress(address)) {\n parentPort.postMessage({ type: 'result', salt, address, attempts: i + 1 });\n return;\n }\n if ((i + 1) % ${PROGRESS_INTERVAL} === 0) parentPort.postMessage({ type: 'progress', attempts: i + 1 });\n }\n parentPort.postMessage({ type: 'exhausted', attempts: maxAttempts });\n `;\n\n return new Promise<MinedSalt>((resolve, reject) => {\n const workers: Array<InstanceType<typeof Worker>> = [];\n let settled = false;\n let exhausted = 0;\n let totalAttempts = 0;\n const progressByWorker = new Array<number>(workerCount).fill(0);\n\n const cleanup = () => {\n clearTimeout(timer);\n signal?.removeEventListener('abort', onAbort);\n for (const w of workers) void w.terminate();\n };\n const settle = (fn: () => void) => {\n if (settled) return;\n settled = true;\n cleanup();\n fn();\n };\n\n const timer = setTimeout(\n () =>\n settle(() =>\n reject(\n new SaltMiningError(\n `Salt mining timed out after ${timeoutMs} ms (~${totalAttempts} attempts across ${workerCount} workers).`,\n 'Raise timeoutMs or maxAttempts.',\n ),\n ),\n ),\n timeoutMs,\n );\n\n const onAbort = () => settle(() => reject(new AbortError('Salt mining')));\n signal?.addEventListener('abort', onAbort, { once: true });\n\n for (let i = 0; i < workerCount; i++) {\n let worker: InstanceType<typeof Worker>;\n try {\n worker = new Worker(workerSource, {\n eval: true,\n workerData: { factory, deployer, bytecodeHash, targetPrefix, maxAttempts: perWorker },\n });\n } catch (err) {\n // Construction itself threw — the runtime forbids workers outright.\n settle(() => reject(new WorkersUnavailable(String(err))));\n return;\n }\n workers.push(worker);\n\n worker.on('message', (msg: { type: string; salt?: string; address?: string; attempts?: number }) => {\n if (msg.type === 'progress') {\n progressByWorker[i] = msg.attempts ?? 0;\n totalAttempts = progressByWorker.reduce((a, b) => a + b, 0);\n onProgress?.(totalAttempts);\n } else if (msg.type === 'result') {\n settle(() =>\n resolve({\n salt: msg.salt as Bytes32,\n predictedAddress: msg.address as Address,\n attempts: totalAttempts + (msg.attempts ?? 0),\n durationMs: Date.now() - startedAt,\n }),\n );\n } else if (msg.type === 'exhausted') {\n if (++exhausted === workerCount) {\n settle(() =>\n reject(\n new SaltMiningError(\n `No valid salt found for prefix ${targetPrefix} after ${maxAttempts} attempts.`,\n 'Raise maxAttempts, or confirm the deployer address is on the shard you expect.',\n ),\n ),\n );\n }\n }\n });\n\n // Any worker-side throw lands here, and in practice it means the worker never\n // got off the ground: a module the bundler did not trace, or a runtime that\n // refuses `eval: true`. The loop itself cannot throw — it is arithmetic over\n // random bytes. Treat it as \"no workers available\" and let the caller retreat\n // to the sync miner.\n worker.on('error', (err) => settle(() => reject(new WorkersUnavailable(err.message))));\n }\n });\n}\n\n/** Prefer worker_threads on Node; the sync miner degrades gracefully everywhere else. */\nexport function defaultStrategy(): MiningStrategy {\n const hasNode =\n typeof (globalThis as { process?: { versions?: { node?: string } } }).process?.versions?.node ===\n 'string';\n return hasNode ? workerThreadsStrategy : syncStrategy;\n}\n\n/**\n * Mine a CREATE2 salt that deploys a vault onto the deployer's Quai shard.\n *\n * The predicted address is a pure function of (factory, implementation, deployer,\n * salt, create params) — so the caller can mine ahead of time, persist the salt,\n * and deploy later, as long as every one of those inputs is unchanged.\n */\nexport async function mineSalt(\n options: MineSaltOptions,\n strategy: MiningStrategy = defaultStrategy(),\n): Promise<MinedSalt> {\n const targetPrefix = (options.targetPrefix ?? shardPrefixOf(options.deployer)).toLowerCase();\n const initData = encodeInitData(options.params);\n const bytecodeHash = computeBytecodeHash(options.implementation, initData);\n\n return strategy.mine({\n factory: options.factory,\n deployer: options.deployer,\n bytecodeHash,\n targetPrefix,\n maxAttempts: options.maxAttempts ?? DEFAULT_MAX_ATTEMPTS,\n timeoutMs: options.timeoutMs ?? DEFAULT_TIMEOUT_MS,\n onProgress: options.onProgress,\n signal: options.signal,\n });\n}\n","import { AbiCoder, Interface, concat, getCreate2Address, keccak256, solidityPacked } from 'quais';\nimport { QuaiVaultAbi, QuaiVaultProxyBytecode } from '../abi/index.js';\nimport type { Address, Bytes32, CreateVaultParams } from '../types.js';\nimport { ValidationError } from '../errors/index.js';\n\nconst vaultInterface = new Interface(QuaiVaultAbi);\n\n/**\n * Encode the `initialize` call the factory delegatecalls from the proxy constructor.\n *\n * This MUST match `QuaiVaultFactory._createWallet` exactly — including the module and\n * delegatecall-target arrays. Encoding `[]` for those while deploying with a non-empty\n * array yields a different bytecode hash, so the mined address will not be the address\n * the factory actually deploys to.\n */\nexport function encodeInitData(params: {\n owners: Address[];\n threshold: number;\n minExecutionDelay?: number;\n initialModules?: Address[];\n initialDelegatecallTargets?: Address[];\n}): string {\n return vaultInterface.encodeFunctionData('initialize', [\n params.owners,\n params.threshold,\n params.minExecutionDelay ?? 0,\n params.initialModules ?? [],\n params.initialDelegatecallTargets ?? [],\n ]);\n}\n\n/**\n * keccak256 of the full proxy creation bytecode (creation code + ABI-encoded\n * constructor args), which is the third input to CREATE2.\n *\n * Constant for a given set of create params, so it is computed once and reused\n * across every mining attempt.\n */\nexport function computeBytecodeHash(implementation: Address, initData: string): Bytes32 {\n const encodedArgs = AbiCoder.defaultAbiCoder().encode(\n ['address', 'bytes'],\n [implementation, initData],\n );\n return keccak256(concat([QuaiVaultProxyBytecode, encodedArgs]));\n}\n\n/**\n * The factory namespaces user salts by caller:\n * `fullSalt = keccak256(abi.encodePacked(msg.sender, userSalt))`.\n * Two deployers using the same user salt therefore get different addresses.\n */\nexport function computeFullSalt(deployer: Address, userSalt: Bytes32): Bytes32 {\n return keccak256(solidityPacked(['address', 'bytes32'], [deployer, userSalt]));\n}\n\n/**\n * Reproduce `QuaiVaultFactory.predictWalletAddress` off-chain — no RPC needed.\n */\nexport function predictVaultAddress(args: {\n factory: Address;\n implementation: Address;\n deployer: Address;\n salt: Bytes32;\n params: CreateVaultParams;\n}): Address {\n const initData = encodeInitData(args.params);\n const bytecodeHash = computeBytecodeHash(args.implementation, initData);\n const fullSalt = computeFullSalt(args.deployer, args.salt);\n return getCreate2Address(args.factory, fullSalt, bytecodeHash);\n}\n\n/**\n * The shard prefix of a Quai address: `0x` plus the leading byte.\n *\n * Quai addresses are shard-scoped. A vault deployed outside the deployer's shard is\n * unreachable from it, which is why deployment requires mining a salt rather than\n * picking one at random.\n */\nexport function shardPrefixOf(address: Address): string {\n if (typeof address !== 'string' || !address.startsWith('0x') || address.length < 4) {\n throw new ValidationError(`Cannot derive a shard prefix from \"${address}\".`);\n }\n return address.slice(0, 4).toLowerCase();\n}\n","import { PostgrestClient } from '@supabase/postgrest-js';\nimport { RealtimeClient, type RealtimeChannel } from '@supabase/realtime-js';\nimport type { z } from 'zod';\nimport type { IndexerConfig, IndexerHealth, Page } from '../types.js';\nimport { AbortError, IndexerQueryError } from '../errors/index.js';\nimport { IndexerStateSchema, toNumber } from './schemas.js';\n\n/** Replaced at build time by tsup's `define`; absent when running from source. */\ndeclare const __SDK_VERSION__: string | undefined;\n\nconst SDK_VERSION = typeof __SDK_VERSION__ === 'string' ? __SDK_VERSION__ : 'dev';\n\n/**\n * The indexer uses one Postgres schema per network, chosen at runtime, so the client\n * cannot be pinned to postgrest-js's default `\"public\"` schema generic.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyPostgrestClient = PostgrestClient<any, any, any>;\n\n/**\n * Thin wrapper over the indexer's Supabase project.\n *\n * Built on `@supabase/postgrest-js` and `@supabase/realtime-js` directly rather than\n * the `@supabase/supabase-js` umbrella. The umbrella's constructor instantiates auth,\n * storage and functions clients unconditionally, so no bundler can shake them out —\n * and this SDK uses none of the three. Going direct costs 57 KB → 22 KB gzip, and the\n * only thing given up is `createClient`'s URL and header wiring, reproduced below.\n *\n * The anon key is a public read-only credential: the indexer's RLS grants `anon`\n * SELECT on every table and nothing else, with all writes reserved for\n * `service_role`. It carries no authority beyond reading already-public chain data.\n */\nexport class IndexerClient {\n readonly config: IndexerConfig;\n private readonly client: AnyPostgrestClient;\n private realtime: RealtimeClient | null = null;\n private healthCache: { value: IndexerHealth; at: number } | null = null;\n private inflightHealth: Promise<IndexerHealth> | null = null;\n\n /** Health results are reused for this long to keep read paths cheap. */\n readonly healthCacheMs: number;\n\n constructor(config: IndexerConfig, options: { healthCacheMs?: number } = {}) {\n this.config = config;\n this.healthCacheMs = options.healthCacheMs ?? 5_000;\n\n // What `createClient` does for the REST half. Both headers are required: PostgREST\n // authenticates on `apikey`, while the `Authorization` bearer is what selects the\n // `anon` role the RLS policies are written against.\n this.client = new PostgrestClient(`${baseUrl(config.url)}/rest/v1`, {\n headers: {\n apikey: config.anonKey,\n Authorization: `Bearer ${config.anonKey}`,\n 'x-client-info': `quaivault-sdk/${SDK_VERSION}`,\n },\n schema: config.schema,\n }) as AnyPostgrestClient;\n }\n\n /** The PostgREST client, for queries the SDK does not wrap. */\n get rest(): AnyPostgrestClient {\n return this.client;\n }\n\n from(table: string) {\n return this.client.from(table);\n }\n\n /**\n * Realtime client, constructed on first use.\n *\n * Lazy because it opens a WebSocket and starts a heartbeat, and the large majority\n * of SDK usage never calls `watch()`. Nothing here should cost a socket unless\n * somebody asked to follow a vault.\n */\n private realtimeClient(): RealtimeClient {\n if (!this.realtime) {\n this.realtime = new RealtimeClient(\n `${baseUrl(this.config.url).replace(/^http/, 'ws')}/realtime/v1`,\n { params: { apikey: this.config.anonKey } },\n );\n }\n return this.realtime;\n }\n\n /** Open a Realtime channel. See `watchVault`, which is what callers should use. */\n channel(name: string): RealtimeChannel {\n return this.realtimeClient().channel(name);\n }\n\n /** Close a channel opened by {@link channel}. */\n async removeChannel(channel: RealtimeChannel): Promise<void> {\n await this.realtimeClient().removeChannel(channel);\n }\n\n /**\n * Run a query, parse each row, and surface failures as `IndexerQueryError`.\n *\n * No retry wrapper here on purpose. `postgrest-js` already retries GET/HEAD/OPTIONS\n * internally (3 attempts, retryable statuses and fetch errors, honouring\n * `Retry-After`), and it reports failures as a resolved `{ error }` value rather\n * than a rejection — so an outer `withRetry` would be dead code that silently\n * multiplied attempts if it were ever made to work. Chain reads, which do reject,\n * are retried in `src/chain/retry.ts`.\n */\n async select<S extends z.ZodTypeAny>(\n table: string,\n schema: S,\n build: (q: ReturnType<AnyPostgrestClient[\"from\"]>) => PromiseLike<{\n data: unknown[] | null;\n error: { message: string; code?: string } | null;\n }>,\n ): Promise<Array<z.infer<S>>> {\n const { data, error } = await build(this.client.from(table));\n if (error) {\n throw new IndexerQueryError(`Indexer query on \"${table}\" failed: ${error.message}`, error);\n }\n return (data ?? []).map((row) => schema.parse(row) as z.infer<S>);\n }\n\n /**\n * Paged select: an exact `hasMore`, an approximate `total`.\n *\n * Both halves of that are deliberate. An `exact` count makes Postgres scan every\n * matching row on every page request, which is invisible on a young vault and\n * quadratic on a busy one — so the count is `estimated`, cheap and good enough for\n * \"roughly how much history is there\".\n *\n * But `hasMore` derived from an estimate would be a lie a caller can act on: a\n * paging loop that stops early drops real rows. So callers request one row beyond\n * the page and this trims it, which answers \"is there another page\" exactly, for\n * the cost of a single extra row.\n */\n async selectPage<S extends z.ZodTypeAny>(\n table: string,\n schema: S,\n limit: number,\n build: (q: ReturnType<AnyPostgrestClient['from']>) => PromiseLike<{\n data: unknown[] | null;\n error: { message: string; code?: string } | null;\n count?: number | null;\n }>,\n ): Promise<Page<z.infer<S>>> {\n const { data, error, count } = await build(this.client.from(table));\n if (error) {\n throw new IndexerQueryError(`Indexer query on \"${table}\" failed: ${error.message}`, error);\n }\n\n const rows = data ?? [];\n const hasMore = rows.length > limit;\n const parsed = (hasMore ? rows.slice(0, limit) : rows).map(\n (row) => schema.parse(row) as z.infer<S>,\n );\n\n return {\n data: parsed,\n // Never report a total below what was just handed out, however the estimate lands.\n total: Math.max(count ?? 0, parsed.length),\n hasMore,\n };\n }\n\n /** Single-row variant. Returns null for PostgREST's \"no rows\" code. */\n async selectOne<S extends z.ZodTypeAny>(\n table: string,\n schema: S,\n build: (q: ReturnType<AnyPostgrestClient[\"from\"]>) => PromiseLike<{\n data: unknown | null;\n error: { message: string; code?: string } | null;\n }>,\n ): Promise<z.infer<S> | null> {\n const { data, error } = await build(this.client.from(table));\n if (error) {\n if (error.code === 'PGRST116') return null; // no rows matched\n throw new IndexerQueryError(`Indexer query on \"${table}\" failed: ${error.message}`, error);\n }\n return data === null ? null : (schema.parse(data) as z.infer<S>);\n }\n\n /** The indexer's sync head, straight from the `indexer_state` table. */\n async state(): Promise<{ lastIndexedBlock: number; isSyncing: boolean } | null> {\n const row = await this.selectOne('indexer_state', IndexerStateSchema, (q) =>\n q.select('*').eq('id', 'main').single(),\n );\n if (!row) return null;\n return {\n lastIndexedBlock: toNumber(row.last_indexed_block),\n isSyncing: row.is_syncing ?? false,\n };\n }\n\n /**\n * Liveness and lag. Prefers the HTTP health endpoint (which knows the chain head)\n * and falls back to the `indexer_state` table when it is unreachable.\n */\n async health(force = false): Promise<IndexerHealth> {\n const now = Date.now();\n if (!force && this.healthCache && now - this.healthCache.at < this.healthCacheMs) {\n return this.healthCache.value;\n }\n if (this.inflightHealth) return this.inflightHealth;\n\n this.inflightHealth = this.probeHealth()\n .then((value) => {\n this.healthCache = { value, at: Date.now() };\n return value;\n })\n .finally(() => {\n this.inflightHealth = null;\n });\n\n return this.inflightHealth;\n }\n\n /**\n * Block until the indexer has processed `blockNumber`.\n *\n * Closes the write-then-read race: a transaction confirmed at block N is not\n * queryable until the indexer reaches N, so `propose()` immediately followed by\n * `pendingTransactions()` will silently miss it. Await this in between.\n *\n * Resolves immediately when the head is already at or past the target.\n */\n async waitForBlock(\n blockNumber: number,\n options: { timeoutMs?: number; pollIntervalMs?: number; signal?: AbortSignal } = {},\n ): Promise<{ reached: boolean; lastIndexedBlock: number }> {\n const timeoutMs = options.timeoutMs ?? 60_000;\n const pollIntervalMs = options.pollIntervalMs ?? 1_500;\n const deadline = Date.now() + timeoutMs;\n\n for (;;) {\n if (options.signal?.aborted) throw new AbortError('Waiting for the indexer');\n\n // Bypass the health cache: a stale hit would add a needless poll interval.\n const state = await this.state();\n const head = state?.lastIndexedBlock ?? 0;\n if (head >= blockNumber) return { reached: true, lastIndexedBlock: head };\n\n if (Date.now() + pollIntervalMs > deadline) {\n return { reached: false, lastIndexedBlock: head };\n }\n await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));\n }\n }\n\n private async probeHealth(): Promise<IndexerHealth> {\n if (this.config.healthUrl) {\n // One deadline covering headers *and* body. Clearing the timer as soon as\n // `fetch` resolved would leave `res.json()` unbounded, and a server that\n // answers its headers promptly then stalls the body would hang every `auto`\n // read behind it — `health()` gates them all.\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), 5_000);\n try {\n const res = await fetch(new URL('/health', this.config.healthUrl), {\n signal: controller.signal,\n });\n\n const body = (await res.json()) as {\n status?: string;\n details?: {\n currentBlock?: number;\n lastIndexedBlock?: number;\n blocksBehind?: number;\n isSyncing?: boolean;\n };\n };\n const d = body.details ?? {};\n return {\n available: res.ok && body.status === 'healthy',\n lastIndexedBlock: d.lastIndexedBlock ?? 0,\n chainHead: d.currentBlock,\n blocksBehind: d.blocksBehind,\n isSyncing: d.isSyncing ?? false,\n ...(res.ok ? {} : { error: `health endpoint returned ${res.status}` }),\n };\n } catch {\n // Fall through to the database probe — a dead health server does not imply\n // a dead indexer, and reads go to Supabase anyway.\n } finally {\n clearTimeout(timer);\n }\n }\n\n try {\n const state = await this.state();\n if (!state) {\n return { available: false, lastIndexedBlock: 0, isSyncing: false, error: 'no indexer_state row' };\n }\n return {\n available: true,\n lastIndexedBlock: state.lastIndexedBlock,\n isSyncing: state.isSyncing,\n };\n } catch (err) {\n return {\n available: false,\n lastIndexedBlock: 0,\n isSyncing: false,\n error: err instanceof Error ? err.message : String(err),\n };\n }\n }\n}\n\n/**\n * Normalise a project URL to a base with no trailing slash.\n *\n * `new URL('rest/v1', base)` — what supabase-js uses — silently replaces the last path\n * segment when the base carries a path, so a self-hosted indexer mounted under a\n * prefix would get the wrong endpoint. Concatenation is blunter and correct.\n */\nfunction baseUrl(url: string): string {\n return url.replace(/\\/+$/, '');\n}\n","import { z } from 'zod';\n\n/**\n * Row schemas for the indexer's Postgres tables.\n *\n * Mirrors quaivault-indexer/supabase/migrations/schema.sql. Parsing is strict on\n * shape but tolerant of added columns, so an indexer that ships new fields does not\n * break an older SDK.\n */\n\nconst address = z.string();\nconst nullableNumber = z.union([z.number(), z.string()]).nullable().optional();\n\nexport const WalletSchema = z.object({\n address: address,\n name: z.string().nullable().optional(),\n threshold: z.number(),\n owner_count: z.number(),\n created_at_block: z.union([z.number(), z.string()]),\n created_at_tx: z.string(),\n min_execution_delay: z.number().nullable().optional(),\n created_at: z.string().nullable().optional(),\n updated_at: z.string().nullable().optional(),\n});\nexport type WalletRow = z.infer<typeof WalletSchema>;\n\nexport const WalletOwnerSchema = z.object({\n wallet_address: address,\n owner_address: address,\n added_at_block: z.union([z.number(), z.string()]),\n added_at_tx: z.string(),\n removed_at_block: nullableNumber,\n removed_at_tx: z.string().nullable().optional(),\n is_active: z.boolean(),\n});\nexport type WalletOwnerRow = z.infer<typeof WalletOwnerSchema>;\n\nexport const TransactionStatusEnum = z.enum([\n 'pending',\n 'executed',\n 'cancelled',\n 'expired',\n 'failed',\n]);\n\nexport const TransactionSchema = z.object({\n wallet_address: address,\n tx_hash: z.string(),\n to_address: address,\n value: z.string(),\n data: z.string().nullable().optional(),\n transaction_type: z.string(),\n decoded_params: z.unknown().nullable().optional(),\n status: TransactionStatusEnum,\n confirmation_count: z.number().nullable().optional(),\n submitted_by: address,\n submitted_at_block: z.union([z.number(), z.string()]),\n submitted_at_tx: z.string(),\n executed_at_block: nullableNumber,\n executed_at_tx: z.string().nullable().optional(),\n executed_by: z.string().nullable().optional(),\n cancelled_at_block: nullableNumber,\n cancelled_at_tx: z.string().nullable().optional(),\n expiration: z.union([z.number(), z.string()]).nullable().optional(),\n execution_delay: z.number().nullable().optional(),\n approved_at: z.union([z.number(), z.string()]).nullable().optional(),\n executable_after: z.union([z.number(), z.string()]).nullable().optional(),\n is_expired: z.boolean().nullable().optional(),\n failed_return_data: z.string().nullable().optional(),\n created_at: z.string().nullable().optional(),\n updated_at: z.string().nullable().optional(),\n});\nexport type TransactionRow = z.infer<typeof TransactionSchema>;\n\nexport const ConfirmationSchema = z.object({\n wallet_address: address,\n tx_hash: z.string(),\n owner_address: address,\n confirmed_at_block: z.union([z.number(), z.string()]),\n confirmed_at_tx: z.string(),\n revoked_at_block: nullableNumber,\n revoked_at_tx: z.string().nullable().optional(),\n is_active: z.boolean(),\n});\nexport type ConfirmationRow = z.infer<typeof ConfirmationSchema>;\n\nexport const WalletModuleSchema = z.object({\n wallet_address: address,\n module_address: address,\n enabled_at_block: z.union([z.number(), z.string()]),\n enabled_at_tx: z.string(),\n disabled_at_block: nullableNumber,\n disabled_at_tx: z.string().nullable().optional(),\n is_active: z.boolean(),\n});\nexport type WalletModuleRow = z.infer<typeof WalletModuleSchema>;\n\nexport const DelegatecallTargetSchema = z.object({\n wallet_address: address,\n target_address: address,\n added_at_block: z.union([z.number(), z.string()]),\n added_at_tx: z.string(),\n removed_at_block: nullableNumber,\n removed_at_tx: z.string().nullable().optional(),\n is_active: z.boolean(),\n});\nexport type DelegatecallTargetRow = z.infer<typeof DelegatecallTargetSchema>;\n\nexport const DepositSchema = z.object({\n wallet_address: address,\n sender_address: address,\n amount: z.string(),\n deposited_at_block: z.union([z.number(), z.string()]),\n deposited_at_tx: z.string(),\n created_at: z.string().nullable().optional(),\n});\nexport type DepositRow = z.infer<typeof DepositSchema>;\n\nexport const TokenSchema = z.object({\n address: address,\n standard: z.enum(['ERC20', 'ERC721', 'ERC1155']),\n symbol: z.string(),\n name: z.string(),\n decimals: z.number(),\n discovered_at_block: nullableNumber,\n discovered_via: z.string().nullable().optional(),\n});\nexport type TokenRow = z.infer<typeof TokenSchema>;\n\nexport const TokenTransferSchema = z.object({\n token_address: address,\n wallet_address: address,\n from_address: address,\n to_address: address,\n value: z.string(),\n token_id: z.string().nullable().optional(),\n batch_index: z.number().nullable().optional(),\n direction: z.enum(['inflow', 'outflow']),\n block_number: z.union([z.number(), z.string()]),\n transaction_hash: z.string(),\n log_index: z.number(),\n});\nexport type TokenTransferRow = z.infer<typeof TokenTransferSchema>;\n\nexport const SignedMessageSchema = z.object({\n wallet_address: address,\n msg_hash: z.string(),\n data: z.string().nullable().optional(),\n signed_at_block: z.union([z.number(), z.string()]),\n signed_at_tx: z.string(),\n unsigned_at_block: nullableNumber,\n unsigned_at_tx: z.string().nullable().optional(),\n is_active: z.boolean(),\n});\nexport type SignedMessageRow = z.infer<typeof SignedMessageSchema>;\n\nexport const IndexerStateSchema = z.object({\n id: z.string(),\n last_indexed_block: z.union([z.number(), z.string()]),\n last_block_hash: z.string().nullable().optional(),\n last_indexed_at: z.string().nullable().optional(),\n is_syncing: z.boolean().nullable().optional(),\n});\nexport type IndexerStateRow = z.infer<typeof IndexerStateSchema>;\n\nexport const RecoveryConfigSchema = z.object({\n wallet_address: address,\n threshold: z.number(),\n recovery_period: z.union([z.number(), z.string()]),\n setup_at_block: z.union([z.number(), z.string()]),\n setup_at_tx: z.string(),\n is_active: z.boolean(),\n});\nexport type RecoveryConfigRow = z.infer<typeof RecoveryConfigSchema>;\n\nexport const RecoveryGuardianSchema = z.object({\n wallet_address: address,\n guardian_address: address,\n added_at_block: z.union([z.number(), z.string()]),\n added_at_tx: z.string(),\n is_active: z.boolean(),\n});\nexport type RecoveryGuardianRow = z.infer<typeof RecoveryGuardianSchema>;\n\nexport const RecoverySchema = z.object({\n wallet_address: address,\n recovery_hash: z.string(),\n new_owners: z.array(address),\n new_threshold: z.number(),\n initiator_address: address,\n approval_count: z.number().nullable().optional(),\n required_threshold: z.number(),\n execution_time: z.union([z.number(), z.string()]),\n status: z.enum(['pending', 'executed', 'cancelled', 'invalidated', 'expired']),\n initiated_at_block: z.union([z.number(), z.string()]),\n initiated_at_tx: z.string(),\n expiration: z.union([z.number(), z.string()]).nullable().optional(),\n});\nexport type RecoveryRow = z.infer<typeof RecoverySchema>;\n\nexport const RecoveryApprovalSchema = z.object({\n wallet_address: address,\n recovery_hash: z.string(),\n guardian_address: address,\n approved_at_block: z.union([z.number(), z.string()]),\n approved_at_tx: z.string(),\n is_active: z.boolean(),\n});\nexport type RecoveryApprovalRow = z.infer<typeof RecoveryApprovalSchema>;\n\n/** Coerce the bigint-ish columns Postgres returns as strings. */\nexport function toNumber(value: unknown, fallback = 0): number {\n if (value === null || value === undefined) return fallback;\n const n = typeof value === 'string' ? Number(value) : (value as number);\n return Number.isFinite(n) ? n : fallback;\n}\n","import type { IndexerClient } from './client.js';\nimport {\n ConfirmationSchema,\n DelegatecallTargetSchema,\n DepositSchema,\n RecoveryApprovalSchema,\n RecoveryConfigSchema,\n RecoveryGuardianSchema,\n RecoverySchema,\n SignedMessageSchema,\n TokenSchema,\n TokenTransferSchema,\n TransactionSchema,\n WalletModuleSchema,\n WalletOwnerSchema,\n WalletSchema,\n type ConfirmationRow,\n type DepositRow,\n type RecoveryApprovalRow,\n type RecoveryRow,\n type SignedMessageRow,\n type TokenRow,\n type TokenTransferRow,\n type TransactionRow,\n type WalletRow,\n} from './schemas.js';\nimport { IndexerQueryError } from '../errors/index.js';\nimport type { Address, Page, Pagination } from '../types.js';\n\nconst DEFAULT_LIMIT = 50;\n/**\n * Rows a single request may ask for.\n *\n * PostgREST is happy to return more, but a large page is also a large response to\n * hold and parse, and it makes a slow query slower rather than failing fast. Callers\n * that genuinely need more should page — see {@link IndexerQueries.tokenTransferScan}\n * for the pattern.\n */\nexport const MAX_LIMIT = 200;\n/**\n * Transaction hashes per `in(...)` filter in {@link IndexerQueries.activeConfirmationsBatch}.\n *\n * 40 keeps the request line near 3 KB and the worst-case response at\n * `40 × MAX_OWNERS = 800` rows — both comfortably inside the defaults that would\n * otherwise truncate the result without saying so.\n */\nconst CONFIRMATION_CHUNK = 40;\n\nfunction lower(address: Address): string {\n return address.toLowerCase();\n}\n\nfunction bounds(options: Pagination = {}) {\n const limit = Math.min(Math.max(options.limit ?? DEFAULT_LIMIT, 1), MAX_LIMIT);\n const offset = Math.max(options.offset ?? 0, 0);\n return { limit, offset };\n}\n\nexport class IndexerQueries {\n constructor(private readonly client: IndexerClient) {}\n\n // ---- wallets -------------------------------------------------------------\n\n async wallet(address: Address): Promise<WalletRow | null> {\n return this.client.selectOne('wallets', WalletSchema, (q) =>\n q.select('*').eq('address', lower(address)).single(),\n );\n }\n\n /** Active owner addresses, lowercased as stored. */\n async owners(address: Address): Promise<string[]> {\n const rows = await this.client.select('wallet_owners', WalletOwnerSchema, (q) =>\n q.select('*').eq('wallet_address', lower(address)).eq('is_active', true),\n );\n return rows.map((r) => r.owner_address);\n }\n\n async vaultsForOwner(owner: Address, options: Pagination = {}): Promise<WalletRow[]> {\n const { limit, offset } = bounds(options);\n const { data, error } = await this.client\n .from('wallet_owners')\n .select('wallet_address, wallets (*)')\n .eq('owner_address', lower(owner))\n .eq('is_active', true)\n .range(offset, offset + limit - 1);\n\n if (error) throw new IndexerQueryError(`Indexer query failed: ${error.message}`, error);\n return extractJoined(data, WalletSchema);\n }\n\n async vaultsForGuardian(guardian: Address, options: Pagination = {}): Promise<WalletRow[]> {\n const { limit, offset } = bounds(options);\n const { data, error } = await this.client\n .from('social_recovery_guardians')\n .select('wallet_address, wallets (*)')\n .eq('guardian_address', lower(guardian))\n .eq('is_active', true)\n .range(offset, offset + limit - 1);\n\n if (error) throw new IndexerQueryError(`Indexer query failed: ${error.message}`, error);\n return extractJoined(data, WalletSchema);\n }\n\n // ---- transactions --------------------------------------------------------\n\n async pendingTransactions(vault: Address, options: Pagination = {}): Promise<TransactionRow[]> {\n const { limit, offset } = bounds(options);\n return this.client.select('transactions', TransactionSchema, (q) =>\n q\n .select('*')\n .eq('wallet_address', lower(vault))\n .eq('status', 'pending')\n .order('submitted_at_block', { ascending: false })\n .range(offset, offset + limit - 1),\n );\n }\n\n async transaction(vault: Address, txHash: string): Promise<TransactionRow | null> {\n return this.client.selectOne('transactions', TransactionSchema, (q) =>\n q.select('*').eq('wallet_address', lower(vault)).eq('tx_hash', txHash.toLowerCase()).single(),\n );\n }\n\n /**\n * Several transactions by hash, chunked for the same reasons as\n * {@link activeConfirmationsBatch} — hashes are long, and they go in the query string.\n *\n * Rows come back in no particular order and hashes with no row are simply absent;\n * the caller matches them up.\n */\n async transactionsByHash(vault: Address, txHashes: string[]): Promise<TransactionRow[]> {\n if (txHashes.length === 0) return [];\n\n const hashes = txHashes.map((h) => h.toLowerCase());\n const chunks: string[][] = [];\n for (let i = 0; i < hashes.length; i += CONFIRMATION_CHUNK) {\n chunks.push(hashes.slice(i, i + CONFIRMATION_CHUNK));\n }\n\n const pages = await Promise.all(\n chunks.map((chunk) =>\n this.client.select('transactions', TransactionSchema, (q) =>\n q.select('*').eq('wallet_address', lower(vault)).in('tx_hash', chunk),\n ),\n ),\n );\n return pages.flat();\n }\n\n async transactionHistory(\n vault: Address,\n options: Pagination & { status?: string[] } = {},\n ): Promise<Page<TransactionRow>> {\n const { limit, offset } = bounds(options);\n const statuses = options.status ?? ['executed', 'cancelled', 'expired', 'failed'];\n\n return this.client.selectPage('transactions', TransactionSchema, limit, (q) =>\n q\n .select('*', { count: 'estimated' })\n .eq('wallet_address', lower(vault))\n .in('status', statuses)\n .order('submitted_at_block', { ascending: false })\n // One past the page, so `hasMore` is exact. See `selectPage`.\n .range(offset, offset + limit),\n );\n }\n\n /** All confirmations for one transaction, including revoked ones. */\n async confirmations(vault: Address, txHash: string): Promise<ConfirmationRow[]> {\n return this.client.select('confirmations', ConfirmationSchema, (q) =>\n q\n .select('*')\n .eq('wallet_address', lower(vault))\n .eq('tx_hash', txHash.toLowerCase())\n .order('confirmed_at_block', { ascending: true }),\n );\n }\n\n /**\n * Active confirmations for many transactions, in as few round trips as is safe.\n *\n * \"Active\" here means not revoked. It does NOT mean the confirming address is\n * still an owner — the indexer does not deactivate confirmations when an owner is\n * removed, while the contract invalidates them via approval epochs. Callers must\n * intersect with the active owner set; `Vault` does this for you.\n *\n * Chunked rather than issued as one `in(...)`, because a single filter fails two\n * ways at scale. PostgREST reads filters from the query string, and each 32-byte\n * hash costs ~70 characters there — a full {@link MAX_LIMIT} page of hashes builds a\n * ~14 KB request line, past the 8 KB cap most reverse proxies apply by default. The\n * response is bounded too: {@link CONFIRMATION_CHUNK} transactions can carry at most\n * `chunk × MAX_OWNERS` rows, and the chunk is sized to keep that under the\n * `max-rows` ceiling PostgREST deployments commonly set, so a busy vault cannot be\n * silently short-served.\n */\n async activeConfirmationsBatch(\n vault: Address,\n txHashes: string[],\n ): Promise<Map<string, ConfirmationRow[]>> {\n const result = new Map<string, ConfirmationRow[]>();\n for (const hash of txHashes) result.set(hash.toLowerCase(), []);\n if (txHashes.length === 0) return result;\n\n const hashes = txHashes.map((h) => h.toLowerCase());\n const chunks: string[][] = [];\n for (let i = 0; i < hashes.length; i += CONFIRMATION_CHUNK) {\n chunks.push(hashes.slice(i, i + CONFIRMATION_CHUNK));\n }\n\n const pages = await Promise.all(\n chunks.map((chunk) =>\n this.client.select('confirmations', ConfirmationSchema, (q) =>\n q\n .select('*')\n .eq('wallet_address', lower(vault))\n .in('tx_hash', chunk)\n .eq('is_active', true),\n ),\n ),\n );\n\n for (const row of pages.flat()) {\n const key = row.tx_hash.toLowerCase();\n const list = result.get(key);\n if (list) list.push(row);\n else result.set(key, [row]);\n }\n return result;\n }\n\n // ---- modules and delegatecall --------------------------------------------\n\n async modules(vault: Address): Promise<string[]> {\n const rows = await this.client.select('wallet_modules', WalletModuleSchema, (q) =>\n q.select('*').eq('wallet_address', lower(vault)).eq('is_active', true),\n );\n return rows.map((r) => r.module_address);\n }\n\n async delegatecallTargets(vault: Address): Promise<string[]> {\n const rows = await this.client.select(\n 'wallet_delegatecall_targets',\n DelegatecallTargetSchema,\n (q) => q.select('*').eq('wallet_address', lower(vault)).eq('is_active', true),\n );\n return rows.map((r) => r.target_address);\n }\n\n // ---- value movement ------------------------------------------------------\n\n async deposits(vault: Address, options: Pagination = {}): Promise<Page<DepositRow>> {\n const { limit, offset } = bounds(options);\n return this.client.selectPage('deposits', DepositSchema, limit, (q) =>\n q\n .select('*', { count: 'estimated' })\n .eq('wallet_address', lower(vault))\n .order('deposited_at_block', { ascending: false })\n .range(offset, offset + limit),\n );\n }\n\n async tokenTransfers(vault: Address, options: Pagination = {}): Promise<Page<TokenTransferRow>> {\n const { limit, offset } = bounds(options);\n return this.client.selectPage('token_transfers', TokenTransferSchema, limit, (q) =>\n q\n .select('*', { count: 'estimated' })\n .eq('wallet_address', lower(vault))\n .order('block_number', { ascending: false })\n .range(offset, offset + limit),\n );\n }\n\n /**\n * Scan up to `budget` of the most recent transfer rows, paging past {@link MAX_LIMIT}.\n *\n * `tokenTransfers` clamps a single request, so a caller asking for more than the cap\n * silently received a short page — and then computed \"did I see everything?\" from\n * that short page's `hasMore`, which reported truncation the caller had not actually\n * hit. Paging here keeps the caller's budget meaningful and makes the returned\n * `hasMore` mean what it says: rows exist beyond the budget that was scanned.\n *\n * Pages by offset over a descending order, so a transfer landing mid-scan can shift\n * rows by one. That is acceptable for token *discovery* — a duplicate collapses into\n * the same map key and a missed row costs at most one candidate that the next call\n * picks up. Do not reuse this for anything that must see each row exactly once.\n */\n async tokenTransferScan(vault: Address, budget: number): Promise<Page<TokenTransferRow>> {\n const target = Math.max(1, Math.floor(budget));\n const data: TokenTransferRow[] = [];\n let total = 0;\n let hasMore = false;\n\n while (data.length < target) {\n const page = await this.tokenTransfers(vault, {\n limit: Math.min(MAX_LIMIT, target - data.length),\n offset: data.length,\n });\n data.push(...page.data);\n total = page.total;\n hasMore = page.hasMore;\n // A short page means the table is exhausted, whatever `total` claims.\n if (page.data.length === 0 || !page.hasMore) break;\n }\n\n return { data, total, hasMore };\n }\n\n async tokens(addresses: string[]): Promise<TokenRow[]> {\n if (addresses.length === 0) return [];\n return this.client.select('tokens', TokenSchema, (q) =>\n q.select('*').in('address', addresses.map(lower)),\n );\n }\n\n async signedMessages(vault: Address): Promise<SignedMessageRow[]> {\n return this.client.select('signed_messages', SignedMessageSchema, (q) =>\n q.select('*').eq('wallet_address', lower(vault)).eq('is_active', true),\n );\n }\n\n // ---- social recovery -----------------------------------------------------\n\n async recoveryConfig(\n vault: Address,\n ): Promise<{ threshold: number; recoveryPeriod: number; guardians: string[] } | null> {\n const config = await this.client.selectOne('social_recovery_configs', RecoveryConfigSchema, (q) =>\n q.select('*').eq('wallet_address', lower(vault)).eq('is_active', true).single(),\n );\n if (!config) return null;\n\n const guardians = await this.client.select(\n 'social_recovery_guardians',\n RecoveryGuardianSchema,\n (q) => q.select('*').eq('wallet_address', lower(vault)).eq('is_active', true),\n );\n\n return {\n threshold: config.threshold,\n recoveryPeriod: Number(config.recovery_period),\n guardians: guardians.map((g) => g.guardian_address),\n };\n }\n\n async pendingRecoveries(vault: Address): Promise<RecoveryRow[]> {\n return this.client.select('social_recoveries', RecoverySchema, (q) =>\n q.select('*').eq('wallet_address', lower(vault)).eq('status', 'pending'),\n );\n }\n\n async recoveryHistory(vault: Address, options: Pagination = {}): Promise<RecoveryRow[]> {\n const { limit, offset } = bounds(options);\n return this.client.select('social_recoveries', RecoverySchema, (q) =>\n q\n .select('*')\n .eq('wallet_address', lower(vault))\n .order('initiated_at_block', { ascending: false })\n .range(offset, offset + limit - 1),\n );\n }\n\n async recoveryApprovals(vault: Address, recoveryHash: string): Promise<RecoveryApprovalRow[]> {\n return this.client.select('social_recovery_approvals', RecoveryApprovalSchema, (q) =>\n q\n .select('*')\n .eq('wallet_address', lower(vault))\n .eq('recovery_hash', recoveryHash.toLowerCase())\n .eq('is_active', true),\n );\n }\n}\n\n/**\n * Pull the embedded rows out of a PostgREST join, dropping any that fail validation\n * rather than failing the whole query over one malformed row.\n */\nfunction extractJoined<T>(\n data: unknown[] | null,\n schema: { parse: (value: unknown) => T },\n): T[] {\n const out: T[] = [];\n for (const row of data ?? []) {\n const embedded = (row as { wallets?: unknown }).wallets;\n if (!embedded) continue;\n // PostgREST returns an object for a to-one join, an array for to-many.\n const candidates = Array.isArray(embedded) ? embedded : [embedded];\n for (const candidate of candidates) {\n try {\n out.push(schema.parse(candidate));\n } catch {\n continue;\n }\n }\n }\n return out;\n}\n","import { formatQuai, getAddress, getZoneForAddress, toShard } from 'quais';\nimport { assertQuaiAddress, assertQuaiAddresses } from './address.js';\nimport type { Connection } from './chain/connection.js';\nimport { VaultContract } from './chain/vault-contract.js';\nimport { RecoveryModule } from './recovery.js';\nimport { loadBalances, type BalanceOptions, type VaultBalances } from './balances.js';\nimport { watchVault, type Subscription, type WatchEvent, type WatchOptions } from './indexer/watch.js';\nimport { normalizeTxHash } from './chain/connection.js';\nimport type { IndexerClient } from './indexer/client.js';\nimport type { IndexerQueries } from './indexer/queries.js';\nimport type { TransactionRow } from './indexer/schemas.js';\nimport { toNumber } from './indexer/schemas.js';\nimport { decodeCall, type DecodedBatchCall } from './decode/index.js';\nimport { decodeRevert, decodeRevertFromError } from './errors/decode.js';\nimport {\n MAX_EXECUTION_DELAY,\n SENTINEL_MODULES,\n encodeMultiSend,\n minimumExpiration,\n selfCall,\n token as tokenEncode,\n recoveryCall,\n type BatchCall,\n} from './encode/index.js';\nimport {\n AbortError,\n NoIndexerError,\n NotFoundError,\n PreconditionError,\n RevertError,\n StaleProposalError,\n ValidationError,\n} from './errors/index.js';\nimport { DEFAULT_CONCURRENCY, mapPooled } from './pool.js';\nimport { computeAffordances } from './lifecycle/affordances.js';\nimport { classifyExecution, extractProposedTxHash, type ReceiptLike } from './lifecycle/outcome.js';\nimport { deriveStatus, executableAfterOf, nowSeconds } from './lifecycle/status.js';\nimport type {\n Address,\n Affordance,\n ApprovalRecord,\n Bytes32,\n ContractAddresses,\n Consistency,\n DryRunResult,\n ExecuteResult,\n Hex,\n Page,\n Pagination,\n ProposeOptions,\n ProposeResult,\n VaultInfo,\n VaultTransaction,\n} from './types.js';\n\nexport interface VaultContext {\n connection: Connection;\n indexer: IndexerClient | null;\n queries: IndexerQueries | null;\n contracts: ContractAddresses;\n consistency: Consistency;\n maxIndexerLagBlocks: number;\n /** Set by {@link Vault.pinned}. Never consulted by a write precondition. */\n view?: VaultView;\n}\n\n/**\n * Owners and threshold, captured at one instant.\n *\n * The SDK deliberately holds no read cache: the owner set decides which approvals\n * count toward the threshold, and serving a stale one silently would reintroduce the\n * exact bug `buildTransaction` intersects confirmations to avoid. An implicit TTL\n * would make that failure invisible and intermittent.\n *\n * So the staleness window is the caller's to open, and to see. `capturedAt` is right\n * there in the object; a CLI rendering one screen can pin a view for that screen and\n * know precisely what it pinned.\n */\nexport interface VaultView {\n owners: Address[];\n threshold: number;\n /** Indexer head when this was taken; absent if the snapshot came from chain. */\n indexedAtBlock?: number;\n /** Unix seconds. How stale the snapshot is allowed to get is the caller's call. */\n capturedAt: number;\n source: 'indexer' | 'chain';\n}\n\n/** A handle to one deployed vault. Cheap to construct; performs no I/O until used. */\nexport class Vault {\n readonly address: Address;\n /** Guardian-based recovery for this vault. */\n readonly recovery: RecoveryModule;\n private readonly ctx: VaultContext;\n\n constructor(address: Address, ctx: VaultContext) {\n // A deployed vault is always a Quai-ledger contract in a real zone, so anything\n // else is a typo or a Qi address and would fail every call.\n this.address = assertQuaiAddress(address, 'vault address');\n this.ctx = ctx;\n this.recovery = new RecoveryModule({\n connection: ctx.connection,\n queries: ctx.queries,\n vaultAddress: this.address,\n moduleAddress: ctx.contracts.socialRecovery,\n });\n }\n\n // =========================================================================\n // Read resolution\n // =========================================================================\n\n /**\n * Whether an indexer read is acceptable right now.\n *\n * `auto` uses the indexer only while it is live and within the configured lag\n * budget, so a stalled indexer silently degrades to chain reads instead of\n * serving stale state.\n */\n private async useIndexer(): Promise<boolean> {\n if (this.ctx.consistency === 'chain') return false;\n if (!this.ctx.indexer || !this.ctx.queries) {\n if (this.ctx.consistency === 'indexed') throw new NoIndexerError('This read');\n return false;\n }\n if (this.ctx.consistency === 'indexed') return true;\n\n const health = await this.ctx.indexer.health();\n if (!health.available) return false;\n if (health.blocksBehind !== undefined && health.blocksBehind > this.ctx.maxIndexerLagBlocks) {\n return false;\n }\n return true;\n }\n\n private requireQueries(operation: string): IndexerQueries {\n if (!this.ctx.queries) throw new NoIndexerError(operation);\n return this.ctx.queries;\n }\n\n /**\n * The indexer's head, for stamping onto records read from it.\n *\n * Reads the cached health result rather than querying `indexer_state` directly.\n * `useIndexer()` has just called `health()` on this same code path and the result is\n * cached, so this is free — whereas a `state()` call is a second round trip per\n * hydration, paid on every indexed read purely to fill one advisory field.\n *\n * Undefined when the indexer is not answering: a head of 0 would read as \"indexed at\n * genesis\" rather than \"unknown\".\n */\n private async indexerHead(): Promise<number | undefined> {\n const health = await this.ctx.indexer?.health();\n return health?.available ? health.lastIndexedBlock : undefined;\n }\n\n private contract(write = false): VaultContract {\n return new VaultContract(this.ctx.connection.vault(this.address, write), this.ctx.connection.retry);\n }\n\n // =========================================================================\n // Vault state\n // =========================================================================\n\n /** Owners, threshold, timelock floor, nonce and balance. Always read from chain. */\n async info(): Promise<VaultInfo> {\n const vault = this.contract();\n const [owners, threshold, minExecutionDelay, nonce, moduleCount, balance] = await Promise.all([\n vault.getOwners(),\n vault.threshold(),\n vault.minExecutionDelay(),\n vault.nonce(),\n vault.moduleCount(),\n this.ctx.connection.provider.getBalance(this.address),\n ]);\n\n return {\n address: this.address,\n owners: Array.from(owners).map((o) => getAddress(String(o))),\n threshold: Number(threshold),\n minExecutionDelay: Number(minExecutionDelay),\n nonce: Number(nonce),\n moduleCount: Number(moduleCount),\n balance: BigInt(balance),\n };\n }\n\n /**\n * Capture owners and threshold once, for reuse across a burst of reads.\n *\n * Pair with {@link pinned}:\n *\n * ```ts\n * const view = await vault.view();\n * const pinned = vault.pinned(view);\n * // every read below shares one owner/threshold read\n * const txs = await pinned.transactions(hashes);\n * ```\n */\n async view(): Promise<VaultView> {\n const fromIndexer = await this.useIndexer();\n const [owners, threshold, indexedAtBlock] = await Promise.all([\n this.owners(),\n this.threshold(),\n this.indexerHead(),\n ]);\n return {\n owners,\n threshold,\n ...(indexedAtBlock !== undefined ? { indexedAtBlock } : {}),\n capturedAt: nowSeconds(),\n source: fromIndexer ? 'indexer' : 'chain',\n };\n }\n\n /**\n * A handle that answers {@link owners} and {@link threshold} from `view` instead of\n * re-reading them.\n *\n * Reads only. Write preconditions go through `chainOwners` / `chainThreshold`, which\n * bypass the snapshot by construction — pinning a view can never cause this SDK to\n * sign against a stale owner set. Everything else about the handle, including the\n * connection and the recovery module, is shared with the original.\n */\n pinned(view: VaultView): Vault {\n return new Vault(this.address, { ...this.ctx, view });\n }\n\n /** Active owners. Prefers a pinned view, then the indexer, then chain. */\n async owners(): Promise<Address[]> {\n if (this.ctx.view) return this.ctx.view.owners;\n if (await this.useIndexer()) {\n try {\n const owners = await this.requireQueries('owners').owners(this.address);\n if (owners.length > 0) return owners.map((o) => getAddress(o));\n } catch {\n // fall through to chain\n }\n }\n return this.chainOwners();\n }\n\n /**\n * Owners straight from the chain, bypassing the indexer entirely.\n *\n * {@link owners} prefers the indexer, which is right for display and wrong for\n * anything that gates a write. A lagging indexer would let the SDK build a proposal\n * against an owner set that no longer exists — admitting a `removeOwner` that drops\n * the vault below its threshold, or rejecting one that is perfectly valid. Every\n * propose-time precondition reads through here instead.\n */\n private async chainOwners(): Promise<Address[]> {\n return (await this.contract().getOwners()).map((o) => getAddress(String(o)));\n }\n\n async isOwner(address: Address): Promise<boolean> {\n return this.contract().isOwner(getAddress(address));\n }\n\n /** Approvals required to execute. Prefers a pinned view, then the indexer, then chain. */\n async threshold(): Promise<number> {\n if (this.ctx.view) return this.ctx.view.threshold;\n if (await this.useIndexer()) {\n try {\n const wallet = await this.requireQueries('threshold').wallet(this.address);\n if (wallet) return wallet.threshold;\n } catch {\n // fall through to chain\n }\n }\n return this.chainThreshold();\n }\n\n /**\n * Threshold straight from the chain. The write-path counterpart to {@link threshold},\n * for the same reason {@link chainOwners} exists.\n */\n private async chainThreshold(): Promise<number> {\n return Number(await this.contract().threshold());\n }\n\n async balance(): Promise<bigint> {\n return BigInt(await this.ctx.connection.provider.getBalance(this.address));\n }\n\n /**\n * Enabled modules, in linked-list order.\n *\n * Order matters: `disableModule` needs each module's predecessor, so this always\n * reads the chain rather than the indexer (which stores an unordered set).\n */\n async modules(): Promise<Address[]> {\n return (await this.contract().getModules()).map((m) => getAddress(String(m)));\n }\n\n async isModuleEnabled(module: Address): Promise<boolean> {\n return this.contract().isModuleEnabled(getAddress(module));\n }\n\n /** Addresses permitted as DelegateCall targets. Empty means DelegateCall is disabled. */\n async delegatecallTargets(): Promise<Address[]> {\n // Indexer-only, with no fallback and no retry-on-failure: `delegatecallAllowed`\n // is a mapping, so the chain cannot enumerate it. A failure here is terminal, and\n // swallowing it only to reissue the identical query would double the load and\n // surface a more confusing second error. Use `isDelegatecallAllowed(target)` to\n // check a specific address against the chain.\n const targets = await this.requireQueries('Listing DelegateCall targets').delegatecallTargets(\n this.address,\n );\n return targets.map((t) => getAddress(t));\n }\n\n async isDelegatecallAllowed(target: Address): Promise<boolean> {\n return this.contract().delegatecallAllowed(getAddress(target));\n }\n\n /** Whether a hash has been pre-approved for EIP-1271 validation. */\n async isValidSignature(hash: Bytes32): Promise<boolean> {\n const magic = await this.contract().isValidSignature(normalizeTxHash(hash, 'hash'), '0x');\n return magic.toLowerCase() === '0x1626ba7e';\n }\n\n // =========================================================================\n // Transactions\n // =========================================================================\n\n /** The vault-transaction hash for a given call, at a given nonce. */\n async transactionHash(\n to: Address,\n value: bigint,\n data: Hex,\n nonce?: number,\n ): Promise<Bytes32> {\n const vault = this.contract();\n const n = nonce ?? Number(await vault.nonce());\n return vault.getTransactionHash(getAddress(to), value, data, n);\n }\n\n async transaction(txHash: Bytes32): Promise<VaultTransaction> {\n const hash = normalizeTxHash(txHash);\n\n if (await this.useIndexer()) {\n try {\n const tx = await this.fromIndexer(hash);\n if (tx) return tx;\n } catch {\n // fall through to chain\n }\n }\n return this.fromChain(hash);\n }\n\n /**\n * Several transactions at once, keyed by hash.\n *\n * The plural form exists because the singular one is expensive to loop: each\n * `transaction()` re-reads the owner set, the threshold and the indexer head, so\n * fetching fifty costs fifty times that. This resolves the whole set the way the\n * listing methods already do — one query for the rows, one owner/threshold read\n * shared across them, one batched confirmations query.\n *\n * Hashes the indexer does not have fall back to chain reads, bounded by a pool.\n * Hashes that exist nowhere are simply absent from the map rather than throwing:\n * one unknown hash should not lose the caller the other forty-nine.\n */\n async transactions(txHashes: Bytes32[]): Promise<Map<Bytes32, VaultTransaction>> {\n const hashes = [...new Set(txHashes.map((h) => normalizeTxHash(h)))];\n const found = new Map<Bytes32, VaultTransaction>();\n if (hashes.length === 0) return found;\n\n if (await this.useIndexer()) {\n try {\n const queries = this.requireQueries('Reading transactions');\n const [rows, owners, threshold] = await Promise.all([\n queries.transactionsByHash(this.address, hashes),\n this.owners(),\n this.threshold(),\n ]);\n for (const tx of await this.hydrateRows(rows, owners, threshold)) {\n found.set(tx.hash.toLowerCase(), tx);\n }\n } catch {\n // fall through — every hash is resolved from chain below\n }\n }\n\n const missing = hashes.filter((hash) => !found.has(hash));\n if (missing.length > 0) {\n const resolved = await mapPooled(missing, DEFAULT_CONCURRENCY, async (hash) => {\n try {\n return await this.fromChain(hash);\n } catch (err) {\n // A hash that exists on neither side is a miss, not a failure. Anything\n // else — an RPC outage, a malformed response — is the caller's to see.\n if (err instanceof NotFoundError) return null;\n throw err;\n }\n });\n for (const tx of resolved) {\n if (tx) found.set(tx.hash.toLowerCase(), tx);\n }\n }\n\n return found;\n }\n\n async pendingTransactions(options: Pagination = {}): Promise<VaultTransaction[]> {\n const queries = this.requireQueries('Listing pending transactions');\n const [rows, owners, threshold] = await Promise.all([\n queries.pendingTransactions(this.address, options),\n this.owners(),\n this.threshold(),\n ]);\n return this.hydrateRows(rows, owners, threshold);\n }\n\n async transactionHistory(\n options: Pagination & { status?: string[] } = {},\n ): Promise<Page<VaultTransaction>> {\n const queries = this.requireQueries('Listing transaction history');\n const [page, owners, threshold] = await Promise.all([\n queries.transactionHistory(this.address, options),\n this.owners(),\n this.threshold(),\n ]);\n return {\n data: await this.hydrateRows(page.data, owners, threshold),\n total: page.total,\n hasMore: page.hasMore,\n };\n }\n\n // ---- hydration -----------------------------------------------------------\n\n private async hydrateRows(\n rows: TransactionRow[],\n owners: Address[],\n threshold: number,\n ): Promise<VaultTransaction[]> {\n if (rows.length === 0) return [];\n const queries = this.requireQueries('Loading confirmations');\n const confirmations = await queries.activeConfirmationsBatch(\n this.address,\n rows.map((r) => r.tx_hash),\n );\n const indexedAtBlock = await this.indexerHead();\n\n return rows.map((row) => {\n const confirmed = (confirmations.get(row.tx_hash.toLowerCase()) ?? []).map(\n (c) => c.owner_address,\n );\n return this.buildTransaction({\n row,\n confirmedBy: confirmed,\n owners,\n threshold,\n indexedAtBlock,\n });\n });\n }\n\n private async fromIndexer(hash: Bytes32): Promise<VaultTransaction | null> {\n const queries = this.requireQueries('Reading a transaction');\n const [row, owners, threshold] = await Promise.all([\n queries.transaction(this.address, hash),\n this.owners(),\n this.threshold(),\n ]);\n if (!row) return null;\n\n const confirmations = await queries.confirmations(this.address, hash);\n const indexedAtBlock = await this.indexerHead();\n\n return this.buildTransaction({\n row,\n confirmedBy: confirmations.filter((c) => c.is_active).map((c) => c.owner_address),\n owners,\n threshold,\n indexedAtBlock,\n });\n }\n\n /**\n * Build a `VaultTransaction` from an indexed row.\n *\n * Approval counting intersects the indexer's confirmations with the current owner\n * set. The indexer marks a confirmation inactive only on an explicit\n * `ApprovalRevoked`; it does not react to `OwnerRemoved`. On chain, removing an\n * owner bumps `ownerVersions` and invalidates every approval that address made, so\n * the stored `confirmation_count` over-reports after any removal. Intersecting here\n * reproduces the contract's `_countValidApprovals`.\n */\n private buildTransaction(input: {\n row: TransactionRow;\n confirmedBy: string[];\n owners: Address[];\n threshold: number;\n indexedAtBlock?: number;\n }): VaultTransaction {\n const { row, owners, threshold, indexedAtBlock } = input;\n const ownerSet = new Set(owners.map((o) => o.toLowerCase()));\n const confirmedSet = new Set(input.confirmedBy.map((c) => c.toLowerCase()));\n\n const approvals: ApprovalRecord[] = owners\n .filter((o) => confirmedSet.has(o.toLowerCase()))\n .map((o) => ({ owner: o, active: true }));\n\n // Confirmations from addresses that are no longer owners: surfaced but not counted.\n for (const confirmed of confirmedSet) {\n if (!ownerSet.has(confirmed)) {\n approvals.push({ owner: getAddress(confirmed), active: false });\n }\n }\n\n const approvalCount = approvals.filter((a) => a.active).length;\n const value = BigInt(row.value);\n const data = (row.data ?? '0x') as Hex;\n const to = getAddress(row.to_address);\n\n const decodeResult = decodeCall({\n vault: this.address,\n to,\n value,\n data,\n socialRecovery: this.ctx.contracts.socialRecovery,\n multiSendCallOnly: this.ctx.contracts.multiSendCallOnly,\n });\n\n const expiration = toNumber(row.expiration);\n const executionDelay = toNumber(row.execution_delay);\n const approvedAt = toNumber(row.approved_at);\n\n const status = deriveStatus({\n executed: row.status === 'executed' || row.status === 'failed',\n cancelled: row.status === 'cancelled' || row.status === 'expired',\n isExpired: row.is_expired ?? row.status === 'expired',\n expiration,\n executionDelay,\n approvedAt,\n approvalCount,\n threshold,\n failed: row.status === 'failed',\n });\n\n const failedReturnData = row.failed_return_data ?? undefined;\n\n return {\n hash: row.tx_hash,\n vault: this.address,\n to,\n value,\n data,\n proposer: getAddress(row.submitted_by),\n // The indexer records the block, not the chain timestamp — they are not\n // interchangeable, and reporting a block number as `proposedAt` renders as 1970.\n proposedAt: 0,\n proposedAtBlock: toNumber(row.submitted_at_block),\n kind: decodeResult.kind,\n decoded: decodeResult.decoded,\n summary: decodeResult.summary,\n status,\n approvals,\n approvalCount,\n threshold,\n expiration,\n executionDelay,\n approvedAt,\n executableAfter: executableAfterOf(approvedAt, executionDelay),\n failedReturnData: failedReturnData as Hex | undefined,\n decodedRevert: failedReturnData ? decodeRevert(failedReturnData) : undefined,\n source: 'indexer',\n indexedAtBlock,\n };\n }\n\n /** Authoritative read: the struct plus a `hasApproved` probe per current owner. */\n private async fromChain(hash: Bytes32): Promise<VaultTransaction> {\n const vault = this.contract();\n const [raw, owners, threshold, isExpired] = await Promise.all([\n vault.transactions(hash),\n vault.getOwners(),\n vault.threshold(),\n vault.expiredTxs(hash),\n ]);\n\n const to = String(raw.to);\n if (!to || to === '0x0000000000000000000000000000000000000000') {\n throw new NotFoundError(`No transaction ${hash} on vault ${this.address}.`);\n }\n\n const ownerList = owners.map((o) => getAddress(String(o)));\n const approvalFlags = await Promise.all(\n ownerList.map((owner) => vault.hasApproved(hash, owner)),\n );\n const approvals: ApprovalRecord[] = ownerList\n .map((owner, i) => ({ owner, active: approvalFlags[i] === true }))\n .filter((a) => a.active);\n\n const value = BigInt(raw.value ?? 0);\n const data = String(raw.data ?? '0x') as Hex;\n const expiration = Number(raw.expiration ?? 0);\n const executionDelay = Number(raw.executionDelay ?? 0);\n const approvedAt = Number(raw.approvedAt ?? 0);\n const executed = Boolean(raw.executed);\n const cancelled = Boolean(raw.cancelled);\n\n const decodeResult = decodeCall({\n vault: this.address,\n to: getAddress(to),\n value,\n data,\n socialRecovery: this.ctx.contracts.socialRecovery,\n multiSendCallOnly: this.ctx.contracts.multiSendCallOnly,\n });\n\n return {\n hash,\n vault: this.address,\n to: getAddress(to),\n value,\n data,\n proposer: getAddress(String(raw.proposer)),\n proposedAt: Number(raw.timestamp ?? 0),\n kind: decodeResult.kind,\n decoded: decodeResult.decoded,\n summary: decodeResult.summary,\n status: deriveStatus({\n executed,\n cancelled,\n isExpired,\n expiration,\n executionDelay,\n approvedAt,\n approvalCount: approvals.length,\n threshold: Number(threshold),\n }),\n approvals,\n approvalCount: approvals.length,\n threshold: Number(threshold),\n expiration,\n executionDelay,\n approvedAt,\n executableAfter: executableAfterOf(approvedAt, executionDelay),\n source: 'chain',\n };\n }\n\n // =========================================================================\n // Affordances\n // =========================================================================\n\n /**\n * What `caller` may legally do to `txHash` right now, and when blocked actions\n * become available. Defaults to the connected signer's address.\n */\n async affordances(txHash: Bytes32, caller?: Address): Promise<Affordance[]> {\n const hash = normalizeTxHash(txHash);\n return this.resolveAffordances(hash, this.transaction(hash), caller);\n }\n\n /**\n * Shared body of {@link affordances}, taking the transaction either as a value or as\n * an in-flight promise.\n *\n * The promise form is the point: a caller that already holds the record (like\n * {@link describe}) passes it and skips a redundant fetch, while `affordances()`\n * passes the unawaited promise so the transaction read still overlaps the two\n * ownership probes rather than serialising behind them.\n */\n private async resolveAffordances(\n hash: Bytes32,\n transaction: VaultTransaction | Promise<VaultTransaction>,\n caller?: Address,\n ): Promise<Affordance[]> {\n const who = caller ?? (await this.ctx.connection.addressOrNull());\n if (!who) {\n throw new ValidationError(\n 'affordances() needs a caller address when the client has no signer.',\n );\n }\n\n const vault = this.contract();\n const [tx, isOwner, hasApproved] = await Promise.all([\n transaction,\n vault.isOwner(getAddress(who)),\n vault.hasApproved(hash, getAddress(who)),\n ]);\n\n return computeAffordances({ tx, caller: getAddress(who), isOwner, hasApproved });\n }\n\n // =========================================================================\n // Proposals\n // =========================================================================\n\n /**\n * Proposal builders.\n *\n * Every method here is async, including the ones whose work is purely local. Mixing\n * synchronous throws with rejected promises is a footgun: `propose.addOwner(bad)`\n * would throw before `.catch()` could attach. Validation failures are always\n * rejections.\n */\n readonly propose = {\n /** Propose an arbitrary call. Every other `propose.*` helper routes through this. */\n call: async (\n params: { to: Address; value?: bigint; data?: Hex } & ProposeOptions,\n ): Promise<ProposeResult | DryRunResult> =>\n this.proposeCall({\n to: assertQuaiAddress(params.to, 'target'),\n value: params.value,\n data: params.data,\n ...proposeOptionsOf(params),\n }),\n\n /** Send native QUAI. */\n transfer: async (\n params: { to: Address; amount: bigint } & ProposeOptions,\n ): Promise<ProposeResult | DryRunResult> =>\n this.proposeCall({\n // Native value sent to a Qi address leaves the Quai ledger and is unrecoverable.\n to: assertQuaiAddress(params.to, 'recipient'),\n value: params.amount,\n data: '0x',\n ...proposeOptionsOf(params),\n }),\n\n erc20Transfer: async (\n params: { token: Address; to: Address; amount: bigint } & ProposeOptions,\n ): Promise<ProposeResult | DryRunResult> =>\n this.proposeCall({\n to: assertQuaiAddress(params.token, 'token'),\n value: 0n,\n data: tokenEncode.erc20Transfer(assertQuaiAddress(params.to, 'recipient'), params.amount),\n ...proposeOptionsOf(params),\n }),\n\n erc721Transfer: async (\n params: { token: Address; to: Address; tokenId: bigint } & ProposeOptions,\n ): Promise<ProposeResult | DryRunResult> =>\n this.proposeCall({\n to: assertQuaiAddress(params.token, 'token'),\n value: 0n,\n data: tokenEncode.erc721Transfer(\n this.address,\n assertQuaiAddress(params.to, 'recipient'),\n params.tokenId,\n ),\n ...proposeOptionsOf(params),\n }),\n\n erc1155Transfer: async (\n params: {\n token: Address;\n to: Address;\n id: bigint;\n amount: bigint;\n data?: Hex;\n } & ProposeOptions,\n ): Promise<ProposeResult | DryRunResult> =>\n this.proposeCall({\n to: assertQuaiAddress(params.token, 'token'),\n value: 0n,\n data: tokenEncode.erc1155Transfer(\n this.address,\n assertQuaiAddress(params.to, 'recipient'),\n params.id,\n params.amount,\n params.data ?? '0x',\n ),\n ...proposeOptionsOf(params),\n }),\n\n /**\n * Batch several calls through MultiSendCallOnly.\n *\n * Requires MultiSendCallOnly to be on this vault's DelegateCall whitelist, which\n * is empty by default. The precondition is checked before signing so the failure\n * names the missing `addDelegatecallTarget` proposal instead of reverting.\n */\n batch: async (\n calls: BatchCall[],\n options: ProposeOptions = {},\n ): Promise<ProposeResult | DryRunResult> => {\n const multiSend = this.ctx.contracts.multiSendCallOnly;\n if (!multiSend) {\n throw new ValidationError(\n 'No MultiSendCallOnly address is configured for this network.',\n 'Set QUAIVAULT_MULTISEND_CALL_ONLY or pass contracts.multiSendCallOnly.',\n );\n }\n if (!(await this.isDelegatecallAllowed(multiSend))) {\n throw new PreconditionError(\n `MultiSendCallOnly (${multiSend}) is not on this vault's DelegateCall whitelist, so a ` +\n 'batched call cannot execute.',\n {\n remediation:\n `Propose and execute addDelegatecallTarget(${multiSend}) first — it requires full ` +\n 'owner consensus, by design.',\n },\n );\n }\n calls.forEach((call, i) => assertQuaiAddress(call.to, `calls[${i}].to`));\n return this.proposeCall({\n to: multiSend,\n value: 0n,\n data: encodeMultiSend(calls),\n ...proposeOptionsOf(options),\n });\n },\n\n // --- self-calls -------------------------------------------------------\n\n addOwner: async (owner: Address, options: ProposeOptions = {}) =>\n this.proposeSelfCall(selfCall.addOwner(assertQuaiAddress(owner, 'owner')), options),\n\n removeOwner: async (owner: Address, options: ProposeOptions = {}) => {\n // Chain reads, not `owners()`: this gates a signature. See `chainOwners`.\n const [owners, threshold] = await Promise.all([this.chainOwners(), this.chainThreshold()]);\n if (!owners.some((o) => o.toLowerCase() === owner.toLowerCase())) {\n throw new PreconditionError(`${owner} is not an owner of this vault.`);\n }\n if (owners.length - 1 < threshold) {\n throw new PreconditionError(\n `Removing an owner would leave ${owners.length - 1} owners, below the threshold of ${threshold}.`,\n { remediation: 'Lower the threshold first, in a separate proposal.' },\n );\n }\n return this.proposeSelfCall(selfCall.removeOwner(getAddress(owner)), options);\n },\n\n changeThreshold: async (threshold: number, options: ProposeOptions = {}) => {\n // Chain read, not `owners()`: this gates a signature. See `chainOwners`.\n const owners = await this.chainOwners();\n if (threshold < 1 || threshold > owners.length) {\n throw new ValidationError(\n `Invalid threshold ${threshold}: this vault has ${owners.length} owners.`,\n );\n }\n return this.proposeSelfCall(selfCall.changeThreshold(threshold), options);\n },\n\n setMinExecutionDelay: async (seconds: number, options: ProposeOptions = {}) =>\n this.proposeSelfCall(selfCall.setMinExecutionDelay(seconds), options),\n\n enableModule: async (module: Address, options: ProposeOptions = {}) =>\n this.proposeSelfCall(selfCall.enableModule(assertQuaiAddress(module, 'module')), options),\n\n /**\n * Disable a module, resolving its predecessor in the Zodiac linked list.\n *\n * The predecessor is baked into the proposal, so any module added or removed\n * before this executes invalidates it. `execute` re-checks and raises\n * `StaleProposalError` rather than letting it revert on chain.\n */\n disableModule: async (module: Address, options: ProposeOptions = {}) => {\n const prev = await this.previousModule(getAddress(module));\n return this.proposeSelfCall(selfCall.disableModule(prev, getAddress(module)), options);\n },\n\n addDelegatecallTarget: async (target: Address, options: ProposeOptions = {}) =>\n this.proposeSelfCall(\n selfCall.addDelegatecallTarget(assertQuaiAddress(target, 'delegatecall target')),\n options,\n ),\n\n removeDelegatecallTarget: async (target: Address, options: ProposeOptions = {}) =>\n this.proposeSelfCall(selfCall.removeDelegatecallTarget(getAddress(target)), options),\n\n /** Cancel a transaction that has already reached quorum. Needs full consensus. */\n cancelByConsensus: async (txHash: Bytes32, options: ProposeOptions = {}) =>\n this.proposeSelfCall(selfCall.cancelByConsensus(normalizeTxHash(txHash)), options),\n\n /** Sign arbitrary bytes. For EIP-1271 hash approval use `approveHashForEip1271`. */\n signMessage: async (message: Hex, options: ProposeOptions = {}) =>\n this.proposeSelfCall(selfCall.signMessage(message), options),\n\n unsignMessage: async (message: Hex, options: ProposeOptions = {}) =>\n this.proposeSelfCall(selfCall.unsignMessage(message), options),\n\n /**\n * Make `isValidSignature(hash, …)` return the EIP-1271 magic value.\n *\n * Enforces the 32-byte precondition: signing an arbitrary-length message `M`\n * does not make `isValidSignature(keccak256(M))` validate, because EIP-1271\n * hashes the dataHash itself, not `M`.\n */\n approveHashForEip1271: async (hash: Bytes32, options: ProposeOptions = {}) =>\n this.proposeSelfCall(selfCall.approveHashForEip1271(normalizeTxHash(hash, 'hash')), options),\n\n revokeHashForEip1271: async (hash: Bytes32, options: ProposeOptions = {}) =>\n this.proposeSelfCall(selfCall.revokeHashForEip1271(normalizeTxHash(hash, 'hash')), options),\n\n /** Configure social recovery. A call to the module, not a self-call. */\n setupRecovery: async (\n params: { guardians: Address[]; threshold: number; recoveryPeriodSeconds: number } & ProposeOptions,\n ) => {\n const module = this.ctx.contracts.socialRecovery;\n if (!module) {\n throw new ValidationError(\n 'No SocialRecoveryModule address is configured for this network.',\n 'Set QUAIVAULT_SOCIAL_RECOVERY_MODULE or pass contracts.socialRecovery.',\n );\n }\n return this.proposeCall({\n to: module,\n value: 0n,\n data: recoveryCall.setupRecovery(\n this.address,\n // A Qi guardian could never approve a recovery.\n assertQuaiAddresses(params.guardians, 'guardians'),\n params.threshold,\n params.recoveryPeriodSeconds,\n ),\n ...proposeOptionsOf(params),\n });\n },\n };\n\n /** Predecessor of `module` in the Zodiac linked list, for `disableModule`. */\n async previousModule(module: Address): Promise<Address> {\n const modules = await this.modules();\n const index = modules.findIndex((m) => m.toLowerCase() === module.toLowerCase());\n if (index === -1) {\n throw new PreconditionError(`Module ${module} is not enabled on this vault.`);\n }\n // Safe: `index === -1` already threw, and the ternary excludes 0, so index >= 1.\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n return index === 0 ? SENTINEL_MODULES : modules[index - 1]!;\n }\n\n private proposeSelfCall(data: Hex, options: ProposeOptions) {\n // Self-calls always execute immediately: the contract forces executionDelay to 0\n // and rejects any value. Passing a delay would be silently ignored, so reject it.\n if (options.executionDelay) {\n throw new ValidationError(\n 'Self-calls always execute immediately — the vault forces executionDelay to 0 for them.',\n );\n }\n return this.proposeCall({\n to: this.address,\n value: 0n,\n data,\n ...proposeOptionsOf(options),\n });\n }\n\n private async proposeCall(params: {\n to: Address;\n value?: bigint;\n data?: Hex;\n expiration?: number;\n executionDelay?: number;\n dryRun?: boolean;\n }): Promise<ProposeResult | DryRunResult> {\n const to = getAddress(params.to);\n const value = params.value ?? 0n;\n const data = params.data ?? '0x';\n\n if (data !== '0x' && !/^0x([0-9a-fA-F]{2})*$/.test(data)) {\n throw new ValidationError('Transaction data must be 0x-prefixed hex with an even length.');\n }\n\n const isSelfCall = to.toLowerCase() === this.address.toLowerCase();\n if (isSelfCall && value > 0n) {\n throw new ValidationError(\n 'Self-calls cannot carry value — the vault rejects them at proposal time.',\n );\n }\n\n const expiration = params.expiration ?? 0;\n const executionDelay = params.executionDelay ?? 0;\n\n if (executionDelay > MAX_EXECUTION_DELAY) {\n throw new ValidationError(\n `executionDelay ${executionDelay}s exceeds the 30-day maximum (${MAX_EXECUTION_DELAY}s).`,\n );\n }\n\n // Reproduce the contract's ExpirationTooSoon check before signing.\n if (expiration > 0) {\n const floor = isSelfCall ? 0 : Math.max(executionDelay, await this.minExecutionDelay());\n const earliest = minimumExpiration(floor, 0);\n if (expiration <= earliest) {\n throw new ValidationError(\n `expiration ${expiration} is too soon: with an effective delay of ${floor}s the vault ` +\n `requires an expiration after ${earliest}.`,\n `Use at least ${minimumExpiration(floor)} to leave a margin for block time.`,\n );\n }\n }\n\n // Explicit overload signatures — quais cannot disambiguate the three\n // proposeTransaction overloads from argument counts alone.\n const useFullOverload = params.expiration != null || params.executionDelay != null;\n\n if (params.dryRun) {\n const readVault = this.contract();\n const encoded = useFullOverload\n ? readVault.encode('proposeTransaction(address,uint256,bytes,uint48,uint32)', [\n to,\n value,\n data,\n expiration,\n executionDelay,\n ])\n : readVault.encode('proposeTransaction(address,uint256,bytes)', [to, value, data]);\n\n let gasEstimate: bigint | null = null;\n let wouldRevert;\n const from = await this.ctx.connection.addressOrNull();\n // Quai requires `from` on a transaction request (it selects the shard), and it\n // matters semantically too: the vault's onlyOwner check makes estimation revert\n // for a non-owner, which is exactly the signal a dry run should surface. Without\n // a signer there is nothing to estimate against, so the estimate stays null.\n if (from) {\n try {\n gasEstimate = BigInt(\n await this.ctx.connection.provider.estimateGas({\n to: this.address,\n data: encoded,\n from,\n }),\n );\n } catch (err) {\n wouldRevert = decodeRevertFromError(err);\n }\n }\n const decoded = decodeCall({\n vault: this.address,\n to,\n value,\n data,\n socialRecovery: this.ctx.contracts.socialRecovery,\n multiSendCallOnly: this.ctx.contracts.multiSendCallOnly,\n });\n return {\n dryRun: true,\n to: this.address,\n data: encoded,\n value: 0n,\n gasEstimate,\n wouldRevert,\n description: `Propose: ${decoded.summary}`,\n };\n }\n\n await this.assertCallerIsOwner('Proposing a transaction');\n\n const writeVault = this.contract(true);\n let receipt: ReceiptLike;\n try {\n const sent = useFullOverload\n ? await writeVault.proposeTransactionFull(to, value, data, expiration, executionDelay)\n : await writeVault.proposeTransactionSimple(to, value, data);\n receipt = (await sent.wait()) as ReceiptLike;\n } catch (err) {\n throw toRevertError(err, 'Transaction proposal failed');\n }\n\n assertReceipt(receipt, 'Proposal', 'The proposal transaction reverted.');\n\n const txHash = extractProposedTxHash(receipt, this.address);\n if (!txHash) {\n throw new RevertError(\n 'The proposal was mined but no TransactionProposed event was found. ' +\n 'Check that the vault address is correct.',\n );\n }\n\n return {\n txHash,\n chainTxHash: (receipt.hash ?? receipt.transactionHash ?? '') as Hex,\n to,\n value,\n data,\n };\n }\n\n private async minExecutionDelay(): Promise<number> {\n return Number(await this.contract().minExecutionDelay());\n }\n\n // =========================================================================\n // Lifecycle writes\n // =========================================================================\n\n async approve(txHash: Bytes32): Promise<{ chainTxHash: Hex }> {\n const hash = normalizeTxHash(txHash);\n const caller = await this.assertCallerIsOwner('Approving a transaction');\n\n const vault = this.contract(true);\n if (await vault.hasApproved(hash, caller)) {\n throw new PreconditionError('You have already approved this transaction.');\n }\n\n try {\n const sent = await vault.approveTransaction(hash);\n const receipt = (await sent.wait()) as ReceiptLike;\n assertReceipt(receipt, 'Approval', 'The approval transaction reverted.');\n return { chainTxHash: (receipt.hash ?? receipt.transactionHash ?? '') as Hex };\n } catch (err) {\n throw toRevertError(err, 'Approval failed');\n }\n }\n\n async revokeApproval(txHash: Bytes32): Promise<{ chainTxHash: Hex }> {\n const hash = normalizeTxHash(txHash);\n const caller = await this.assertCallerIsOwner('Revoking an approval');\n\n const vault = this.contract(true);\n if (!(await vault.hasApproved(hash, caller))) {\n throw new PreconditionError('You have no active approval on this transaction to revoke.');\n }\n\n try {\n const sent = await vault.revokeApproval(hash);\n const receipt = (await sent.wait()) as ReceiptLike;\n assertReceipt(receipt, 'Revocation', 'The revocation transaction reverted.');\n return { chainTxHash: (receipt.hash ?? receipt.transactionHash ?? '') as Hex };\n } catch (err) {\n throw toRevertError(err, 'Revoking the approval failed');\n }\n }\n\n /**\n * Execute a transaction that has reached quorum.\n *\n * The returned {@link ExecuteResult} says what actually happened. A successful\n * receipt does not imply execution — see {@link classifyExecution}.\n */\n async execute(txHash: Bytes32): Promise<ExecuteResult> {\n const hash = normalizeTxHash(txHash);\n await this.assertCallerIsOwner('Executing a transaction');\n await this.assertExecutable(hash);\n\n const vault = this.contract(true);\n try {\n const sent = await vault.executeTransaction(hash);\n const receipt = (await sent.wait()) as ReceiptLike;\n assertReceipt(receipt, 'Execution', 'The execution transaction reverted.');\n return classifyExecution(receipt, this.address, hash);\n } catch (err) {\n throw toRevertError(err, 'Execution failed');\n }\n }\n\n /** Approve and, if that meets quorum and the timelock allows, execute in one call. */\n async approveAndExecute(txHash: Bytes32): Promise<ExecuteResult> {\n const hash = normalizeTxHash(txHash);\n const caller = await this.assertCallerIsOwner('Approving and executing');\n\n const vault = this.contract(true);\n if (await vault.hasApproved(hash, caller)) {\n throw new PreconditionError('You have already approved this transaction.', {\n remediation: 'Use execute() instead.',\n });\n }\n\n try {\n const sent = await vault.approveAndExecute(hash);\n const receipt = (await sent.wait()) as ReceiptLike;\n assertReceipt(receipt, 'Approve-and-execute', 'The transaction reverted.');\n return classifyExecution(receipt, this.address, hash);\n } catch (err) {\n throw toRevertError(err, 'Approve-and-execute failed');\n }\n }\n\n /** Cancel a transaction you proposed, before it ever reaches quorum. */\n async cancel(txHash: Bytes32): Promise<{ chainTxHash: Hex }> {\n const hash = normalizeTxHash(txHash);\n const caller = await this.assertCallerIsOwner('Cancelling a transaction');\n const tx = await this.fromChain(hash);\n\n if (tx.proposer.toLowerCase() !== caller.toLowerCase()) {\n throw new PreconditionError('Only the proposer can cancel a transaction directly.', {\n remediation: 'Propose a cancelByConsensus self-call instead.',\n });\n }\n if (tx.approvedAt !== 0) {\n throw new PreconditionError(\n 'This transaction reached quorum, which permanently blocks proposer-cancel.',\n { remediation: 'Use propose.cancelByConsensus() instead.' },\n );\n }\n\n try {\n const sent = await this.contract(true).cancelTransaction(hash);\n const receipt = (await sent.wait()) as ReceiptLike;\n assertReceipt(receipt, 'Cancellation', 'The cancellation reverted.');\n return { chainTxHash: (receipt.hash ?? receipt.transactionHash ?? '') as Hex };\n } catch (err) {\n throw toRevertError(err, 'Cancellation failed');\n }\n }\n\n /** Close out an expired transaction. Permissionless — no ownership required. */\n async expire(txHash: Bytes32): Promise<{ chainTxHash: Hex }> {\n const hash = normalizeTxHash(txHash);\n try {\n const sent = await this.contract(true).expireTransaction(hash);\n const receipt = (await sent.wait()) as ReceiptLike;\n assertReceipt(receipt, 'Expiry', 'The expiry transaction reverted.');\n return { chainTxHash: (receipt.hash ?? receipt.transactionHash ?? '') as Hex };\n } catch (err) {\n throw toRevertError(err, 'Expiring the transaction failed');\n }\n }\n\n // =========================================================================\n // Preconditions\n // =========================================================================\n\n private async assertCallerIsOwner(operation: string): Promise<Address> {\n const caller = await this.ctx.connection.address();\n const isOwner = await this.contract().isOwner(caller);\n if (!isOwner) {\n throw new PreconditionError(`${operation} requires an owner. ${caller} is not one.`);\n }\n return getAddress(caller);\n }\n\n /**\n * Re-validate on chain immediately before signing an execute.\n *\n * Reads always go through the chain here, never the indexer: indexed approval\n * counts can over-report after an owner removal, and a stale count must never gate\n * a signature.\n */\n private async assertExecutable(hash: Bytes32): Promise<void> {\n const tx = await this.fromChain(hash);\n\n if (tx.status === 'executed' || tx.status === 'failed') {\n throw new PreconditionError('This transaction has already been executed.');\n }\n if (tx.status === 'cancelled') {\n throw new PreconditionError('This transaction has been cancelled.');\n }\n if (tx.status === 'expired') {\n throw new PreconditionError('This transaction has expired and can no longer execute.', {\n remediation: 'Call expire() to close it out, then propose a replacement.',\n });\n }\n if (tx.approvalCount < tx.threshold) {\n throw new PreconditionError(\n `Not enough approvals: ${tx.approvalCount} of ${tx.threshold}.`,\n );\n }\n\n // A stale prevModule can never execute — surface it now rather than on chain.\n if (tx.decoded?.name === 'disableModule' && tx.decoded.target === 'vault') {\n const module = String(tx.decoded.args.module ?? '');\n const bakedPrev = String(tx.decoded.args.prevModule ?? '');\n const modules = await this.modules();\n const index = modules.findIndex((m) => m.toLowerCase() === module.toLowerCase());\n if (index === -1) {\n throw new StaleProposalError(\n `This proposal disables module ${module}, which is no longer enabled.`,\n );\n }\n // Safe: `index === -1` already threw, and the ternary excludes 0, so index >= 1.\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const expectedPrev = index === 0 ? SENTINEL_MODULES : modules[index - 1]!;\n if (expectedPrev.toLowerCase() !== bakedPrev.toLowerCase()) {\n throw new StaleProposalError(\n `The module list changed since this proposal was created: it names ${bakedPrev} as the ` +\n `predecessor of ${module}, but the current predecessor is ${expectedPrev}.`,\n );\n }\n }\n }\n\n // =========================================================================\n // Holdings and activity\n // =========================================================================\n\n /**\n * Native and token holdings.\n *\n * Token discovery needs the indexer — the chain cannot answer \"which contracts has\n * this address touched\" without scanning every log. Amounts are verified on chain\n * by default; pass `{ verify: false }` to accept replayed transfer totals instead.\n */\n async balances(options: BalanceOptions = {}): Promise<VaultBalances> {\n return loadBalances(this.ctx.connection, this.ctx.queries, this.address, options);\n }\n\n /** Native QUAI received by the vault. Indexer-only. */\n async deposits(options: Pagination = {}) {\n return this.requireQueries('Listing deposits').deposits(this.address, options);\n }\n\n /** ERC20/721/1155 transfers involving this vault. Indexer-only. */\n async tokenTransfers(options: Pagination = {}) {\n return this.requireQueries('Listing token transfers').tokenTransfers(this.address, options);\n }\n\n /** Message hashes currently signed by the vault for EIP-1271. Indexer-only. */\n async signedMessages() {\n return this.requireQueries('Listing signed messages').signedMessages(this.address);\n }\n\n /**\n * Follow indexer changes for this vault over Supabase Realtime.\n *\n * Events fire after the indexer processes a block, so treat them as a signal to\n * re-read rather than as state themselves — re-read through this handle so approval\n * counts stay intersected with the current owner set.\n *\n * ```ts\n * const sub = vault.watch((e) => console.log(e.topic, e.type));\n * // …later\n * await sub.unsubscribe();\n * ```\n */\n watch(handler: (event: WatchEvent) => void, options: WatchOptions = {}): Subscription {\n if (!this.ctx.indexer) throw new NoIndexerError('Watching a vault');\n return watchVault(this.ctx.indexer, this.address, handler, options);\n }\n\n // =========================================================================\n // Waiting\n // =========================================================================\n\n /**\n * Block until the indexer has caught up to `blockNumber` (or to the chain head\n * when omitted), so a subsequent indexed read reflects a write you just made.\n *\n * Returns `reached: false` on timeout rather than throwing — a lagging indexer is\n * an expected operating condition, and the caller may reasonably fall back to a\n * chain read. Requires an indexer; without one there is nothing to wait for.\n */\n async waitForIndexer(\n blockNumber?: number,\n options: { timeoutMs?: number; pollIntervalMs?: number; signal?: AbortSignal } = {},\n ): Promise<{ reached: boolean; lastIndexedBlock: number }> {\n if (!this.ctx.indexer) throw new NoIndexerError('Waiting for the indexer');\n\n let target = blockNumber;\n if (target === undefined) {\n // Quai is sharded, so there is no single chain head — the head that matters is\n // the one for this vault's own zone, derived from its address prefix.\n const zone = getZoneForAddress(this.address);\n if (!zone) {\n throw new ValidationError(\n `Cannot determine the Quai zone for vault ${this.address}; pass an explicit block number.`,\n );\n }\n // Zone and Shard share their wire values but are nominally distinct types.\n target = Number(await this.ctx.connection.provider.getBlockNumber(toShard(zone)));\n }\n return this.ctx.indexer.waitForBlock(target, options);\n }\n\n /**\n * Poll until a transaction is executable, then resolve with its current state.\n *\n * Lets a caller express \"run this when it can run\" instead of reimplementing the\n * timelock arithmetic. Resolves as soon as the status reaches `ready`; rejects if\n * the transaction reaches a terminal state first, or if the deadline passes.\n *\n * Reads go through the chain so the answer is authoritative — a `ready` verdict\n * here is immediately actionable.\n */\n async waitForExecutable(\n txHash: Bytes32,\n options: {\n /** Give up after this long. Default 1 hour. */\n timeoutMs?: number;\n /** Poll interval. Default 15s, roughly three Quai blocks. */\n pollIntervalMs?: number;\n signal?: AbortSignal;\n onPoll?: (tx: VaultTransaction) => void;\n } = {},\n ): Promise<VaultTransaction> {\n const hash = normalizeTxHash(txHash);\n const timeoutMs = options.timeoutMs ?? 60 * 60 * 1000;\n const pollIntervalMs = options.pollIntervalMs ?? 15_000;\n const deadline = Date.now() + timeoutMs;\n\n for (;;) {\n if (options.signal?.aborted) throw new AbortError('Waiting for the transaction');\n\n const tx = await this.fromChain(hash);\n options.onPoll?.(tx);\n\n if (tx.status === 'ready') return tx;\n\n if (tx.status === 'executed' || tx.status === 'failed') {\n throw new PreconditionError(`Transaction ${hash} has already been executed.`);\n }\n if (tx.status === 'cancelled' || tx.status === 'expired') {\n throw new PreconditionError(`Transaction ${hash} is ${tx.status} and can never execute.`);\n }\n\n // Below quorum there is no deadline to wait for — only more approvals help.\n if (tx.approvalCount < tx.threshold) {\n throw new PreconditionError(\n `Transaction ${hash} needs ${tx.threshold} approvals and has ${tx.approvalCount}. ` +\n 'Waiting cannot resolve this.',\n { remediation: 'Collect the remaining approvals, then wait for the timelock.' },\n );\n }\n\n // Timelocked with quorum: sleep until the clock lifts, or the next poll tick.\n const untilExecutable =\n tx.executableAfter > 0 ? tx.executableAfter * 1000 - Date.now() : pollIntervalMs;\n const wait = Math.max(1_000, Math.min(untilExecutable, pollIntervalMs));\n\n if (Date.now() + wait > deadline) {\n throw new PreconditionError(\n `Timed out after ${timeoutMs}ms waiting for ${hash} to become executable.`,\n {\n ...(tx.executableAfter > 0 ? { retryableAt: tx.executableAfter } : {}),\n remediation:\n tx.executableAfter > 0\n ? `Executable after ${new Date(tx.executableAfter * 1000).toISOString()}.`\n : 'The timelock clock has not started yet.',\n },\n );\n }\n\n await new Promise((resolve) => setTimeout(resolve, wait));\n }\n }\n\n // =========================================================================\n // Presentation\n // =========================================================================\n\n /** Compact human-readable summary of a transaction's state. */\n async describe(txHash: Bytes32, caller?: Address): Promise<string> {\n const tx = await this.transaction(txHash);\n const lines = [\n `Transaction ${tx.hash}`,\n ` ${tx.summary}`,\n ` status: ${tx.status} (${tx.approvalCount}/${tx.threshold} approvals)`,\n ];\n if (tx.value > 0n) lines.push(` value: ${formatQuai(tx.value)} QUAI`);\n if (tx.approvedAt > 0) {\n lines.push(` quorum reached: ${new Date(tx.approvedAt * 1000).toISOString()}`);\n }\n if (tx.executableAfter > 0) {\n const remaining = tx.executableAfter - nowSeconds();\n lines.push(\n ` executable after: ${new Date(tx.executableAfter * 1000).toISOString()}` +\n (remaining > 0 ? ` (in ${remaining}s)` : ' (now)'),\n );\n }\n if (tx.expiration > 0) {\n lines.push(` expires: ${new Date(tx.expiration * 1000).toISOString()}`);\n }\n if (tx.decodedRevert) lines.push(` revert: ${tx.decodedRevert.message}`);\n lines.push(` source: ${tx.source}`);\n\n if (caller || this.ctx.connection.hasSigner()) {\n // Reuse the record already fetched above rather than reading it a second time.\n const affordances = await this.resolveAffordances(tx.hash, tx, caller);\n const allowed = affordances.filter((a) => a.allowed).map((a) => a.action);\n lines.push(` you can: ${allowed.length > 0 ? allowed.join(', ') : 'nothing right now'}`);\n }\n return lines.join('\\n');\n }\n}\n\n/**\n * Assert a receipt exists and did not revert.\n *\n * `wait()` resolves to null when the transaction was replaced or dropped rather than\n * mined. Without this guard the caller would get a `TypeError` from dereferencing\n * `receipt.hash` instead of an explanation of what happened.\n */\nfunction assertReceipt(\n receipt: ReceiptLike | null | undefined,\n operation: string,\n revertMessage: string,\n): asserts receipt is ReceiptLike {\n if (!receipt) {\n throw new RevertError(\n `${operation} produced no receipt — the transaction was replaced or dropped before it was mined.`,\n undefined,\n { remediation: 'Check the mempool for a replacement, then retry if it never landed.' },\n );\n }\n if (receipt.status === 0) throw new RevertError(revertMessage);\n}\n\n/**\n * Extract only the proposal options from a params bag.\n *\n * Spreading the whole bag would let a caller-facing field named `to` (the token\n * recipient) overwrite the encoded call target (the token contract) — silently\n * sending a proposal to the wrong address.\n */\nfunction proposeOptionsOf(options: ProposeOptions): ProposeOptions {\n return {\n ...(options.expiration != null ? { expiration: options.expiration } : {}),\n ...(options.executionDelay != null ? { executionDelay: options.executionDelay } : {}),\n ...(options.dryRun != null ? { dryRun: options.dryRun } : {}),\n };\n}\n\n/** Wrap a provider/contract error with decoded revert data when available. */\nfunction toRevertError(err: unknown, context: string): Error {\n if (err instanceof RevertError || err instanceof PreconditionError) return err;\n const decoded = decodeRevertFromError(err);\n const detail = decoded ? `: ${decoded.message}` : '';\n const base = err instanceof Error ? err.message : String(err);\n return new RevertError(`${context}${detail || `: ${base}`}`, decoded, { cause: err });\n}\n\nexport type { DecodedBatchCall };\n","import { getAddress } from 'quais';\nimport { assertQuaiAddress } from './address.js';\nimport type { Connection } from './chain/connection.js';\nimport { normalizeTxHash } from './chain/connection.js';\nimport { RecoveryContract, type RawRecovery } from './chain/recovery-contract.js';\nimport { VaultContract } from './chain/vault-contract.js';\nimport { MAX_OWNERS, SENTINEL_MODULES, ZERO_ADDRESS } from './encode/index.js';\nimport type { IndexerQueries } from './indexer/queries.js';\nimport { decodeRevertFromError } from './errors/decode.js';\nimport {\n NoIndexerError,\n NotFoundError,\n PreconditionError,\n RevertError,\n ValidationError,\n} from './errors/index.js';\nimport { deriveRecoveryStatus, nowSeconds } from './lifecycle/status.js';\nimport type { ReceiptLike } from './lifecycle/outcome.js';\nimport type {\n Address,\n Bytes32,\n Hex,\n RecoveryAffordance,\n RecoveryConfig,\n RecoveryRequest,\n} from './types.js';\n\nexport interface RecoveryModuleContext {\n connection: Connection;\n queries: IndexerQueries | null;\n vaultAddress: Address;\n moduleAddress: Address | undefined;\n}\n\n/**\n * Guardian-based recovery for one vault.\n *\n * Recovery is an escape hatch that bypasses the owner multisig entirely: enough\n * guardians can replace the owner set after a delay. Every write here is therefore\n * gated on the module still being enabled on the vault, which is the vault owners'\n * only lever once guardians are configured.\n */\nexport class RecoveryModule {\n constructor(private readonly ctx: RecoveryModuleContext) {}\n\n /** The module address, or a typed error naming the variable to set. */\n get address(): Address {\n if (!this.ctx.moduleAddress) {\n throw new ValidationError(\n 'No SocialRecoveryModule address is configured for this network.',\n 'Set QUAIVAULT_SOCIAL_RECOVERY_MODULE or pass contracts.socialRecovery.',\n );\n }\n return this.ctx.moduleAddress;\n }\n\n private contract(write = false): RecoveryContract {\n return new RecoveryContract(this.ctx.connection.socialRecovery(this.address, write), this.ctx.connection.retry);\n }\n\n private get vault(): Address {\n return this.ctx.vaultAddress;\n }\n\n /**\n * The vault this module acts on, through the same retrying facade every other vault\n * read in the SDK uses. Recovery reaches into the vault for three checks — is the\n * module enabled, is the caller an owner, who are the current owners — and each of\n * them gates a write, so none of them should be the one read that silently skips\n * transient-failure handling.\n */\n private vaultContract(): VaultContract {\n return new VaultContract(this.ctx.connection.vault(this.vault), this.ctx.connection.retry);\n }\n\n // =========================================================================\n // Reads\n // =========================================================================\n\n /** Whether the module is currently enabled on the vault. */\n async isEnabled(): Promise<boolean> {\n if (!this.ctx.moduleAddress) return false;\n return this.vaultContract().isModuleEnabled(this.address);\n }\n\n async config(): Promise<RecoveryConfig> {\n const raw = await this.contract().getRecoveryConfig(this.vault);\n const guardians = Array.from(raw.guardians ?? []).map((g) => getAddress(String(g)));\n return {\n guardians,\n threshold: Number(raw.threshold ?? 0),\n recoveryPeriod: Number(raw.recoveryPeriod ?? 0),\n configured: guardians.length > 0,\n };\n }\n\n async isGuardian(address: Address): Promise<boolean> {\n return this.contract().isGuardian(this.vault, getAddress(address));\n }\n\n /** Hashes of recoveries the module still tracks as pending. */\n async pendingHashes(): Promise<Bytes32[]> {\n return (await this.contract().getPendingRecoveryHashes(this.vault)).map((h) => String(h));\n }\n\n async hasPending(): Promise<boolean> {\n return this.contract().hasPendingRecoveries(this.vault);\n }\n\n /**\n * One recovery request, read from chain.\n *\n * Throws `NotFoundError` for a hash that was never initiated *or* was cancelled —\n * `cancelRecovery` deletes the struct, so the two are indistinguishable on chain.\n * Use {@link history} for cancelled recoveries.\n */\n async get(recoveryHash: Bytes32): Promise<RecoveryRequest> {\n const hash = normalizeTxHash(recoveryHash, 'recovery hash');\n const raw = await this.contract().getRecovery(this.vault, hash);\n\n if (Number(raw.executionTime ?? 0) === 0) {\n throw new NotFoundError(\n `No active recovery ${hash} on vault ${this.vault}. It was never initiated, or it was ` +\n 'cancelled (cancellation deletes the on-chain record).',\n );\n }\n return this.buildFromChain(hash, raw);\n }\n\n /** Every recovery the module still tracks as pending, hydrated. */\n async pending(): Promise<RecoveryRequest[]> {\n const hashes = await this.pendingHashes();\n const contract = this.contract();\n const results = await Promise.all(\n hashes.map(async (hash) => {\n const raw = await contract.getRecovery(this.vault, hash);\n if (Number(raw.executionTime ?? 0) === 0) return null;\n return this.buildFromChain(hash, raw);\n }),\n );\n return results.filter((r): r is RecoveryRequest => r !== null);\n }\n\n /**\n * Full recovery history including executed, cancelled and expired requests.\n * Indexer-only — the chain retains no record of cancelled recoveries.\n */\n async history(options: { limit?: number; offset?: number } = {}): Promise<RecoveryRequest[]> {\n // Throws rather than returning `[]`, matching every other indexer-only read on the\n // SDK. An empty array here is indistinguishable from \"this vault has no recovery\n // history\", which is exactly the wrong thing to tell someone whose vault is being\n // recovered out from under them.\n const queries = this.ctx.queries;\n if (!queries) throw new NoIndexerError('Listing recovery history');\n\n const rows = await queries.recoveryHistory(this.vault, options);\n return rows.map((row) => ({\n hash: row.recovery_hash,\n vault: this.vault,\n newOwners: row.new_owners.map((o) => getAddress(o)),\n newThreshold: row.new_threshold,\n approvalCount: row.approval_count ?? 0,\n requiredThreshold: row.required_threshold,\n executionTime: Number(row.execution_time),\n expiration: Number(row.expiration ?? 0),\n // Trust the indexer only for states it alone can observe (cancelled /\n // invalidated); derive everything else, since an un-cleaned recovery stays\n // 'pending' in the database long after its deadline.\n status:\n row.status === 'cancelled' || row.status === 'invalidated'\n ? 'cancelled'\n : deriveRecoveryStatus({\n executed: row.status === 'executed',\n approvalCount: row.approval_count ?? 0,\n requiredThreshold: row.required_threshold,\n executionTime: Number(row.execution_time),\n expiration: Number(row.expiration ?? 0),\n }),\n executed: row.status === 'executed',\n initiator: getAddress(row.initiator_address),\n source: 'indexer' as const,\n }));\n }\n\n /** Guardians who have an active approval on a recovery. */\n async approvals(recoveryHash: Bytes32): Promise<Address[]> {\n const hash = normalizeTxHash(recoveryHash, 'recovery hash');\n\n // The chain has no enumeration, so probe each configured guardian.\n const { guardians } = await this.config();\n const contract = this.contract();\n const flags = await Promise.all(\n guardians.map((g) => contract.recoveryApprovals(this.vault, hash, g)),\n );\n return guardians.filter((_, i) => flags[i] === true);\n }\n\n /** Hash the next `initiate` with these parameters would produce. */\n async predictHash(newOwners: Address[], newThreshold: number): Promise<Bytes32> {\n return this.contract().predictNextRecoveryHash(\n this.vault,\n newOwners.map((o) => getAddress(o)),\n newThreshold,\n );\n }\n\n // =========================================================================\n // Writes\n // =========================================================================\n\n /**\n * Initiate a recovery. Guardians only.\n *\n * Returns the recovery hash, read from the `RecoveryInitiated` event — the function's\n * return value is not recoverable from a receipt.\n */\n async initiate(params: {\n newOwners: Address[];\n newThreshold: number;\n }): Promise<{ recoveryHash: Bytes32; chainTxHash: Hex }> {\n // A Qi or zone-less owner could never sign, so a recovery installing one would\n // hand the vault to a set that cannot act.\n const newOwners = params.newOwners.map((o, i) => assertQuaiAddress(o, `newOwners[${i}]`));\n this.validateNewOwners(newOwners, params.newThreshold);\n\n const caller = await this.ctx.connection.address();\n await this.assertEnabled('Initiating a recovery');\n\n const config = await this.config();\n if (!config.configured) {\n throw new PreconditionError('This vault has no social recovery configuration.', {\n remediation:\n 'Owners must first propose and execute setupRecovery via vault.propose.setupRecovery().',\n });\n }\n if (!(await this.isGuardian(caller))) {\n throw new PreconditionError(`${caller} is not a guardian of this vault.`);\n }\n\n const contract = this.contract(true);\n try {\n const sent = await contract.initiateRecovery(this.vault, newOwners, params.newThreshold);\n const receipt = (await sent.wait()) as ReceiptLike;\n if (!receipt || receipt.status === 0) {\n throw new RevertError('The recovery initiation reverted.');\n }\n const recoveryHash = this.extractRecoveryHash(receipt);\n if (!recoveryHash) {\n throw new RevertError(\n 'The recovery was initiated but no RecoveryInitiated event was found.',\n );\n }\n return { recoveryHash, chainTxHash: (receipt.hash ?? receipt.transactionHash ?? '') as Hex };\n } catch (err) {\n throw this.toRevert(err, 'Initiating the recovery failed');\n }\n }\n\n /** Approve a recovery. Guardians only. */\n async approve(recoveryHash: Bytes32): Promise<{ chainTxHash: Hex }> {\n const hash = normalizeTxHash(recoveryHash, 'recovery hash');\n const caller = await this.ctx.connection.address();\n await this.assertEnabled('Approving a recovery');\n\n if (!(await this.isGuardian(caller))) {\n throw new PreconditionError(`${caller} is not a guardian of this vault.`);\n }\n const request = await this.get(hash);\n this.assertLive(request);\n if (await this.contract().recoveryApprovals(this.vault, hash, caller)) {\n throw new PreconditionError('You have already approved this recovery.');\n }\n\n return this.send((c) => c.approveRecovery(this.vault, hash), 'Approving the recovery failed');\n }\n\n /** Withdraw a guardian approval before the recovery executes. */\n async revokeApproval(recoveryHash: Bytes32): Promise<{ chainTxHash: Hex }> {\n const hash = normalizeTxHash(recoveryHash, 'recovery hash');\n const caller = await this.ctx.connection.address();\n\n if (!(await this.isGuardian(caller))) {\n throw new PreconditionError(`${caller} is not a guardian of this vault.`);\n }\n if (!(await this.contract().recoveryApprovals(this.vault, hash, caller))) {\n throw new PreconditionError('You have no active approval on this recovery to revoke.');\n }\n\n return this.send(\n (c) => c.revokeRecoveryApproval(this.vault, hash),\n 'Revoking the recovery approval failed',\n );\n }\n\n /**\n * Execute a recovery, replacing the vault's owner set. Permissionless once the\n * guardian threshold is met and the recovery period has elapsed.\n */\n async execute(recoveryHash: Bytes32): Promise<{ chainTxHash: Hex }> {\n const hash = normalizeTxHash(recoveryHash, 'recovery hash');\n await this.assertEnabled('Executing a recovery');\n\n const request = await this.get(hash);\n this.assertLive(request);\n\n if (request.approvalCount < request.requiredThreshold) {\n throw new PreconditionError(\n `Not enough guardian approvals: ${request.approvalCount} of ${request.requiredThreshold}.`,\n );\n }\n const now = nowSeconds();\n if (now < request.executionTime) {\n throw new PreconditionError(\n `The recovery period has not elapsed. Executable after ` +\n `${new Date(request.executionTime * 1000).toISOString()}.`,\n { retryableAt: request.executionTime },\n );\n }\n\n // S-1: new owners are added before old ones are removed, so a fully disjoint\n // replacement can transiently exceed MAX_OWNERS and revert.\n const currentOwners = await this.vaultContract().getOwners();\n const current = new Set(Array.from(currentOwners).map((o) => String(o).toLowerCase()));\n const overlap = request.newOwners.filter((o) => current.has(o.toLowerCase())).length;\n const peak = current.size + request.newOwners.length - overlap;\n if (peak > MAX_OWNERS) {\n throw new PreconditionError(\n `Executing this recovery would transiently hold ${peak} owners, above the ` +\n `${MAX_OWNERS}-owner maximum — new owners are added before old ones are removed.`,\n {\n remediation:\n 'Run a recovery that retains at least one existing owner, then a second recovery to ' +\n 'replace it.',\n },\n );\n }\n\n return this.send((c) => c.executeRecovery(this.vault, hash), 'Executing the recovery failed');\n }\n\n /**\n * Cancel a recovery. Callable by any current vault owner — this is the owners'\n * defence against a hostile or mistaken guardian action.\n */\n async cancel(recoveryHash: Bytes32): Promise<{ chainTxHash: Hex }> {\n const hash = normalizeTxHash(recoveryHash, 'recovery hash');\n const caller = await this.ctx.connection.address();\n\n const isOwner = await this.vaultContract().isOwner(caller);\n if (!isOwner) {\n throw new PreconditionError(\n `Only a current owner of the vault can cancel a recovery. ${caller} is not one.`,\n );\n }\n\n return this.send((c) => c.cancelRecovery(this.vault, hash), 'Cancelling the recovery failed');\n }\n\n /** Clean up a recovery past its deadline. Permissionless. */\n async expire(recoveryHash: Bytes32): Promise<{ chainTxHash: Hex }> {\n const hash = normalizeTxHash(recoveryHash, 'recovery hash');\n return this.send((c) => c.expireRecovery(this.vault, hash), 'Expiring the recovery failed');\n }\n\n // =========================================================================\n // Affordances\n // =========================================================================\n\n /** What `caller` may do to a recovery right now, and when blocked actions unlock. */\n async affordances(recoveryHash: Bytes32, caller?: Address): Promise<RecoveryAffordance[]> {\n const hash = normalizeTxHash(recoveryHash, 'recovery hash');\n const who = caller ?? (await this.ctx.connection.addressOrNull());\n if (!who) {\n throw new ValidationError(\n 'affordances() needs a caller address when the client has no signer.',\n );\n }\n const address = getAddress(who);\n\n const [request, isGuardian, hasApproved, enabled, isOwner] = await Promise.all([\n this.get(hash),\n this.isGuardian(address),\n this.contract().recoveryApprovals(this.vault, hash, address),\n this.isEnabled(),\n this.vaultContract().isOwner(address),\n ]);\n\n const now = nowSeconds();\n const terminal = request.status === 'executed' || request.status === 'cancelled';\n const expired = now > request.expiration && request.expiration > 0;\n const quorum = request.approvalCount >= request.requiredThreshold;\n const out: RecoveryAffordance[] = [];\n\n const blocked = (\n action: RecoveryAffordance['action'],\n reason: string,\n blockedBy: RecoveryAffordance['blockedBy'],\n availableAt?: number,\n ): RecoveryAffordance => ({\n action,\n allowed: false,\n reason,\n blockedBy,\n ...(availableAt !== undefined ? { availableAt } : {}),\n });\n\n // --- approve\n if (terminal) out.push(blocked('approve', terminalReason(request), 'terminal_state'));\n else if (expired) out.push(blocked('approve', 'The recovery has expired.', 'expired'));\n else if (!enabled) {\n out.push(blocked('approve', 'The recovery module is not enabled on this vault.', 'module_disabled'));\n } else if (!isGuardian) {\n out.push(blocked('approve', 'Only guardians can approve a recovery.', 'not_guardian'));\n } else if (hasApproved) {\n out.push(blocked('approve', 'You have already approved this recovery.', 'already_approved'));\n } else {\n out.push({ action: 'approve', allowed: true, reason: 'You can approve this recovery.' });\n }\n\n // --- revokeApproval (no module-enabled gate on chain)\n if (terminal) out.push(blocked('revokeApproval', terminalReason(request), 'terminal_state'));\n else if (!isGuardian) {\n out.push(blocked('revokeApproval', 'Only guardians can revoke a recovery approval.', 'not_guardian'));\n } else if (!hasApproved) {\n out.push(blocked('revokeApproval', 'You have no active approval to revoke.', 'not_approved'));\n } else {\n out.push({ action: 'revokeApproval', allowed: true, reason: 'You can revoke your approval.' });\n }\n\n // --- execute (permissionless once the gates clear)\n if (terminal) out.push(blocked('execute', terminalReason(request), 'terminal_state'));\n else if (expired) out.push(blocked('execute', 'The recovery has expired.', 'expired'));\n else if (!enabled) {\n out.push(blocked('execute', 'The recovery module is not enabled on this vault.', 'module_disabled'));\n } else if (!quorum) {\n out.push(\n blocked(\n 'execute',\n `Needs ${request.requiredThreshold} guardian approvals, has ${request.approvalCount}.`,\n 'threshold',\n ),\n );\n } else if (now < request.executionTime) {\n out.push(\n blocked(\n 'execute',\n `Recovery period ends ${new Date(request.executionTime * 1000).toISOString()}.`,\n 'timelock',\n request.executionTime,\n ),\n );\n } else {\n out.push({\n action: 'execute',\n allowed: true,\n reason: 'This recovery is ready to execute and will replace the vault owner set.',\n });\n }\n\n // --- cancel (any current owner)\n if (terminal) out.push(blocked('cancel', terminalReason(request), 'terminal_state'));\n else if (!isOwner) {\n out.push(blocked('cancel', 'Only a current vault owner can cancel a recovery.', 'not_owner'));\n } else {\n out.push({\n action: 'cancel',\n allowed: true,\n reason: 'As a vault owner you can cancel this recovery.',\n });\n }\n\n // --- expire (permissionless, past the deadline)\n if (terminal) out.push(blocked('expire', terminalReason(request), 'terminal_state'));\n else if (!expired) {\n out.push(\n blocked(\n 'expire',\n `Not expired yet. Expires ${new Date(request.expiration * 1000).toISOString()}.`,\n 'not_expired',\n request.expiration + 1,\n ),\n );\n } else {\n out.push({\n action: 'expire',\n allowed: true,\n reason: 'Past its deadline — anyone can clean it up, which also unblocks setupRecovery.',\n });\n }\n\n return out;\n }\n\n // =========================================================================\n // Internals\n // =========================================================================\n\n private buildFromChain(hash: Bytes32, raw: RawRecovery): RecoveryRequest {\n const executionTime = Number(raw.executionTime ?? 0);\n const expiration = Number(raw.expiration ?? 0);\n const approvalCount = Number(raw.approvalCount ?? 0);\n const requiredThreshold = Number(raw.requiredThreshold ?? 0);\n const executed = Boolean(raw.executed);\n\n const status = deriveRecoveryStatus({\n executed,\n approvalCount,\n requiredThreshold,\n executionTime,\n expiration,\n });\n\n return {\n hash,\n vault: this.vault,\n newOwners: Array.from(raw.newOwners ?? []).map((o) => getAddress(String(o))),\n newThreshold: Number(raw.newThreshold ?? 0),\n approvalCount,\n requiredThreshold,\n executionTime,\n expiration,\n status,\n executed,\n source: 'chain',\n };\n }\n\n private validateNewOwners(newOwners: Address[], newThreshold: number): void {\n if (newOwners.length === 0) throw new ValidationError('At least one new owner is required.');\n\n const seen = new Set<string>();\n for (const owner of newOwners) {\n const key = owner.toLowerCase();\n if (key === ZERO_ADDRESS || key === SENTINEL_MODULES) {\n throw new ValidationError(\n `New owner ${owner} is reserved — the zero address and the module sentinel 0x…01 are rejected.`,\n );\n }\n if (key === this.vault.toLowerCase()) {\n throw new ValidationError('The vault cannot be an owner of itself.');\n }\n if (seen.has(key)) throw new ValidationError(`Duplicate new owner: ${owner}.`);\n seen.add(key);\n }\n if (!Number.isInteger(newThreshold) || newThreshold < 1 || newThreshold > newOwners.length) {\n throw new ValidationError(\n `Invalid new threshold ${newThreshold}: must be between 1 and ${newOwners.length}.`,\n );\n }\n }\n\n private assertLive(request: RecoveryRequest): void {\n if (request.executed) {\n throw new PreconditionError('This recovery has already been executed.');\n }\n if (request.expiration > 0 && nowSeconds() > request.expiration) {\n throw new PreconditionError('This recovery has expired.', {\n remediation: 'Call expire() to clean it up, then initiate a new recovery.',\n });\n }\n }\n\n private async assertEnabled(operation: string): Promise<void> {\n if (!(await this.isEnabled())) {\n throw new PreconditionError(\n `${operation} requires the SocialRecoveryModule to be enabled on this vault.`,\n {\n remediation:\n 'Owners must propose and execute enableModule for the recovery module first.',\n },\n );\n }\n }\n\n private async send(\n call: (contract: RecoveryContract) => Promise<{ hash: string; wait(): Promise<unknown> }>,\n context: string,\n ): Promise<{ chainTxHash: Hex }> {\n try {\n const sent = await call(this.contract(true));\n const receipt = (await sent.wait()) as ReceiptLike;\n if (!receipt || receipt.status === 0) throw new RevertError(`${context}: reverted.`);\n return { chainTxHash: (receipt.hash ?? receipt.transactionHash ?? '') as Hex };\n } catch (err) {\n throw this.toRevert(err, context);\n }\n }\n\n private extractRecoveryHash(receipt: ReceiptLike): Bytes32 | null {\n const iface = this.contract().interface;\n const target = this.address.toLowerCase();\n for (const log of receipt.logs ?? []) {\n if (log.address && log.address.toLowerCase() !== target) continue;\n try {\n const parsed = iface.parseLog({ topics: Array.from(log.topics), data: log.data });\n if (parsed?.name === 'RecoveryInitiated') {\n const index = parsed.fragment.inputs.findIndex((i) => i.name === 'recoveryHash');\n const value = index >= 0 ? parsed.args[index] : undefined;\n if (typeof value === 'string') return value;\n }\n } catch {\n continue;\n }\n }\n return null;\n }\n\n private toRevert(err: unknown, context: string): Error {\n if (err instanceof RevertError || err instanceof PreconditionError) return err;\n const decoded = decodeRevertFromError(err);\n const base = err instanceof Error ? err.message : String(err);\n return new RevertError(`${context}${decoded ? `: ${decoded.message}` : `: ${base}`}`, decoded, {\n cause: err,\n });\n }\n}\n\nfunction terminalReason(request: RecoveryRequest): string {\n if (request.executed) return 'This recovery has already been executed.';\n if (request.status === 'cancelled') return 'This recovery was cancelled.';\n return 'This recovery is in a terminal state.';\n}\n","import type { Contract } from 'quais';\nimport { withRetry, type RetryOptions } from './retry.js';\nimport type { Address, Bytes32 } from '../types.js';\nimport type { ContractTransactionResponse } from './vault-contract.js';\n\n/** Raw `RecoveryConfig` struct from `getRecoveryConfig(address)`. */\nexport interface RawRecoveryConfig {\n guardians: string[];\n threshold: bigint;\n recoveryPeriod: bigint;\n}\n\n/** Raw `Recovery` struct from `getRecovery(address,bytes32)`. */\nexport interface RawRecovery {\n newOwners: string[];\n newThreshold: bigint;\n approvalCount: bigint;\n executionTime: bigint;\n expiration: bigint;\n requiredThreshold: bigint;\n executed: boolean;\n}\n\n/**\n * Typed facade over `SocialRecoveryModule`.\n *\n * Every function is wallet-scoped: one module deployment serves every vault, so the\n * vault address is always the first argument.\n */\nexport class RecoveryContract {\n constructor(\n readonly contract: Contract,\n private readonly retry: RetryOptions = {},\n ) {}\n\n private fn(signature: string) {\n return this.contract.getFunction(signature);\n }\n\n /**\n * Reads retry transient RPC failures (see {@link withRetry}); writes never do,\n * because a resubmit that looks like a timeout may already be in the mempool.\n */\n private read<T>(signature: string, ...args: unknown[]): Promise<T> {\n return withRetry(() => this.fn(signature)(...args) as Promise<T>, this.retry);\n }\n\n get interface() {\n return this.contract.interface;\n }\n\n // ---- reads ---------------------------------------------------------------\n\n getRecoveryConfig(vault: Address): Promise<RawRecoveryConfig> {\n return this.read<RawRecoveryConfig>('getRecoveryConfig(address)', vault);\n }\n\n getRecovery(vault: Address, recoveryHash: Bytes32): Promise<RawRecovery> {\n return this.read<RawRecovery>('getRecovery(address,bytes32)', vault, recoveryHash);\n }\n\n isGuardian(vault: Address, guardian: Address): Promise<boolean> {\n return this.read<boolean>('isGuardian(address,address)', vault, guardian);\n }\n\n getPendingRecoveryHashes(vault: Address): Promise<string[]> {\n return this.read<string[]>('getPendingRecoveryHashes(address)', vault);\n }\n\n hasPendingRecoveries(vault: Address): Promise<boolean> {\n return this.read<boolean>('hasPendingRecoveries(address)', vault);\n }\n\n recoveryApprovals(vault: Address, recoveryHash: Bytes32, guardian: Address): Promise<boolean> {\n return this.read<boolean>(\n 'recoveryApprovals(address,bytes32,address)',\n vault, recoveryHash, guardian,\n );\n }\n\n recoveryNonces(vault: Address): Promise<bigint> {\n return this.read<bigint>('recoveryNonces(address)', vault);\n }\n\n maxGuardians(): Promise<bigint> {\n return this.read<bigint>('MAX_GUARDIANS()');\n }\n\n /** Hash for an explicit nonce. Use {@link predictNextRecoveryHash} for the next one. */\n getRecoveryHash(\n vault: Address,\n newOwners: Address[],\n newThreshold: number,\n nonce: bigint | number,\n ): Promise<Bytes32> {\n return this.read<Bytes32>(\n 'getRecoveryHash(address,address[],uint256,uint256)',\n vault, newOwners, newThreshold, nonce,\n );\n }\n\n /** Hash the next `initiateRecovery` would produce, at the current nonce. */\n predictNextRecoveryHash(\n vault: Address,\n newOwners: Address[],\n newThreshold: number,\n ): Promise<Bytes32> {\n return this.read<Bytes32>(\n 'predictNextRecoveryHash(address,address[],uint256)',\n vault, newOwners, newThreshold,\n );\n }\n\n // ---- writes --------------------------------------------------------------\n\n initiateRecovery(\n vault: Address,\n newOwners: Address[],\n newThreshold: number,\n ): Promise<ContractTransactionResponse> {\n return this.fn('initiateRecovery(address,address[],uint256)')(\n vault,\n newOwners,\n newThreshold,\n ) as Promise<ContractTransactionResponse>;\n }\n\n approveRecovery(vault: Address, recoveryHash: Bytes32): Promise<ContractTransactionResponse> {\n return this.fn('approveRecovery(address,bytes32)')(\n vault,\n recoveryHash,\n ) as Promise<ContractTransactionResponse>;\n }\n\n revokeRecoveryApproval(\n vault: Address,\n recoveryHash: Bytes32,\n ): Promise<ContractTransactionResponse> {\n return this.fn('revokeRecoveryApproval(address,bytes32)')(\n vault,\n recoveryHash,\n ) as Promise<ContractTransactionResponse>;\n }\n\n executeRecovery(vault: Address, recoveryHash: Bytes32): Promise<ContractTransactionResponse> {\n return this.fn('executeRecovery(address,bytes32)')(\n vault,\n recoveryHash,\n ) as Promise<ContractTransactionResponse>;\n }\n\n cancelRecovery(vault: Address, recoveryHash: Bytes32): Promise<ContractTransactionResponse> {\n return this.fn('cancelRecovery(address,bytes32)')(\n vault,\n recoveryHash,\n ) as Promise<ContractTransactionResponse>;\n }\n\n expireRecovery(vault: Address, recoveryHash: Bytes32): Promise<ContractTransactionResponse> {\n return this.fn('expireRecovery(address,bytes32)')(\n vault,\n recoveryHash,\n ) as Promise<ContractTransactionResponse>;\n }\n}\n","import type { RecoveryStatus, TransactionStatus } from '../types.js';\n\nexport interface RawTransactionState {\n executed: boolean;\n cancelled: boolean;\n /** From `expiredTxs[txHash]` — distinguishes expiry from voluntary cancellation. */\n isExpired?: boolean;\n expiration: number;\n executionDelay: number;\n approvedAt: number;\n approvalCount: number;\n threshold: number;\n /** Set when a TransactionFailed event was indexed. */\n failed?: boolean;\n}\n\nexport function nowSeconds(): number {\n return Math.floor(Date.now() / 1000);\n}\n\n/**\n * `approvedAt + executionDelay`, or 0 when the timelock clock has not started.\n *\n * `approvedAt` is written once, on the first threshold crossing, and is never\n * cleared — revoking approvals below the threshold does not reset the clock.\n */\nexport function executableAfterOf(approvedAt: number, executionDelay: number): number {\n return approvedAt > 0 ? approvedAt + executionDelay : 0;\n}\n\n/**\n * Derive the lifecycle status from raw contract state.\n *\n * `ready` and `timelocked` refine the contract's \"pending\": both mean not yet\n * executed with quorum reached, differing only on whether the delay has elapsed.\n * The contract has no such distinction — it is computed here so callers do not\n * have to reimplement the timelock arithmetic.\n */\nexport function deriveStatus(state: RawTransactionState, at: number = nowSeconds()): TransactionStatus {\n if (state.failed) return 'failed';\n if (state.executed) return 'executed';\n\n // expireTransaction sets both `cancelled` and `expiredTxs`, so check expiry first\n // to avoid reporting a timed-out transaction as voluntarily cancelled.\n if (state.cancelled) return state.isExpired ? 'expired' : 'cancelled';\n\n // Past its deadline but not yet formally closed by expireTransaction.\n if (state.expiration > 0 && at > state.expiration) return 'expired';\n\n if (state.approvalCount < state.threshold) return 'pending';\n\n const executableAfter = executableAfterOf(state.approvedAt, state.executionDelay);\n // approvedAt === 0 with quorum met means the clock has not started (e.g. the\n // threshold was lowered after approvals were collected). The first execute call\n // will start it rather than execute — treat that as timelocked, not ready.\n if (state.executionDelay > 0 && (state.approvedAt === 0 || at < executableAfter)) {\n return 'timelocked';\n }\n return 'ready';\n}\n\n/** Whether the status admits no further state transitions. */\nexport function isTerminal(status: TransactionStatus): boolean {\n return status === 'executed' || status === 'failed' || status === 'cancelled' || status === 'expired';\n}\n\nexport interface RawRecoveryState {\n executed: boolean;\n approvalCount: number;\n /** Threshold captured at initiation, not the current config. */\n requiredThreshold: number;\n executionTime: number;\n expiration: number;\n}\n\n/**\n * Derive a recovery's lifecycle status from raw module state.\n *\n * Expiry is computed from `expiration` rather than taken from a stored flag, because\n * nothing transitions a recovery to expired on its own — `expireRecovery` is a\n * permissionless cleanup call somebody has to make. The indexer only writes an\n * expired status when it sees `RecoveryExpiredEvent`, so an un-cleaned recovery reads\n * as `pending` there long after it died. Computing it here keeps the SDK honest\n * regardless of which side the data came from.\n *\n * `cancelled` is never returned: `cancelRecovery` deletes the on-chain struct, so it\n * is only observable through indexed history.\n */\nexport function deriveRecoveryStatus(\n state: RawRecoveryState,\n at: number = nowSeconds(),\n): Exclude<RecoveryStatus, 'cancelled'> {\n if (state.executed) return 'executed';\n if (state.expiration > 0 && at > state.expiration) return 'expired';\n if (state.approvalCount < state.requiredThreshold) return 'pending';\n if (at < state.executionTime) return 'timelocked';\n return 'ready';\n}\n","import { getAddress } from 'quais';\nimport type { Connection } from './chain/connection.js';\nimport { TokenContract } from './chain/token-contract.js';\nimport { DEFAULT_CONCURRENCY, mapPooled } from './pool.js';\nimport type { IndexerQueries } from './indexer/queries.js';\nimport type { TokenRow, TokenTransferRow } from './indexer/schemas.js';\nimport { sanitizeText } from './text.js';\nimport type { Address } from './types.js';\n\nexport interface TokenBalance {\n token: Address;\n standard: 'ERC20' | 'ERC721' | 'ERC1155';\n /**\n * Ticker as the token reports it — deployer-controlled, so passed through\n * {@link sanitizeText} and capped. Falls back to `???` when the token has none or\n * supplied nothing printable.\n */\n symbol: string;\n /** Display name. Same provenance and treatment as {@link symbol}. */\n name: string;\n decimals: number;\n /** ERC20: raw units. ERC721: number held. ERC1155: total across ids. */\n balance: bigint;\n /** ERC721 / ERC1155 only. */\n tokenIds?: string[];\n /** True when the balance came from an on-chain read rather than transfer replay. */\n verified: boolean;\n /**\n * Set when more candidate ids existed than `maxTokenIdChecks` allowed, so\n * `tokenIds` is a subset. The `balance` is still the authoritative on-chain count.\n */\n tokenIdsTruncated?: boolean;\n}\n\nexport interface VaultBalances {\n native: bigint;\n tokens: TokenBalance[];\n /**\n * Set when a scan limit was hit, so the result may be incomplete. Silent\n * truncation would read as \"these are all the holdings\" when they are not.\n */\n truncated?: {\n /** More transfer history existed than `transferScanLimit` scanned. */\n transfers?: boolean;\n /** More distinct tokens were discovered than `maxTokens` allowed. */\n tokens?: boolean;\n };\n}\n\nexport interface BalanceOptions {\n /**\n * Confirm each candidate balance with an on-chain read. Slower, but authoritative —\n * a token that moved through a path the indexer does not observe still reports\n * correctly. Default true.\n */\n verify?: boolean;\n /** Cap on tokens considered, newest activity first. Default 50. */\n maxTokens?: number;\n /**\n * How many recent transfer rows to scan when discovering tokens. Default 500.\n *\n * Scanned across as many indexer requests as it takes, so this is a real budget\n * rather than a single page size. A vault with more transfers than this may not\n * surface its oldest holdings, so raise it for long-lived vaults. Reported back in\n * {@link VaultBalances.truncated}.\n */\n transferScanLimit?: number;\n /** Cap on ERC721 ids ownership-checked per token. Default 100. */\n maxTokenIdChecks?: number;\n /**\n * Ceiling on in-flight RPC reads. Default 8.\n *\n * Applied at both fan-out levels independently, so the true ceiling is the square\n * of this. Raise it against a private node; lower it if a shared endpoint is\n * rate-limiting you.\n */\n concurrency?: number;\n}\n\n/**\n * Aggregate a vault's holdings.\n *\n * Discovery is indexer-driven: `token_transfers` tells us which contracts a vault has\n * ever touched, which the chain cannot answer without scanning every log. Amounts are\n * then read on chain by default, because replaying transfers misses anything the\n * indexer did not observe (a token discovered after the transfer, a rebasing balance,\n * a direct mint). Set `verify: false` to skip the reads and accept replayed totals.\n */\nexport async function loadBalances(\n connection: Connection,\n queries: IndexerQueries | null,\n vault: Address,\n options: BalanceOptions = {},\n): Promise<VaultBalances> {\n const verify = options.verify !== false;\n const maxTokens = options.maxTokens ?? 50;\n const transferScanLimit = options.transferScanLimit ?? 500;\n const maxTokenIdChecks = options.maxTokenIdChecks ?? 100;\n const concurrency = Math.max(1, options.concurrency ?? DEFAULT_CONCURRENCY);\n const address = getAddress(vault);\n\n const native = BigInt(await connection.provider.getBalance(address));\n if (!queries) return { native, tokens: [] };\n\n // Discover candidates from transfer history, most recent first. Scanned as a budget\n // across however many requests it takes, so `hasMore` below means \"older transfers\n // exist beyond the budget\", not \"the page was clamped\".\n const transfers = await queries.tokenTransferScan(address, transferScanLimit);\n const seen = new Map<string, TokenTransferRow[]>();\n for (const row of transfers.data) {\n const key = row.token_address.toLowerCase();\n const list = seen.get(key);\n if (list) list.push(row);\n else seen.set(key, [row]);\n }\n\n const allCandidates = Array.from(seen.keys());\n const candidates = allCandidates.slice(0, maxTokens);\n const truncated = {\n ...(transfers.hasMore ? { transfers: true } : {}),\n ...(allCandidates.length > maxTokens ? { tokens: true } : {}),\n };\n\n if (candidates.length === 0) {\n return { native, tokens: [], ...(Object.keys(truncated).length ? { truncated } : {}) };\n }\n\n const metadata = await queries.tokens(candidates);\n const byAddress = new Map(metadata.map((t) => [t.address.toLowerCase(), t]));\n\n const balances = await mapPooled(candidates, concurrency, (token) =>\n buildBalance(\n connection,\n address,\n token,\n byAddress.get(token),\n seen.get(token) ?? [],\n verify,\n maxTokenIdChecks,\n concurrency,\n ),\n );\n\n return {\n native,\n // Drop dust and fully-exited positions so callers get a holdings view, not a history.\n tokens: balances.filter((b): b is TokenBalance => b !== null && b.balance > 0n),\n ...(Object.keys(truncated).length ? { truncated } : {}),\n };\n}\n\nasync function buildBalance(\n connection: Connection,\n vault: Address,\n token: string,\n meta: TokenRow | undefined,\n transfers: TokenTransferRow[],\n verify: boolean,\n maxTokenIdChecks: number,\n concurrency: number,\n): Promise<TokenBalance | null> {\n const standard = meta?.standard ?? inferStandard(transfers);\n const replayed = replayBalance(transfers, standard);\n\n const base: TokenBalance = {\n token: getAddress(token),\n standard,\n // Deployer-controlled strings headed for someone's terminal. See `src/text.ts`.\n symbol: sanitizeText(meta?.symbol, 32) || '???',\n name: sanitizeText(meta?.name, 64) || 'Unknown token',\n decimals: meta?.decimals ?? (standard === 'ERC20' ? 18 : 0),\n balance: replayed.balance,\n ...(replayed.tokenIds.length > 0 ? { tokenIds: replayed.tokenIds } : {}),\n verified: false,\n };\n\n if (!verify) return base;\n\n // Through the facade, not a bare `new Contract`: these are the highest-volume reads\n // the SDK issues and so the likeliest to meet a rate limit. See `TokenContract`.\n const contract = new TokenContract(connection.token(token, standard), connection.retry);\n\n try {\n if (standard === 'ERC20') {\n return { ...base, balance: BigInt(await contract.balanceOf(vault)), verified: true };\n }\n\n if (standard === 'ERC721') {\n const count = await contract.balanceOf(vault);\n // ERC721 has no enumeration without the optional extension; keep the replayed\n // id list but trust the on-chain count.\n const owned = await filterOwned(\n contract,\n vault,\n replayed.tokenIds,\n maxTokenIdChecks,\n concurrency,\n );\n return {\n ...base,\n balance: BigInt(count),\n ...(owned.length > 0 ? { tokenIds: owned } : {}),\n ...(replayed.tokenIds.length > maxTokenIdChecks ? { tokenIdsTruncated: true } : {}),\n verified: true,\n };\n }\n\n // ERC1155: balances are per-id, so read the ids the vault has touched.\n const ids = replayed.tokenIds;\n if (ids.length === 0) return { ...base, verified: true };\n\n const amounts = await contract.balanceOfBatch(\n ids.map(() => vault),\n ids,\n );\n\n const held: string[] = [];\n let total = 0n;\n ids.forEach((id, i) => {\n const amount = BigInt(amounts[i] ?? 0);\n if (amount > 0n) {\n held.push(id);\n total += amount;\n }\n });\n return { ...base, balance: total, ...(held.length > 0 ? { tokenIds: held } : {}), verified: true };\n } catch {\n // Unreadable contract (self-destructed, non-standard, wrong shard): fall back to\n // the replayed figure rather than dropping the position silently.\n return base;\n }\n}\n\n/** Net inflows minus outflows, and the set of ids currently believed held. */\nfunction replayBalance(\n transfers: TokenTransferRow[],\n standard: 'ERC20' | 'ERC721' | 'ERC1155',\n): { balance: bigint; tokenIds: string[] } {\n if (standard === 'ERC20') {\n let balance = 0n;\n for (const t of transfers) {\n const value = safeBigInt(t.value);\n balance += t.direction === 'inflow' ? value : -value;\n }\n return { balance: balance > 0n ? balance : 0n, tokenIds: [] };\n }\n\n // NFTs: track per-id net position, oldest first so later transfers win.\n const perId = new Map<string, bigint>();\n const ordered = [...transfers].sort((a, b) => Number(a.block_number) - Number(b.block_number));\n for (const t of ordered) {\n const id = t.token_id ?? '0';\n const amount = standard === 'ERC721' ? 1n : safeBigInt(t.value);\n const current = perId.get(id) ?? 0n;\n perId.set(id, current + (t.direction === 'inflow' ? amount : -amount));\n }\n\n const tokenIds: string[] = [];\n let balance = 0n;\n for (const [id, amount] of perId) {\n if (amount > 0n) {\n tokenIds.push(id);\n balance += amount;\n }\n }\n return { balance, tokenIds };\n}\n\n/** Confirm current ownership of candidate ERC721 ids. */\nasync function filterOwned(\n contract: TokenContract,\n vault: Address,\n ids: string[],\n limit: number,\n concurrency: number,\n): Promise<string[]> {\n if (ids.length === 0) return [];\n const results = await mapPooled(ids.slice(0, limit), concurrency, async (id) => {\n try {\n const owner = await contract.ownerOf(id);\n return owner.toLowerCase() === vault.toLowerCase() ? id : null;\n } catch {\n return null; // burned or non-existent\n }\n });\n return results.filter((id): id is string => id !== null);\n}\n\nfunction inferStandard(transfers: TokenTransferRow[]): 'ERC20' | 'ERC721' | 'ERC1155' {\n const withId = transfers.find((t) => t.token_id != null);\n if (!withId) return 'ERC20';\n // ERC1155 fans batches out with a batch_index; ERC721 never does.\n return transfers.some((t) => (t.batch_index ?? 0) > 0) ? 'ERC1155' : 'ERC721';\n}\n\nfunction safeBigInt(value: string): bigint {\n try {\n return BigInt(value);\n } catch {\n return 0n;\n }\n}\n","import type { Contract } from 'quais';\nimport { withRetry, type RetryOptions } from './retry.js';\nimport type { Address } from '../types.js';\n\n/**\n * Retry policy for token reads, deliberately tighter than the client's default.\n *\n * These are the highest-volume reads the SDK issues — a `balances()` call fans out\n * over every token a vault has ever touched — so they are the most likely to trip a\n * shared endpoint's rate limit, which is exactly what a retry should absorb.\n *\n * But they are also the reads most likely to fail *permanently* and unremarkably. A\n * self-destructed or non-standard token answers `balanceOf` with `0x`, which `quais`\n * reports as `BAD_DATA` — a code the shared policy classes as transient. Under the\n * default three attempts with backoff, one junk token in a vault's history would cost\n * seconds before the caller falls back to the replayed figure it was always going to\n * use. Two attempts absorbs a genuine blip without paying for that twice over.\n */\nconst TOKEN_RETRY: RetryOptions = { maxAttempts: 2, baseDelayMs: 150 };\n\n/**\n * Typed, retrying facade over an ERC20/721/1155 contract.\n *\n * Tokens are only ever read, never written to — the vault's own proposal flow is what\n * moves them — so there is no write half here and no signer involved.\n */\nexport class TokenContract {\n private readonly retry: RetryOptions;\n\n constructor(\n readonly contract: Contract,\n retry: RetryOptions = {},\n ) {\n // Defaults, not overrides: a caller who explicitly configured a retry policy\n // meant it, and still gets their `onRetry` hook either way.\n this.retry = { ...TOKEN_RETRY, ...retry };\n }\n\n private read<T>(signature: string, ...args: unknown[]): Promise<T> {\n return withRetry(() => this.contract.getFunction(signature)(...args) as Promise<T>, this.retry);\n }\n\n /** ERC20 units held, or — for ERC721 — the number of tokens held. */\n balanceOf(owner: Address): Promise<bigint> {\n return this.read<bigint>('balanceOf(address)', owner);\n }\n\n /** ERC721 only. Reverts for a burned or never-minted id. */\n ownerOf(tokenId: string | bigint): Promise<string> {\n return this.read<string>('ownerOf(uint256)', tokenId);\n }\n\n /** ERC1155 only. One call for many ids, so it stays a single round trip. */\n balanceOfBatch(owners: Address[], ids: Array<string | bigint>): Promise<bigint[]> {\n return this.read<bigint[]>('balanceOfBatch(address[],uint256[])', owners, ids);\n }\n}\n","/**\n * Map with a bounded number of in-flight promises, preserving input order.\n *\n * A plain `Promise.all` over a fan-out the caller does not control is a liability:\n * `balances()` can reach `maxTokens × maxTokenIdChecks` — 5,000 with the defaults —\n * concurrent RPC reads from one call, and a batched transaction read fans out over\n * however many hashes the caller passed. Public endpoints rate-limit long before\n * either, and the failures come back as transient errors on reads that would each\n * have succeeded on their own.\n *\n * Rejections propagate: the first failure rejects the whole call, matching\n * `Promise.all`. Callers that want per-item tolerance catch inside `fn`.\n */\nexport async function mapPooled<T, R>(\n items: readonly T[],\n limit: number,\n fn: (item: T, index: number) => Promise<R>,\n): Promise<R[]> {\n const results = new Array<R>(items.length);\n let next = 0;\n\n const worker = async (): Promise<void> => {\n for (;;) {\n const i = next++;\n if (i >= items.length) return;\n // Safe: the bound check above proves the index is in range.\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n results[i] = await fn(items[i]!, i);\n }\n };\n\n await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));\n return results;\n}\n\n/** Default ceiling on concurrent chain reads issued by one SDK call. */\nexport const DEFAULT_CONCURRENCY = 8;\n","import type { RealtimeChannel } from '@supabase/realtime-js';\nimport { isAddress } from 'quais';\nimport type { IndexerClient } from './client.js';\nimport { ValidationError } from '../errors/index.js';\nimport type { Address } from '../types.js';\n\n/** Indexer tables a vault subscription can follow. */\nexport type WatchTopic =\n | 'transactions'\n | 'confirmations'\n | 'owners'\n | 'modules'\n | 'deposits'\n | 'tokenTransfers'\n | 'recoveries'\n | 'signedMessages';\n\nconst TABLE_FOR: Record<WatchTopic, string> = {\n transactions: 'transactions',\n confirmations: 'confirmations',\n owners: 'wallet_owners',\n modules: 'wallet_modules',\n deposits: 'deposits',\n tokenTransfers: 'token_transfers',\n recoveries: 'social_recoveries',\n signedMessages: 'signed_messages',\n};\n\nexport interface WatchEvent {\n topic: WatchTopic;\n table: string;\n /** Postgres operation that produced the event. */\n type: 'INSERT' | 'UPDATE' | 'DELETE';\n /** Row after the change. Absent for DELETE. */\n row: Record<string, unknown> | null;\n /** Row before the change, when the table's replica identity provides it. */\n previous: Record<string, unknown> | null;\n}\n\nexport interface WatchOptions {\n topics?: WatchTopic[];\n /** Called on subscription lifecycle changes, so callers can surface reconnects. */\n onStatus?: (status: string, error?: Error) => void;\n}\n\n/** Handle returned by {@link watchVault}. Call `unsubscribe` to release the channel. */\nexport interface Subscription {\n unsubscribe(): Promise<void>;\n readonly topics: WatchTopic[];\n}\n\nconst DEFAULT_TOPICS: WatchTopic[] = ['transactions', 'confirmations', 'owners'];\n\n/**\n * Follow indexer changes for one vault over Supabase Realtime.\n *\n * All topics share a single channel — one WebSocket per vault rather than one per\n * table, which matters because Realtime caps concurrent channels per client.\n *\n * Realtime delivers *indexer* writes, so events arrive only after the indexer has\n * processed the block. It is a change feed, not a chain subscription: use it to know\n * when to re-read, and re-read through `Vault` so approval counts stay correct.\n */\nexport function watchVault(\n client: IndexerClient,\n vault: Address,\n handler: (event: WatchEvent) => void,\n options: WatchOptions = {},\n): Subscription {\n // The address is interpolated into a PostgREST filter string, so validate it here\n // rather than trusting the caller — this function is exported, not just reached\n // through `Vault.watch()` where the address is already checked.\n if (!isAddress(vault)) {\n throw new ValidationError(`Invalid vault address for subscription: \"${vault}\".`);\n }\n const topics = options.topics ?? DEFAULT_TOPICS;\n const address = vault.toLowerCase();\n const schema = client.config.schema;\n\n // Channel names must be unique per client; include the vault so two handles on\n // different vaults do not collide.\n const channel: RealtimeChannel = client.channel(`quaivault:${schema}:${address}`);\n\n for (const topic of topics) {\n const table = TABLE_FOR[topic];\n channel.on(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n 'postgres_changes' as any,\n {\n event: '*',\n schema,\n table,\n // Every watched table keys the vault on wallet_address.\n filter: `wallet_address=eq.${address}`,\n },\n (payload: {\n eventType: 'INSERT' | 'UPDATE' | 'DELETE';\n new: Record<string, unknown> | null;\n old: Record<string, unknown> | null;\n }) => {\n handler({\n topic,\n table,\n type: payload.eventType,\n row: payload.new && Object.keys(payload.new).length > 0 ? payload.new : null,\n previous: payload.old && Object.keys(payload.old).length > 0 ? payload.old : null,\n });\n },\n );\n }\n\n channel.subscribe((status, err) => {\n options.onStatus?.(status, err instanceof Error ? err : undefined);\n });\n\n return {\n topics,\n async unsubscribe() {\n await client.removeChannel(channel);\n },\n };\n}\n","import { formatQuai, getBytes } from 'quais';\nimport { interfaces } from '../encode/index.js';\nimport type { Address, DecodedCall, Hex, TransactionKind } from '../types.js';\n\nexport interface DecodeContext {\n /** The vault the transaction belongs to — used to detect self-calls. */\n vault: Address;\n to: Address;\n value: bigint;\n data: Hex;\n /** Known module addresses, for classifying `module_config` calls. */\n socialRecovery?: Address;\n multiSendCallOnly?: Address;\n}\n\nexport interface DecodeResult {\n kind: TransactionKind;\n decoded?: DecodedCall;\n summary: string;\n}\n\nconst SELF_CALL_ADMIN = new Set([\n 'addOwner',\n 'removeOwner',\n 'changeThreshold',\n 'enableModule',\n 'disableModule',\n 'cancelByConsensus',\n 'setMinExecutionDelay',\n 'addDelegatecallTarget',\n 'removeDelegatecallTarget',\n]);\n\nconst MESSAGE_SIGNING = new Set(['signMessage', 'unsignMessage']);\n\nfunction short(address: string): string {\n return address.length > 12 ? `${address.slice(0, 6)}…${address.slice(-4)}` : address;\n}\n\nfunction formatDuration(seconds: number): string {\n if (seconds === 0) return 'none';\n const units: Array<[number, string]> = [\n [86400, 'day'],\n [3600, 'hour'],\n [60, 'minute'],\n ];\n for (const [size, label] of units) {\n if (seconds >= size) {\n const n = Math.floor(seconds / size);\n return `${n} ${label}${n === 1 ? '' : 's'}`;\n }\n }\n return `${seconds} seconds`;\n}\n\nfunction namedArgs(fragmentInputs: ReadonlyArray<{ name: string }>, args: readonly unknown[]) {\n const out: Record<string, unknown> = {};\n fragmentInputs.forEach((input, i) => {\n out[input.name || `arg${i}`] = args[i];\n });\n return out;\n}\n\n/**\n * Classify and describe a proposed vault transaction from its calldata.\n *\n * Resolution order matters: self-calls are checked against the vault ABI first,\n * because several vault selectors would otherwise be ambiguous with token calls.\n */\nexport function decodeCall(ctx: DecodeContext): DecodeResult {\n const { vault, to, value, data } = ctx;\n const isSelfCall = to.toLowerCase() === vault.toLowerCase();\n const hasData = typeof data === 'string' && data !== '0x' && data.length > 2;\n\n if (!hasData) {\n return {\n kind: 'transfer',\n summary: `Transfer ${formatQuai(value)} QUAI to ${short(to)}`,\n };\n }\n\n // --- vault self-calls\n if (isSelfCall) {\n const parsed = tryParse(interfaces.vault, data);\n if (parsed) {\n const decoded: DecodedCall = {\n name: parsed.name,\n signature: parsed.signature,\n args: parsed.args,\n target: 'vault',\n };\n if (MESSAGE_SIGNING.has(parsed.name)) {\n return {\n kind: 'message_signing',\n decoded,\n summary:\n parsed.name === 'signMessage'\n ? 'Sign a message on behalf of the vault (EIP-1271)'\n : 'Revoke a previously signed message (EIP-1271)',\n };\n }\n if (SELF_CALL_ADMIN.has(parsed.name)) {\n return { kind: 'wallet_admin', decoded, summary: describeAdmin(parsed.name, parsed.args) };\n }\n return { kind: 'wallet_admin', decoded, summary: `Vault self-call: ${parsed.name}` };\n }\n }\n\n // --- social recovery module\n if (ctx.socialRecovery && to.toLowerCase() === ctx.socialRecovery.toLowerCase()) {\n const parsed = tryParse(interfaces.recovery, data);\n if (parsed) {\n const decoded: DecodedCall = { ...parsed, target: 'socialRecovery' };\n if (parsed.name === 'setupRecovery') {\n const guardians = parsed.args.guardians as unknown[] | undefined;\n const threshold = parsed.args.threshold;\n return {\n kind: 'recovery_setup',\n decoded,\n summary: `Configure social recovery: ${guardians?.length ?? '?'} guardians, ${String(\n threshold ?? '?',\n )} required`,\n };\n }\n return { kind: 'module_config', decoded, summary: `Social recovery: ${parsed.name}` };\n }\n }\n\n // --- MultiSend batch\n if (ctx.multiSendCallOnly && to.toLowerCase() === ctx.multiSendCallOnly.toLowerCase()) {\n const parsed = tryParse(interfaces.multiSend, data);\n if (parsed?.name === 'multiSend') {\n const inner = decodeMultiSendPayload(parsed.args.transactions as Hex);\n return {\n kind: 'batched_call',\n decoded: { ...parsed, target: 'multiSend' },\n summary: `Batched call: ${inner.length} sub-transaction${inner.length === 1 ? '' : 's'}`,\n };\n }\n }\n\n // --- module execution via Zodiac\n const asVault = tryParse(interfaces.vault, data);\n if (asVault?.name.startsWith('execTransactionFromModule')) {\n return {\n kind: 'module_execution',\n decoded: { ...asVault, target: 'vault' },\n summary: `Module execution against ${short(String(asVault.args.to ?? to))}`,\n };\n }\n\n // --- token standards\n const erc20 = tryParse(interfaces.erc20, data);\n if (erc20 && ['transfer', 'approve', 'transferFrom'].includes(erc20.name)) {\n return {\n kind: 'erc20_transfer',\n decoded: { ...erc20, target: 'erc20' },\n summary: describeErc20(erc20.name, erc20.args, to),\n };\n }\n\n const erc1155 = tryParse(interfaces.erc1155, data);\n if (erc1155 && erc1155.name.startsWith('safe')) {\n return {\n kind: 'erc1155_transfer',\n decoded: { ...erc1155, target: 'erc1155' },\n summary:\n erc1155.name === 'safeBatchTransferFrom'\n ? `Transfer a batch of ERC1155 tokens from ${short(to)}`\n : `Transfer ERC1155 token #${String(erc1155.args.id ?? '?')} from ${short(to)}`,\n };\n }\n\n const erc721 = tryParse(interfaces.erc721, data);\n if (erc721 && erc721.name === 'safeTransferFrom') {\n return {\n kind: 'erc721_transfer',\n decoded: { ...erc721, target: 'erc721' },\n summary: `Transfer NFT #${String(erc721.args.tokenId ?? '?')} to ${short(\n String(erc721.args.to ?? '?'),\n )}`,\n };\n }\n\n const selector = data.slice(0, 10);\n return {\n kind: 'external_call',\n summary:\n `Call ${short(to)} (selector ${selector})` +\n (value > 0n ? ` with ${formatQuai(value)} QUAI` : ''),\n };\n}\n\nfunction tryParse(\n iface: (typeof interfaces)[keyof typeof interfaces],\n data: Hex,\n): { name: string; signature: string; args: Record<string, unknown> } | null {\n try {\n const parsed = iface.parseTransaction({ data });\n if (!parsed) return null;\n return {\n name: parsed.name,\n signature: parsed.fragment.format('sighash'),\n args: namedArgs(parsed.fragment.inputs, parsed.args),\n };\n } catch {\n return null;\n }\n}\n\nfunction describeAdmin(name: string, args: Record<string, unknown>): string {\n switch (name) {\n case 'addOwner':\n return `Add owner ${short(String(args.owner))}`;\n case 'removeOwner':\n return `Remove owner ${short(String(args.owner))}`;\n case 'changeThreshold':\n return `Change approval threshold to ${String(args._threshold ?? args.threshold)}`;\n case 'enableModule':\n return `Enable module ${short(String(args.module))}`;\n case 'disableModule':\n return `Disable module ${short(String(args.module))}`;\n case 'setMinExecutionDelay':\n return `Set minimum execution delay to ${formatDuration(Number(args.delay ?? 0))}`;\n case 'addDelegatecallTarget':\n return `Whitelist ${short(String(args.target))} as a DelegateCall target`;\n case 'removeDelegatecallTarget':\n return `Remove ${short(String(args.target))} from the DelegateCall whitelist`;\n case 'cancelByConsensus':\n return `Cancel transaction ${short(String(args.txHash))} by consensus`;\n default:\n return `Vault admin: ${name}`;\n }\n}\n\nfunction describeErc20(name: string, args: Record<string, unknown>, tokenAddress: string): string {\n switch (name) {\n case 'transfer':\n return `Transfer ${String(args.amount)} units of token ${short(tokenAddress)} to ${short(\n String(args.to),\n )}`;\n case 'approve':\n return `Approve ${short(String(args.spender))} to spend ${String(args.amount)} units of ${short(\n tokenAddress,\n )}`;\n default:\n return `ERC20 ${name} on ${short(tokenAddress)}`;\n }\n}\n\nexport interface DecodedBatchCall {\n operation: number;\n to: Address;\n value: bigint;\n data: Hex;\n}\n\n/**\n * Unpack a MultiSend payload into its constituent calls.\n * Layout per call: `operation(1) ‖ to(20) ‖ value(32) ‖ dataLength(32) ‖ data`.\n */\nexport function decodeMultiSendPayload(payload: Hex): DecodedBatchCall[] {\n const bytes = getBytes(payload);\n const out: DecodedBatchCall[] = [];\n let offset = 0;\n\n while (offset < bytes.length) {\n // 1 + 20 + 32 + 32 = 85 bytes of fixed header\n if (offset + 85 > bytes.length) break;\n\n // Safe: the `offset + 85 > bytes.length` guard above proves this index is in range.\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const operation = bytes[offset]!;\n offset += 1;\n\n const to = hexOf(bytes.subarray(offset, offset + 20));\n offset += 20;\n\n const value = BigInt(hexOf(bytes.subarray(offset, offset + 32)));\n offset += 32;\n\n const length = Number(BigInt(hexOf(bytes.subarray(offset, offset + 32))));\n offset += 32;\n\n if (offset + length > bytes.length) break;\n const data = hexOf(bytes.subarray(offset, offset + length));\n offset += length;\n\n out.push({ operation, to, value, data });\n }\n\n return out;\n}\n\nfunction hexOf(bytes: Uint8Array): string {\n let s = '0x';\n for (const b of bytes) s += b.toString(16).padStart(2, '0');\n return s;\n}\n","import type { Address, Affordance, VaultTransaction } from '../types.js';\nimport { executableAfterOf, isTerminal, nowSeconds } from './status.js';\n\nexport interface AffordanceContext {\n tx: VaultTransaction;\n caller: Address;\n isOwner: boolean;\n /** Whether `caller` currently has a threshold-counting approval. */\n hasApproved: boolean;\n at?: number;\n}\n\nfunction terminalReason(tx: VaultTransaction): string {\n switch (tx.status) {\n case 'executed':\n return 'The transaction has already been executed.';\n case 'failed':\n return 'The transaction executed but its target call reverted. This state is terminal.';\n case 'cancelled':\n return 'The transaction has been cancelled.';\n case 'expired':\n return 'The transaction passed its expiration timestamp.';\n default:\n return 'The transaction is in a terminal state.';\n }\n}\n\n/**\n * Enumerate which actions `caller` may legally take on `tx` right now, and when a\n * blocked action becomes available.\n *\n * Every rule here mirrors an on-chain check, so callers can plan instead of\n * discovering constraints through reverted transactions:\n *\n * - `onlyOwner` on approve / revoke / execute / cancel\n * - epoch-based approvals (`_approvalValid`) for already-approved / not-approved\n * - `approvedAt != 0` permanently locking proposer-cancel, even after revocations\n * - the timelock on external calls (self-calls bypass it)\n * - expiration, and the permissionless `expireTransaction` cleanup path\n */\nexport function computeAffordances(ctx: AffordanceContext): Affordance[] {\n const { tx, isOwner, hasApproved } = ctx;\n const at = ctx.at ?? nowSeconds();\n const terminal = isTerminal(tx.status);\n const quorum = tx.approvalCount >= tx.threshold;\n const isSelfCall = tx.to.toLowerCase() === tx.vault.toLowerCase();\n const executableAfter = executableAfterOf(tx.approvedAt, tx.executionDelay);\n // Self-calls always execute immediately; the contract stores executionDelay 0 for\n // them, but guard here too so a malformed record cannot produce a wrong answer.\n const timelockActive =\n !isSelfCall && tx.executionDelay > 0 && (tx.approvedAt === 0 || at < executableAfter);\n const isProposer = tx.proposer.toLowerCase() === ctx.caller.toLowerCase();\n\n const out: Affordance[] = [];\n\n const notOwner = (action: Affordance['action']): Affordance => ({\n action,\n allowed: false,\n reason: 'Only owners of this vault may take this action.',\n blockedBy: 'not_owner',\n });\n const isTerminalBlocked = (action: Affordance['action']): Affordance => ({\n action,\n allowed: false,\n reason: terminalReason(tx),\n blockedBy: 'terminal_state',\n });\n\n // --- approve\n if (terminal) out.push(isTerminalBlocked('approve'));\n else if (!isOwner) out.push(notOwner('approve'));\n else if (hasApproved) {\n out.push({\n action: 'approve',\n allowed: false,\n reason: 'You have already approved this transaction.',\n blockedBy: 'already_approved',\n });\n } else {\n out.push({ action: 'approve', allowed: true, reason: 'You can approve this transaction.' });\n }\n\n // --- revokeApproval\n if (terminal) out.push(isTerminalBlocked('revokeApproval'));\n else if (!isOwner) out.push(notOwner('revokeApproval'));\n else if (!hasApproved) {\n out.push({\n action: 'revokeApproval',\n allowed: false,\n reason: 'You have no active approval on this transaction to revoke.',\n blockedBy: 'not_approved',\n });\n } else {\n out.push({\n action: 'revokeApproval',\n allowed: true,\n reason:\n tx.approvedAt > 0\n ? 'You can revoke your approval. Note that quorum was already reached, so the ' +\n 'timelock clock keeps running and the proposer still cannot cancel.'\n : 'You can revoke your approval.',\n });\n }\n\n // --- execute\n if (terminal) out.push(isTerminalBlocked('execute'));\n else if (!isOwner) out.push(notOwner('execute'));\n else if (!quorum) {\n out.push({\n action: 'execute',\n allowed: false,\n reason: `Needs ${tx.threshold} approvals, has ${tx.approvalCount}.`,\n blockedBy: 'threshold',\n });\n } else if (timelockActive) {\n out.push({\n action: 'execute',\n allowed: false,\n reason:\n tx.approvedAt === 0\n ? 'Quorum is met but the timelock clock has not started. The next execute call will ' +\n `start it and return without executing; you must call execute again ${tx.executionDelay}s later.`\n : `Timelocked until ${new Date(executableAfter * 1000).toISOString()}.`,\n blockedBy: 'timelock',\n ...(tx.approvedAt > 0 ? { availableAt: executableAfter } : {}),\n });\n } else {\n out.push({ action: 'execute', allowed: true, reason: 'This transaction is ready to execute.' });\n }\n\n // --- approveAndExecute: approve and, if that meets quorum and the timelock allows, execute\n if (terminal) out.push(isTerminalBlocked('approveAndExecute'));\n else if (!isOwner) out.push(notOwner('approveAndExecute'));\n else if (hasApproved) {\n out.push({\n action: 'approveAndExecute',\n allowed: false,\n reason: 'You have already approved. Use execute instead.',\n blockedBy: 'already_approved',\n });\n } else {\n const wouldReachQuorum = tx.approvalCount + 1 >= tx.threshold;\n out.push({\n action: 'approveAndExecute',\n allowed: true,\n reason: !wouldReachQuorum\n ? `Your approval will be recorded, but execution needs ${tx.threshold} approvals ` +\n `(would be ${tx.approvalCount + 1}). The call returns without executing.`\n : timelockActive\n ? 'Your approval will be recorded and will start the timelock, but the call returns ' +\n 'without executing. Execute again after the delay elapses.'\n : 'Your approval meets the threshold and the transaction will execute in the same call.',\n });\n }\n\n // --- cancel (proposer-only, and permanently locked once quorum is ever reached)\n if (terminal) out.push(isTerminalBlocked('cancel'));\n else if (!isOwner) out.push(notOwner('cancel'));\n else if (!isProposer) {\n out.push({\n action: 'cancel',\n allowed: false,\n reason: 'Only the proposer can cancel directly. Others need a cancelByConsensus proposal.',\n blockedBy: 'not_proposer',\n });\n } else if (tx.approvedAt !== 0) {\n out.push({\n action: 'cancel',\n allowed: false,\n reason:\n 'This transaction reached quorum, which permanently blocks proposer-cancel — even though ' +\n 'approvals may since have been revoked. Use a cancelByConsensus proposal instead.',\n blockedBy: 'quorum_locked',\n });\n } else {\n out.push({ action: 'cancel', allowed: true, reason: 'You proposed this and can cancel it.' });\n }\n\n // --- expire (permissionless once past the deadline)\n if (tx.status === 'executed' || tx.status === 'failed' || tx.status === 'cancelled') {\n out.push(isTerminalBlocked('expire'));\n } else if (tx.expiration === 0) {\n out.push({\n action: 'expire',\n allowed: false,\n reason: 'This transaction has no expiration and can never be expired.',\n blockedBy: 'no_expiration',\n });\n } else if (at <= tx.expiration) {\n out.push({\n action: 'expire',\n allowed: false,\n reason: `Not expired yet. Expires at ${new Date(tx.expiration * 1000).toISOString()}.`,\n blockedBy: 'expired',\n availableAt: tx.expiration + 1,\n });\n } else {\n out.push({\n action: 'expire',\n allowed: true,\n reason: 'Past its expiration — anyone may close it out and reclaim approval storage.',\n });\n }\n\n // --- proposeCancelByConsensus: the post-quorum cancellation path\n if (terminal) out.push(isTerminalBlocked('proposeCancelByConsensus'));\n else if (!isOwner) out.push(notOwner('proposeCancelByConsensus'));\n else {\n out.push({\n action: 'proposeCancelByConsensus',\n allowed: true,\n reason:\n 'You can propose a cancelByConsensus self-call. It needs the same threshold as executing ' +\n 'the original transaction, but self-calls bypass the timelock, so it always resolves faster.',\n });\n }\n\n return out;\n}\n\n/** The subset of actions currently allowed. */\nexport function allowedActions(affordances: Affordance[]): Affordance[] {\n return affordances.filter((a) => a.allowed);\n}\n","import { Interface } from 'quais';\nimport { QuaiVaultAbi } from '../abi/index.js';\nimport { decodeRevert } from '../errors/decode.js';\nimport type { Bytes32, ExecuteResult, Hex } from '../types.js';\n\nconst vaultInterface = new Interface(QuaiVaultAbi);\n\nexport interface ReceiptLike {\n hash?: string;\n transactionHash?: string;\n blockNumber?: number | bigint | null;\n gasUsed?: bigint | number | null;\n status?: number | null;\n logs: ReadonlyArray<{ topics: ReadonlyArray<string>; data: string; address?: string }>;\n}\n\ninterface ParsedEvent {\n name: string;\n args: Record<string, unknown>;\n}\n\n/** Parse only the logs emitted by the vault itself; ignore everything else. */\nfunction parseVaultEvents(receipt: ReceiptLike, vault: string): ParsedEvent[] {\n const out: ParsedEvent[] = [];\n const target = vault.toLowerCase();\n\n for (const log of receipt.logs ?? []) {\n if (log.address && log.address.toLowerCase() !== target) continue;\n try {\n const parsed = vaultInterface.parseLog({\n topics: Array.from(log.topics),\n data: log.data,\n });\n if (!parsed) continue;\n const args: Record<string, unknown> = {};\n parsed.fragment.inputs.forEach((input, i) => {\n if (input.name) args[input.name] = parsed.args[i];\n });\n out.push({ name: parsed.name, args });\n } catch {\n // Not a vault event (token transfers from the executed call, etc.)\n }\n }\n return out;\n}\n\nfunction eventFor(events: ParsedEvent[], name: string, txHash: Bytes32): ParsedEvent | undefined {\n const wanted = txHash.toLowerCase();\n return events.find(\n (e) => e.name === name && String(e.args.txHash ?? '').toLowerCase() === wanted,\n );\n}\n\nfunction toNumber(value: unknown): number {\n if (typeof value === 'bigint') return Number(value);\n if (typeof value === 'number') return value;\n return Number(value ?? 0);\n}\n\n/**\n * Classify what actually happened to a vault transaction, from the receipt of the\n * Quai transaction that carried `execute` / `approveAndExecute`.\n *\n * This exists because `receipt.status === 1` does NOT mean the vault transaction ran.\n * Three cases produce a successful receipt with no execution:\n *\n * 1. **Lazy timelock clock** — `executeTransaction` on a timelocked transaction whose\n * `approvedAt` was never set (e.g. the threshold was lowered after owners approved)\n * sets `approvedAt`, emits `ThresholdReached`, and returns without executing. It\n * deliberately does not revert, because a revert would roll back the clock start.\n * 2. **`approveAndExecute` returned false** — the threshold is unmet, or the timelock\n * has not elapsed. A boolean return value is invisible in a receipt.\n * 3. **External call failure (Option B)** — the vault marks the transaction `executed`\n * permanently and emits `TransactionFailed` instead of reverting. The vault\n * transaction is dead; the receipt says success.\n */\nexport function classifyExecution(\n receipt: ReceiptLike,\n vault: string,\n txHash: Bytes32,\n): ExecuteResult {\n const chainTxHash = (receipt.hash ?? receipt.transactionHash ?? '') as Hex;\n const base = {\n txHash,\n chainTxHash,\n blockNumber: toNumber(receipt.blockNumber),\n gasUsed: BigInt(receipt.gasUsed ?? 0),\n };\n\n const events = parseVaultEvents(receipt, vault);\n\n const executed = eventFor(events, 'TransactionExecuted', txHash);\n if (executed) {\n return {\n ...base,\n outcome: 'executed',\n message: 'Transaction executed successfully.',\n };\n }\n\n const failed = eventFor(events, 'TransactionFailed', txHash);\n if (failed) {\n const returnData = String(failed.args.returnData ?? '0x') as Hex;\n const decodedRevert = decodeRevert(returnData);\n return {\n ...base,\n outcome: 'failed',\n returnData,\n decodedRevert,\n message:\n `The vault executed the transaction but the target call reverted` +\n (decodedRevert ? `: ${decodedRevert.message}` : '.') +\n ' This state is terminal — the transaction is permanently marked executed and cannot be retried.' +\n ' Propose a new transaction to try again.',\n };\n }\n\n // Threshold was reached during this call but nothing executed → the lazy clock\n // started. The caller must come back after the delay.\n const thresholdReached = eventFor(events, 'ThresholdReached', txHash);\n if (thresholdReached) {\n const executableAfter = toNumber(thresholdReached.args.executableAfter);\n // A zero delay reaching threshold without executing means approveAndExecute\n // recorded the final approval but the caller used the approve-only path.\n if (executableAfter > Math.floor(Date.now() / 1000)) {\n return {\n ...base,\n outcome: 'timelock_started',\n executableAfter,\n message:\n `Quorum was reached and the execution delay started. Nothing has executed yet. ` +\n `Call execute again after ${new Date(executableAfter * 1000).toISOString()}.`,\n };\n }\n return {\n ...base,\n outcome: 'approved_only',\n executableAfter,\n message:\n 'Quorum was reached but the transaction did not execute in this call. Call execute again.',\n };\n }\n\n const approved = eventFor(events, 'TransactionApproved', txHash);\n return {\n ...base,\n outcome: 'approved_only',\n message: approved\n ? 'Your approval was recorded, but the transaction did not execute — the threshold is not yet met.'\n : 'The transaction did not execute. It may be timelocked, or already approved by this owner ' +\n 'without the threshold being met.',\n };\n}\n\n/**\n * Pull the vault-transaction hash out of a `proposeTransaction` receipt.\n * The `TransactionProposed` event is the only reliable source — `proposeTransaction`\n * returns the hash, but return values are not available from a receipt.\n */\nexport function extractProposedTxHash(receipt: ReceiptLike, vault: string): Bytes32 | null {\n const events = parseVaultEvents(receipt, vault);\n const proposed = events.find((e) => e.name === 'TransactionProposed');\n const hash = proposed?.args.txHash;\n return typeof hash === 'string' ? hash : null;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA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AAAA,EACtD;AAAA,EAEQ,eAAe,WAAmC;AACxD,QAAI,CAAC,KAAK,QAAS,OAAM,IAAI,eAAe,SAAS;AACrD,WAAO,KAAK;AAAA,EACd;AAAA;AAAA,EAGA,MAAM,gBAAwC;AAC5C,QAAI,CAAC,KAAK,SAAS;AACjB,aAAO;AAAA,QACL,WAAW;AAAA,QACX,kBAAkB;AAAA,QAClB,WAAW;AAAA,QACX,OAAO;AAAA,MACT;AAAA,IACF;AACA,WAAO,KAAK,QAAQ,OAAO;AAAA,EAC7B;AACF;AAiBO,SAAS,QAAQ,UAAyB,CAAC,GAAoB;AACpE,SAAO,IAAI,gBAAgB,OAAO;AACpC;AAGO,IAAM,YAAY,EAAE,QAAQ;","names":["import_quais","address","import_quais","import_quais","import_quais","address","module","import_quais","import_quais","Operation","module","import_quais","import_quais","address","address","vault","address","address","vault","import_quais","import_quais","vault","address","import_quais","vault","address","token","balance","import_quais","vault","address","import_quais","address","vault","erc20","erc1155","erc721","terminalReason","import_quais","vaultInterface","vault","toNumber","address","vault","module","multiSend","address"]}
|