{"version":3,"sources":["../src/headless-client.ts","../src/smart-session-signatures.ts","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/api/accounts.js","../../../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/src/cryptoNode.ts","../../../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/src/utils.ts","../../../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/src/_md.ts","../../../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/src/_u64.ts","../../../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/src/sha2.ts","../../../node_modules/.pnpm/@noble+curves@1.9.7/node_modules/@noble/curves/src/utils.ts","../../../node_modules/.pnpm/@noble+curves@1.9.7/node_modules/@noble/curves/src/abstract/modular.ts","../../../node_modules/.pnpm/@noble+curves@1.9.7/node_modules/@noble/curves/src/abstract/curve.ts","../../../node_modules/.pnpm/@noble+curves@1.9.7/node_modules/@noble/curves/src/abstract/edwards.ts","../../../node_modules/.pnpm/@noble+curves@1.9.7/node_modules/@noble/curves/src/ed25519.ts","../../../node_modules/.pnpm/@scure+base@1.2.6/node_modules/@scure/base/index.ts","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/accounts/solana/address.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/chains/non-evm.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/config/legacy.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/modules/validators/signer-id.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/modules/validators/definition.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/modules/validators/ownable.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/modules/validators/social-recovery.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/config/defaults.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/config/resolve.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/accounts/error.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/config/validate.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/errors/capability.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/transactions/intents/solana.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/chains/caip2.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/clients/orchestrator/serialization.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/clients/orchestrator/normalized.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/errors/execution.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/signing/signers/ecdsa.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/signing/signers/wallet-chain.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/transactions/intents/account.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/transactions/intents/compatibility.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/clients/orchestrator/errors.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/transactions/intents/normalize.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/chains/tokens.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/transactions/intents/source.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/transactions/intents/request.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/transactions/intents/solana-instructions.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/api/account.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/chains/catalog.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/accounts/construction.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/modules/plan.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/modules/intent-executor.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/modules/normalize.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/modules/validators/smart-sessions/module.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/modules/validators/ens.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/modules/validators/ordering.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/modules/validators/multi-factor.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/modules/validators/quorum.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/modules/validators/webauthn.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/modules/validators/resolve.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/accounts/passkey-install.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/accounts/deployment.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/accounts/adapters/eoa.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/accounts/adapters/hca.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/accounts/erc7579-calls.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/accounts/adapters/shared.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/modules/erc7579-abi.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/accounts/adapters/kernel.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/accounts/adapters/nexus.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/accounts/adapters/safe.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/modules/legacy-core.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/accounts/adapters/startale.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/modules/validators/k1.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/accounts/registry.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/config/account-runtime.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/hypercore/errors.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/hypercore/market.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/hypercore/orders.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/hypercore/resolve.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/transactions/intents/prepare.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/calls/resolve.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/signing/error.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/signing/plan.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/transactions/intents/origin-chain.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/transactions/intents/quotes.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/modules/validators/smart-sessions/mock-signature.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/modules/validators/smart-sessions/signature.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/modules/validators/smart-sessions/digest.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/modules/validators/policies/claim/permit2.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/modules/validators/policies/claim/types.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/modules/validators/smart-sessions/policies/claim.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/modules/validators/permissions.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/modules/validators/policies/claim/arbiters.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/modules/validators/smart-sessions/fast-lz.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/modules/validators/smart-sessions/resolve.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/modules/validators/smart-sessions/cross-chain-permits.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/modules/validators/smart-sessions/policies/addresses.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/modules/validators/smart-sessions/policies/encode.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/modules/validators/smart-sessions/signing.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/modules/validators/smart-sessions/erc7739.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/modules/validators/smart-sessions/swap/fynd.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/modules/validators/smart-sessions/swap/rules.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/modules/validators/smart-sessions/swap/rhinestone.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/modules/validators/smart-sessions/swap/zero-ex.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/modules/validators/smart-sessions/swap/scope.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/transactions/intents/sessions.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/api/project-mappers.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/api/signer-selection.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/api/compose.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/clients/bundler/client.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/clients/json-rpc.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/clients/rpc/transport.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/clients/rpc/providers.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/clients/bundler/endpoints.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/clients/orchestrator/auth.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/clients/orchestrator/chain-catalog.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/clients/orchestrator/fetch.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/clients/orchestrator/mappers.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/clients/orchestrator/sponsorship-approval.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/clients/orchestrator/client.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/clients/paymaster/client.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/clients/paymaster/endpoints.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/clients/rpc/client.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/modules/read-core.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/modules/validators/smart-sessions/authorization.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/modules/validators/smart-sessions/state.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/signing/context.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/modules/validators/capabilities.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/signing/eip7702.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/signing/execute.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/signing/session-enable.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/signing/typed-data.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/modules/validators/contribution.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/signing/contribution.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/accounts/kernel-signing.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/signing/hash.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/signing/protocols/erc6492.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/signing/protocols/erc7739.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/signing/signers/webauthn.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/signing/signers/registry.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/transactions/intents/proofs.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/signing/intent-plans/assemble.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/signing/intent-plans/independent.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/signing/intent-plans/types.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/signing/intent-plans/plan.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/transactions/intents/session-signing.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/transactions/intents/sign-transaction.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/transactions/intents/submit.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/transactions/intents/send.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/transactions/intents/solana-deployment.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/transactions/intents/split.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/transactions/intents/status-policy.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/transactions/intents/status.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/transactions/user-operations/hash.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/transactions/user-operations/nonce.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/transactions/user-operations/validator-account.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/transactions/user-operations/prepare.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/transactions/user-operations/reconstruct.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/signing/user-operation.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/transactions/user-operations/sign.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/transactions/user-operations/submit.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/transactions/user-operations/send.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/transactions/user-operations/status.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/api/direct-signing.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/signing/message.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/api/queries/app-fees.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/api/queries/portfolio.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/api/queries/session.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/api/sdk.js","../../../node_modules/.pnpm/@rhinestone+sdk@0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787_jose@_d0d86b8baebaa36d5551f4416237856c/node_modules/@rhinestone/sdk/dist/src/smart-sessions/index.js"],"sourcesContent":["/**\n * Headless 1auth client.\n *\n * Used by integrators that hold their own ECDSA signer in localStorage\n * and produce signatures for an ERC-7579 validator other than the\n * passkey one (typically `@rhinestone/sdk` experimental SmartSession).\n *\n * Responsibilities:\n *  - Fetch sponsorship JWTs from the app's own backend.\n *  - Call `/api/intent/batch-prepare` with `signingMode: \"headless\"` and one\n *    intent to get an orchestrator-quoted `intentOp` + `digestResult`.\n *  - Forward pre-encoded validator-prefixed signatures to the new\n *    `/api/intent/headless-execute` route.\n *  - Drive the existing passkey dialog (via {@link WalletClient}) for\n *    the one-time SmartSession install ceremony.\n *\n * 1auth itself stays ignorant of session keys — the on-chain\n * SmartSession validator is the only authority over what a session key\n * may sign for. The host app persists `{ sessionKeyAddress, permissionId,\n * accountAddress, permissions }` in its own storage.\n */\n\nimport {\n  APP_ORIGIN_WIRE_MODE,\n  assertSponsorshipMode,\n  assertWebAuthnConfig,\n  type AppFeeRate,\n  type HeadlessIntentOptions,\n  type HeadlessIntentStatusResult,\n  type HeadlessPrepareResult,\n  type HeadlessSubmitOptions,\n  type HeadlessSubmitResult,\n  type IntentQuote,\n  type WalletClientConfig,\n} from \"./types\";\nimport type { Address } from \"viem\";\nimport { resolveAppFees } from \"./app-fees\";\nimport {\n  serializeIntentCalls,\n  serializeIntentTokenRequests,\n} from \"./intent-serialization\";\nimport { createSponsorshipFetcher, type SponsorshipFetcher } from \"./sponsorship-fetch\";\n\nconst DEFAULT_PROVIDER_URL = \"https://passkey.1auth.app\";\n\nconst MISSING_APP_CREDENTIALS_MESSAGE =\n  \"No sponsorship configured on WalletHeadlessClient. Every user intent must carry the app's JWT — pass `sponsorship: { accessTokenUrl, extensionTokenUrl }` to the constructor.\";\n\ntype AccessTokenFetchResult =\n  | { ok: true; accessToken: string }\n  | { ok: false; code?: \"MISSING_APP_CREDENTIALS\"; message: string };\n\ntype ExtensionTokenFetchResult =\n  | { ok: true; extensionToken: string | undefined }\n  | { ok: false; message: string };\n\n/** The batch-prepare response fields a headless batch of one reads. */\ntype BatchPrepareBody = {\n  error?: string;\n  failedIntents?: Array<{ error?: string }>;\n  sponsorshipIntentInputs?: Record<string, unknown>;\n  challenge?: `0x${string}`;\n  binding?: string;\n  accountAddress?: Address;\n  intents?: Array<{\n    intentOp: string;\n    digestResult: string;\n    originMessages: Array<{ chainId: number; hash: `0x${string}` }>;\n    destinationMessageHash?: `0x${string}`;\n    targetExecutionMessageHash?: `0x${string}`;\n    targetChain: number;\n    calls: string;\n    expiresAt: string;\n    quote?: IntentQuote;\n  }>;\n};\n\n/** Return the tuple-isolated app-origin bearer key shared with WalletClient. */\nfunction appOriginSessionStorageKey(\n  providerUrl: string,\n  clientId?: string,\n  rpId?: string,\n): string | null {\n  if (typeof window === \"undefined\") return null;\n  const origin = window.location?.origin;\n  if (!origin) return null;\n  const namespace = rpId ? `${rpId}:` : \"\";\n  return `1auth-app-origin:${new URL(providerUrl).origin}:${clientId ?? \"anonymous\"}:${namespace}${origin}`;\n}\n\nexport class WalletHeadlessClient {\n  private providerUrl: string;\n  private clientId?: string;\n  private sponsorship: SponsorshipFetcher | null;\n  private rpId?: string;\n  private appFees?: AppFeeRate;\n\n\n  constructor(config: WalletClientConfig) {\n    assertWebAuthnConfig(config);\n    this.providerUrl = config.providerUrl || DEFAULT_PROVIDER_URL;\n    this.clientId = config.clientId;\n    this.rpId = config.webauthn?.rpId?.trim().toLowerCase();\n    this.sponsorship = config.sponsorship ? createSponsorshipFetcher(config.sponsorship) : null;\n    this.appFees = config.appFees;\n  }\n\n  /** Read the current app-origin bearer without exposing it to callers. */\n  private readAppOriginSessionToken(): string | null {\n    const key = appOriginSessionStorageKey(this.providerUrl, this.clientId, this.rpId);\n    if (!key || typeof window === \"undefined\") return null;\n    try {\n      return window.localStorage.getItem(key);\n    } catch {\n      return null;\n    }\n  }\n\n  /** The stored app-origin bearer with its namespace headers, or nothing without a session. */\n  private appOriginBearerHeaders(): Record<string, string> {\n    const sessionToken = this.readAppOriginSessionToken();\n    if (!sessionToken) return {};\n    return {\n      Authorization: `Bearer ${sessionToken}`,\n      ...(this.rpId ? { \"X-1Auth-RP-ID\": this.rpId } : {}),\n      ...(this.rpId && this.clientId ? { \"X-1Auth-Client-ID\": this.clientId } : {}),\n    };\n  }\n\n  /** Add app-origin identity binding to a headless passkey-service request. */\n  private appOriginRequest(): { body: Record<string, string>; headers: Record<string, string> } {\n    const headers = this.appOriginBearerHeaders();\n    if (!headers.Authorization) throw new Error(\"An app-origin session is required\");\n    return {\n      body: {\n        webauthnMode: APP_ORIGIN_WIRE_MODE,\n        ...(this.clientId ? { clientId: this.clientId } : {}),\n      },\n      headers,\n    };\n  }\n\n  // ---------------------------------------------------------------------------\n  // Sponsorship JWT fetchers\n  // ---------------------------------------------------------------------------\n\n  private async fetchAccessToken(): Promise<AccessTokenFetchResult> {\n    if (!this.sponsorship) {\n      return {\n        ok: false,\n        code: \"MISSING_APP_CREDENTIALS\",\n        message: MISSING_APP_CREDENTIALS_MESSAGE,\n      };\n    }\n    try {\n      const accessToken = await this.sponsorship.accessToken();\n      return { ok: true, accessToken };\n    } catch (err) {\n      return {\n        ok: false,\n        message: err instanceof Error ? err.message : String(err),\n      };\n    }\n  }\n\n  /** Mint one digest-bound extension grant from a canonical intent input. */\n  private async fetchExtensionToken(intentInput: string): Promise<ExtensionTokenFetchResult> {\n    if (!this.sponsorship) {\n      return { ok: false, message: MISSING_APP_CREDENTIALS_MESSAGE };\n    }\n    try {\n      const token = await this.sponsorship.getExtensionToken(intentInput);\n      return { ok: true, extensionToken: token };\n    } catch (err) {\n      return {\n        ok: false,\n        message: err instanceof Error ? err.message : String(err),\n      };\n    }\n  }\n\n  // ---------------------------------------------------------------------------\n  // Intent prepare / submit\n  // ---------------------------------------------------------------------------\n\n  /**\n   * Quote an intent without opening any dialog. Returns the orchestrator's\n   * `intentOp` plus the digest the caller must sign with their own\n   * validator (e.g. SmartSession). The caller is responsible for\n   * encoding signatures and submitting via {@link submitIntent}.\n   */\n  async prepareIntent(options: HeadlessIntentOptions): Promise<HeadlessPrepareResult> {\n    if (!options.accountAddress) {\n      throw new Error(\"prepareIntent requires `accountAddress`\");\n    }\n\n    // Validate the app-origin namespace before sponsorship callbacks can make\n    // any network request. A missing bearer must fail locally and reveal no\n    // intent to the app's access-token endpoint.\n    const appOriginRequest = this.appOriginRequest();\n    const appFees = resolveAppFees(options.appFees, this.appFees);\n    assertSponsorshipMode(options.sponsorshipMode);\n\n    const accessTokenResult = await this.fetchAccessToken();\n    if (!accessTokenResult.ok) {\n      throw new Error(`Sponsorship access token fetch failed: ${accessTokenResult.message}`);\n    }\n\n    const body = {\n      accountAddress: options.accountAddress,\n      intents: [{\n        targetChain: options.targetChain,\n        calls: serializeIntentCalls(options.calls),\n        tokenRequests: serializeIntentTokenRequests(options.tokenRequests),\n        sourceAssets: options.sourceAssets,\n        sourceChainId: options.sourceChainId,\n        ...(appFees && { appFees }),\n      }],\n      sessionKeyHandle: options.sessionKeyHandle,\n      clientId: this.clientId,\n      signingMode: \"headless\" as const,\n      auth: { accessToken: accessTokenResult.accessToken },\n      ...appOriginRequest.body,\n    };\n    const requestPrepare = async (requestBody: Record<string, unknown>): Promise<BatchPrepareBody> => {\n      const response = await fetch(`${this.providerUrl}/api/intent/batch-prepare`, {\n        method: \"POST\",\n        headers: { \"Content-Type\": \"application/json\", ...appOriginRequest.headers },\n        body: JSON.stringify(requestBody),\n      });\n      const data = (await response.json().catch(() => ({}))) as BatchPrepareBody;\n      const failure = data.failedIntents?.[0]?.error;\n      if (!response.ok || failure) {\n        throw new Error(failure || data.error || `Prepare failed (${response.status})`);\n      }\n      return data;\n    };\n\n    const finalPrepare = async (\n      fundingMode: \"required\" | \"self-funded\",\n      extensionToken?: string,\n    ): Promise<HeadlessPrepareResult> => {\n      const prepared = await requestPrepare({\n        ...body,\n        quoteMode: \"final\",\n        fundingModes: [fundingMode],\n        ...(extensionToken && { quoteExtensionTokens: { \"0\": extensionToken } }),\n      });\n      const [intent] = prepared.intents ?? [];\n      if (!intent || !prepared.challenge || !prepared.binding) {\n        throw new Error(\"Prepare response missing the prepared intent\");\n      }\n      return {\n        intentOp: intent.intentOp,\n        digestResult: intent.digestResult,\n        originMessages: intent.originMessages.map((message) => ({\n          chainId: message.chainId,\n          messageHash: message.hash,\n          hash: message.hash,\n        })),\n        destinationMessageHash: intent.destinationMessageHash,\n        targetExecutionMessageHash: intent.targetExecutionMessageHash,\n        challenge: prepared.challenge,\n        targetChain: intent.targetChain,\n        calls: intent.calls,\n        expiresAt: intent.expiresAt,\n        accountAddress: prepared.accountAddress ?? options.accountAddress,\n        binding: prepared.binding,\n        quote: intent.quote,\n        sponsorshipMode: fundingMode === \"required\" ? \"sponsored\" : \"self-funded\",\n      };\n    };\n\n    if (options.sponsorshipMode === \"disabled\") return finalPrepare(\"self-funded\");\n\n    const draft = await requestPrepare({\n      ...body,\n      quoteMode: \"draft\",\n      fundingModes: [\"required\"],\n    });\n    const sponsorshipIntentInput = draft.sponsorshipIntentInputs?.[\"0\"];\n    if (sponsorshipIntentInput === undefined) {\n      throw new Error(\"Prepare response missing sponsorship intent input\");\n    }\n    const extensionResult = await this.fetchExtensionToken(\n      JSON.stringify(sponsorshipIntentInput),\n    );\n    if (!extensionResult.ok || !extensionResult.extensionToken) {\n      throw new Error(extensionResult.ok ? \"Extension token missing\" : extensionResult.message);\n    }\n    return finalPrepare(\"required\", extensionResult.extensionToken);\n  }\n\n  /** Forward a pre-signed intent; the quote grant was consumed during prepare. */\n  async submitIntent(options: HeadlessSubmitOptions): Promise<HeadlessSubmitResult> {\n    const accessTokenResult = await this.fetchAccessToken();\n    if (!accessTokenResult.ok) {\n      throw new Error(`Sponsorship access token fetch failed: ${accessTokenResult.message}`);\n    }\n    const body = {\n      intentOp: options.intentOp,\n      digestResult: options.digestResult,\n      binding: options.binding,\n      accountAddress: options.accountAddress,\n      targetChain: options.targetChain,\n      calls: options.calls,\n      expiresAt: options.expiresAt,\n      originSignatures: options.originSignatures,\n      destinationSignature: options.destinationSignature,\n      targetExecutionSignature: options.targetExecutionSignature,\n      auth: { accessToken: accessTokenResult.accessToken },\n    };\n\n    const response = await fetch(`${this.providerUrl}/api/intent/headless-execute`, {\n      method: \"POST\",\n      headers: { \"Content-Type\": \"application/json\" },\n      body: JSON.stringify(body),\n    });\n\n    if (!response.ok) {\n      const errorData = (await response.json().catch(() => ({}))) as { error?: string };\n      throw new Error(errorData.error || `Headless execute failed (${response.status})`);\n    }\n\n    return (await response.json()) as HeadlessSubmitResult;\n  }\n\n  // ---------------------------------------------------------------------------\n  // Status / wait — proxies to the existing routes (no headless variant needed).\n  // ---------------------------------------------------------------------------\n\n  /**\n   * Fetch the latest known status for a submitted headless intent.\n   * This is a non-blocking read and may return `pending` before a\n   * solver has produced a fill transaction hash.\n   */\n  async getIntentStatus(intentId: string): Promise<HeadlessIntentStatusResult> {\n    const response = await fetch(`${this.providerUrl}/api/intent/status/${intentId}`, {\n      headers: this.appOriginBearerHeaders(),\n    });\n    if (!response.ok) {\n      throw new Error(`Status fetch failed (${response.status})`);\n    }\n    return (await response.json()) as HeadlessIntentStatusResult;\n  }\n\n  /**\n   * Wait for a submitted headless intent to produce a status update and,\n   * when available, the final fill transaction hash. The wait endpoint\n   * needs the opaque `transactionResult` returned by submit because 1auth\n   * does not persist that SDK object in its database.\n   */\n  async waitForIntent(\n    intentId: string,\n    transactionResult: unknown,\n  ): Promise<HeadlessIntentStatusResult> {\n    if (!transactionResult) {\n      throw new Error(\"waitForIntent requires submitResult.transactionResult\");\n    }\n\n    const response = await fetch(`${this.providerUrl}/api/intent/wait/${intentId}`, {\n      method: \"POST\",\n      headers: { \"Content-Type\": \"application/json\", ...this.appOriginBearerHeaders() },\n      body: JSON.stringify({ transactionResult }),\n    });\n    if (!response.ok) {\n      const errorData = (await response.json().catch(() => ({}))) as {\n        error?: string;\n        details?: string;\n      };\n      throw new Error(\n        errorData.details || errorData.error || `Wait fetch failed (${response.status})`,\n      );\n    }\n    return (await response.json()) as HeadlessIntentStatusResult;\n  }\n}\n","import { type Address, type Abi, type Chain, type Hex } from \"viem\";\nimport { privateKeyToAccount } from \"viem/accounts\";\nimport {\n  RhinestoneSDK,\n  type Permission,\n  type PreparedTransactionData,\n  type Session,\n  type SigningRequest,\n  type SigningProof,\n  type SignerSet,\n} from \"@rhinestone/sdk\";\nimport { toCrossChainPermissionInput, toSession } from \"@rhinestone/sdk/smart-sessions\";\nimport { getChainById } from \"./registry\";\nimport type { HeadlessPrepareResult, SessionKeyHandle } from \"./types\";\n\n/** Restores bigint sentinel strings emitted by 1auth's JSON transport. */\nfunction reviveBigIntStrings<T>(value: T): T {\n  if (Array.isArray(value)) return value.map((entry) => reviveBigIntStrings(entry)) as T;\n  if (value && typeof value === \"object\") {\n    return Object.fromEntries(\n      Object.entries(value).map(([key, entry]) => [key, reviveBigIntStrings(entry)]),\n    ) as T;\n  }\n  if (typeof value === \"string\" && value.startsWith(\"__bigint:\")) {\n    return BigInt(value.slice(\"__bigint:\".length)) as T;\n  }\n  if (typeof value === \"string\" && /^\\d+$/.test(value)) return BigInt(value) as T;\n  return value;\n}\n\n/** Parses the complete prepared transaction and restores bigint wire values. */\nfunction parsePreparedTransaction(value: string): PreparedTransactionData {\n  const envelope: unknown = JSON.parse(value, (_key, nested) =>\n    typeof nested === \"string\" && nested.startsWith(\"__bigint:\")\n      ? BigInt(nested.slice(\"__bigint:\".length))\n      : nested,\n  );\n  if (!envelope || typeof envelope !== \"object\" || !(\"v3\" in envelope)) {\n    throw new Error(\"Prepared headless intent is missing its v3 artifact; prepare the intent again\");\n  }\n  const artifact = envelope.v3;\n  if (!artifact || typeof artifact !== \"object\" || !(\"request\" in artifact)) {\n    throw new Error(\"Prepared headless intent has an invalid v3 artifact; prepare the intent again\");\n  }\n  return artifact as PreparedTransactionData;\n}\n\nfunction requestChainId(request: SigningRequest): number {\n  if (request.payload.kind !== \"eip712\" || request.account.vm !== \"evm\") {\n    throw new Error(`Unsupported headless signing request: ${request.purpose}/${request.payload.kind}`);\n  }\n  const chainId = chainIdFromSignDataDomain(request.payload.typedData.domain?.chainId);\n  if (chainId === undefined || !Number.isSafeInteger(chainId) || chainId <= 0) {\n    throw new Error(\"Headless signing request is missing an EVM typed-data chain id\");\n  }\n  return chainId;\n}\n\nfunction signatureFromProof(proof: SigningProof | undefined, purpose: SigningRequest[\"purpose\"]) {\n  if (!proof || proof.kind !== \"eip712\") {\n    throw new Error(`Missing EIP-712 proof for ${purpose}`);\n  }\n  return proof.signature;\n}\n\nfunction toLegacySignatures(requests: SigningRequest[], proofs: SigningProof[]) {\n  if (proofs.length !== requests.length) {\n    throw new Error(`Expected ${requests.length} headless proofs, received ${proofs.length}`);\n  }\n  const originSignatures: Array<Hex | { preClaimSig: Hex; notarizedClaimSig: Hex }> = [];\n  let destinationSignature: Hex | undefined;\n  let targetExecutionSignature: Hex | undefined;\n  requests.forEach((request, index) => {\n    requestChainId(request);\n    const signature = signatureFromProof(proofs[index], request.purpose);\n    if (request.purpose === \"originAuthorization\") {\n      originSignatures.push(typeof signature === \"string\" ? signature : {\n        preClaimSig: signature.preClaim,\n        notarizedClaimSig: signature.notarizedClaim,\n      });\n    } else if (request.purpose === \"destinationAuthorization\") {\n      if (destinationSignature || typeof signature !== \"string\") {\n        throw new Error(\"Invalid destination headless proof\");\n      }\n      destinationSignature = signature;\n    } else if (request.purpose === \"targetExecutionAuthorization\") {\n      if (targetExecutionSignature || typeof signature !== \"string\") {\n        throw new Error(\"Invalid target execution headless proof\");\n      }\n      targetExecutionSignature = signature;\n    } else {\n      throw new Error(`Unsupported headless signing purpose: ${request.purpose}`);\n    }\n  });\n  if (!destinationSignature) throw new Error(\"Missing destination headless proof\");\n  return { originSignatures, destinationSignature, targetExecutionSignature };\n}\n\n/** Reads the numeric EIP-712 chain id from a typed-data domain. */\nfunction chainIdFromSignDataDomain(domainChainId: unknown): number | undefined {\n  if (typeof domainChainId === \"number\" && Number.isSafeInteger(domainChainId)) {\n    return domainChainId;\n  }\n  if (typeof domainChainId === \"bigint\") return Number(domainChainId);\n  if (typeof domainChainId === \"string\" && /^\\d+$/.test(domainChainId)) {\n    return Number(domainChainId);\n  }\n  return undefined;\n}\n\n/**\n * Converts a persisted timestamp back to a Date. Grant handles cross JSON\n * boundaries, so SDK `Date` config fields arrive as ISO strings,\n * seconds/ms numbers, or bigint strings (already revived to bigint).\n * Values below 2286-11-20 are treated as Unix seconds, larger as ms — the\n * same tolerance the passkey server applies, so the rebuilt session hashes\n * to the same permission ID that install quoted.\n */\nfunction reviveDateValue(value: unknown): Date | undefined {\n  if (value === undefined || value === null) return undefined;\n  if (value instanceof Date) return value;\n  if (typeof value === \"string\" && !/^-?\\d+$/.test(value)) {\n    const parsed = Date.parse(value);\n    return Number.isNaN(parsed) ? undefined : new Date(parsed);\n  }\n  const numeric =\n    typeof value === \"bigint\"\n      ? Number(value)\n      : typeof value === \"number\"\n        ? value\n        : typeof value === \"string\" && /^-?\\d+$/.test(value)\n          ? Number(value)\n          : NaN;\n  if (Number.isNaN(numeric)) return undefined;\n  return new Date(numeric < 10_000_000_000 ? numeric * 1000 : numeric);\n}\n\n/**\n * Rebuilds the permission list exactly as the passkey server's `buildSession`\n * enriched it at install time: per-function timestamps converted back to\n * `Date`, and handle-level `validUntil`/`validAfter`/`maxUses` merged into\n * every function that doesn't set its own. Without this, a time-limited\n * grant rebuilds to a different session — wrong permission ID, or a throw\n * inside the SDK (`Date.getTime` on a non-Date).\n */\nfunction rebuildPermissions(handle: SessionKeyHandle, chainId: number): Permission<Abi>[] {\n  // Mirror the server's smartSessionPermissionsForChain: on source-only\n  // chains the installed session strips selector permissions and keeps only\n  // the cross-chain claim permits, so the funding-chain hash matches\n  // install/revoke. Legacy grants without recorded target chains keep the\n  // full permission set on every chain.\n  const targetChains = handle.targetChains ?? [];\n  if (targetChains.length > 0 && !targetChains.includes(chainId)) {\n    return [];\n  }\n  const defaults = {\n    validUntil: reviveDateValue(handle.validUntil),\n    validAfter: reviveDateValue(handle.validAfter),\n    maxUses: handle.maxUses !== undefined ? BigInt(handle.maxUses) : undefined,\n  };\n  return reviveBigIntStrings(handle.permissions ?? []).map((permission) => ({\n    ...permission,\n    functions: Object.fromEntries(\n      Object.entries(permission.functions ?? {}).map(([name, config]) => {\n        const cfg = (config ?? {}) as Record<string, unknown>;\n        // Per-function values win; handle-level defaults fill in gaps.\n        const merged: Record<string, unknown> = { ...cfg };\n        const validUntil = reviveDateValue(cfg.validUntil) ?? defaults.validUntil;\n        if (validUntil) merged.validUntil = validUntil;\n        const validAfter = reviveDateValue(cfg.validAfter) ?? defaults.validAfter;\n        if (validAfter) merged.validAfter = validAfter;\n        if (defaults.maxUses !== undefined && cfg.maxUses === undefined) {\n          merged.maxUses = defaults.maxUses;\n        }\n        return [name, merged];\n      }),\n    ) as Permission<Abi>[\"functions\"],\n  }));\n}\n\n/** Rebuilds the SDK SmartSession object from the persisted grant handle. */\nfunction buildSessionForChain(args: {\n  privateKey: Hex;\n  handle: SessionKeyHandle;\n  chain: Chain;\n}): Session {\n  return toSession(\n    {\n      chain: args.chain,\n      owners: { type: \"ecdsa\", accounts: [privateKeyToAccount(args.privateKey)] },\n      permissions: rebuildPermissions(args.handle, args.chain.id),\n      // Persisted handles store the resolved wire permit (bigint deadlines);\n      // toSession wants the ergonomic input, converted by the SDK.\n      crossChainPermits: reviveBigIntStrings(args.handle.crossChainPermits ?? []).map(\n        toCrossChainPermissionInput,\n      ),\n    },\n    // The production SmartSession module is deployed on testnets too. Never opt\n    // into SDK dev contracts for 1auth headless permissions.\n    { useDevContracts: false },\n  );\n}\n\n/** Builds a per-chain SmartSession signer set for the ordered requests. */\nasync function buildSessionSigners(args: {\n  privateKey: Hex;\n  handle: SessionKeyHandle;\n  prepared: HeadlessPrepareResult;\n  requests: SigningRequest[];\n}): Promise<SignerSet> {\n  const chainIds = new Set<number>([args.prepared.targetChain]);\n  for (const request of args.requests) chainIds.add(requestChainId(request));\n\n  const chains = await Promise.all([...chainIds].map((chainId) => getChainById(chainId)));\n  return {\n    type: \"session\",\n    sessions: Object.fromEntries(\n      chains.map((chain) => [\n        chain.id,\n        {\n          session: buildSessionForChain({\n            privateKey: args.privateKey,\n            handle: args.handle,\n            chain,\n          }),\n        },\n      ]),\n    ),\n  };\n}\n\nexport interface BuildSmartSessionHeadlessSignaturesOptions {\n  /** ECDSA private key for the locally-held SmartSession signer. */\n  privateKey: Hex;\n  /** Smart account address the SmartSession is scoped to. */\n  accountAddress: Address;\n  /** Persisted handle returned by `grantPermissions` / SmartSession install. */\n  sessionKeyHandle: SessionKeyHandle;\n  /** Prepared headless intent returned by `WalletHeadlessClient.prepareIntent`. */\n  prepared: HeadlessPrepareResult;\n}\n\n/**\n * Builds SmartSession signatures for `WalletHeadlessClient.submitIntent`.\n *\n * This intentionally delegates signing and SmartSession signature packing to\n * `@rhinestone/sdk`. 1auth only rebuilds the persisted session descriptor and\n * supplies the SDK-native ordered signing requests returned by the quote.\n */\nexport async function buildSmartSessionHeadlessSignatures(\n  options: BuildSmartSessionHeadlessSignaturesOptions,\n) {\n  const preparedTransaction = parsePreparedTransaction(options.prepared.intentOp);\n  const requests = preparedTransaction.quotes?.best?.signingRequests;\n  if (!requests?.length) {\n    throw new Error(\"Prepared headless intent is missing quotes.best.signingRequests\");\n  }\n  // Reject unsupported slots before account construction or RPC reads.\n  for (const request of requests) {\n    requestChainId(request);\n    if (request.purpose === \"delegationAuthorization\") {\n      throw new Error(\"Unsupported headless signing purpose: delegationAuthorization\");\n    }\n  }\n  // The SDK requires apiKey-or-auth at construction. Signing here performs only\n  // RPC session-state reads and local signatures; the placeholder key is never\n  // sent to the orchestrator.\n  const account = await new RhinestoneSDK({ apiKey: \"local-signing-only\" }).createAccount({\n    evm: {\n      initData: { address: options.accountAddress },\n      owners: {\n        type: \"ecdsa\",\n        accounts: [privateKeyToAccount(options.privateKey)],\n      },\n      sessions: { enabled: true },\n    },\n  });\n\n  const signers = await buildSessionSigners({\n    privateKey: options.privateKey,\n    handle: options.sessionKeyHandle,\n    prepared: options.prepared,\n    requests,\n  });\n  // signIntent on requests reconstructs only the destination chain,\n  // so cross-chain origin sessions disappear and signing fails with\n  // \"Prepared session for chain <source> is missing\". Re-sign the full prepared\n  // transaction instead: it retains sourceChains and resolves every per-chain\n  // session configured above.\n  const signed = await account.signTransaction({\n    ...preparedTransaction,\n    transaction: {\n      ...preparedTransaction.transaction,\n      signers,\n    } as PreparedTransactionData[\"transaction\"],\n  });\n  return toLegacySignatures(requests, signed.proofs);\n}\n","import { isAddress } from 'viem';\nimport { locateSwigWallet } from '../accounts/solana/address.js';\nimport { solanaAddress } from '../chains/non-evm.js';\nimport { captureLegacySdkConfig, createLegacyAccountConfig, } from '../config/legacy.js';\nimport { materializeAccountInvocationContext, resolveSdkConfig, } from '../config/resolve.js';\nimport { assertAccountOwnersConfigured } from '../config/validate.js';\nimport { AccountVmNotConfiguredError, InvalidAccountConfigError, ManagedSolanaAccountNotSupportedError, } from '../errors/capability.js';\nimport { compressP256PublicKey } from '../transactions/intents/solana.js';\nimport { createAccountFacade, createSolanaAccountFacade, isManagedSolanaEndpoint, } from './account.js';\nimport { createConfiguredCoreComposition } from './compose.js';\nexport function composeSdk(input) {\n    const resolved = resolveSdkConfig(input);\n    return {\n        composition: createConfiguredCoreComposition(resolved),\n        snapshot: captureLegacySdkConfig(input, resolved.auth),\n    };\n}\nconst ACCOUNT_KEYS = ['evm', 'solana'];\nconst EVM_KEYS = [\n    'account',\n    'owners',\n    'sessions',\n    'recovery',\n    'eoa',\n    'modules',\n    'initData',\n];\nfunction record(value, label) {\n    if (!value || typeof value !== 'object' || Array.isArray(value)) {\n        throw new InvalidAccountConfigError(`${label} must be an object`);\n    }\n    return value;\n}\nfunction exactKeys(value, allowed, label) {\n    const unknown = Object.keys(value).find((key) => !allowed.includes(key));\n    if (unknown) {\n        throw new InvalidAccountConfigError(`unknown ${label} field \\`${unknown}\\``);\n    }\n}\nfunction isEcdsaAccount(value) {\n    return (!!value &&\n        typeof value === 'object' &&\n        typeof value.address === 'string' &&\n        isAddress(value.address));\n}\nfunction isPasskeyAccount(value) {\n    if (!value || typeof value !== 'object')\n        return false;\n    const account = value;\n    if (account.type !== 'webAuthn' ||\n        typeof account.id !== 'string' ||\n        account.id.length === 0 ||\n        typeof account.sign !== 'function' ||\n        typeof account.publicKey !== 'string') {\n        return false;\n    }\n    try {\n        compressP256PublicKey(account.publicKey);\n        return true;\n    }\n    catch {\n        return false;\n    }\n}\nfunction parseSwig(value) {\n    try {\n        const swigAccount = solanaAddress(value);\n        return {\n            address: locateSwigWallet(swigAccount).address,\n            swigAccount,\n        };\n    }\n    catch {\n        throw new InvalidAccountConfigError('`solana.swig` must be a valid Solana Swig state account address');\n    }\n}\nexport function attachAccount(sdk, config) {\n    const input = record(config, 'account configuration');\n    exactKeys(input, ACCOUNT_KEYS, 'account');\n    if ((!Object.hasOwn(input, 'evm') && !Object.hasOwn(input, 'solana')) ||\n        (input.evm === undefined && input.solana === undefined)) {\n        throw new InvalidAccountConfigError('at least one VM must be configured');\n    }\n    let evmReceiver;\n    let managedEvm;\n    let managedSolanaOwner;\n    let managedSolanaSwig;\n    let solanaReceiver;\n    if (input.evm !== undefined) {\n        const evm = record(input.evm, 'EVM configuration');\n        if (Object.hasOwn(evm, 'address')) {\n            exactKeys(evm, ['address'], 'EVM receiver');\n            if (typeof evm.address !== 'string' || !isAddress(evm.address)) {\n                throw new InvalidAccountConfigError('EVM receiver address is invalid');\n            }\n            evmReceiver = evm.address;\n        }\n        else {\n            exactKeys(evm, EVM_KEYS, 'managed EVM');\n            managedEvm = input.evm;\n        }\n    }\n    if (input.solana !== undefined) {\n        const solana = record(input.solana, 'Solana configuration');\n        if (Object.hasOwn(solana, 'address')) {\n            exactKeys(solana, ['address'], 'Solana receiver');\n            if (typeof solana.address !== 'string') {\n                throw new InvalidAccountConfigError('Solana receiver address is invalid');\n            }\n            try {\n                solanaReceiver = solanaAddress(solana.address);\n            }\n            catch {\n                throw new InvalidAccountConfigError('Solana receiver address is invalid');\n            }\n        }\n        else {\n            exactKeys(solana, ['owner', 'swig'], 'managed Solana');\n            const owner = record(solana.owner, 'managed Solana owner');\n            exactKeys(owner, ['type', 'account'], 'managed Solana owner');\n            if (owner.type === 'ecdsa' && isEcdsaAccount(owner.account)) {\n                managedSolanaOwner = owner;\n            }\n            else if (owner.type === 'passkey' && isPasskeyAccount(owner.account)) {\n                managedSolanaOwner = owner;\n            }\n            else {\n                throw new ManagedSolanaAccountNotSupportedError(\"Managed Solana requires `{ owner: { type: 'ecdsa', account } }` with a valid viem ECDSA account, or `{ owner: { type: 'passkey', account } }` with a viem WebAuthn account holding a P-256 public key.\");\n            }\n            if (solana.swig === undefined) {\n                throw new InvalidAccountConfigError('Managed Solana requires `swig` with the existing provisioned Swig state account address; the SDK no longer derives it from an EVM account.');\n            }\n            managedSolanaSwig = parseSwig(solana.swig);\n        }\n    }\n    if (managedSolanaOwner &&\n        !isManagedSolanaEndpoint(sdk.composition.config.environment, sdk.composition.config.orchestratorUrl)) {\n        throw new ManagedSolanaAccountNotSupportedError();\n    }\n    const capturedEvmReceiver = evmReceiver\n        ? Object.freeze({ address: evmReceiver })\n        : undefined;\n    const capturedSolanaReceiver = solanaReceiver\n        ? Object.freeze({ address: solanaReceiver })\n        : undefined;\n    const capturedSolana = managedSolanaOwner &&\n        managedSolanaSwig &&\n        Object.freeze({\n            owner: Object.freeze({\n                type: managedSolanaOwner.type,\n                account: managedSolanaOwner.account,\n            }),\n            swig: managedSolanaSwig.swigAccount,\n        });\n    if (managedSolanaOwner && managedSolanaSwig && !managedEvm) {\n        const captured = Object.freeze({\n            ...config,\n            ...(capturedEvmReceiver ? { evm: capturedEvmReceiver } : {}),\n            solana: capturedSolana,\n        });\n        return createSolanaAccountFacade({\n            owner: managedSolanaOwner,\n            walletAddress: managedSolanaSwig.address,\n            swigAddress: managedSolanaSwig.swigAccount,\n            environment: sdk.composition.config.environment,\n            endpoint: sdk.composition.config.orchestratorUrl,\n            ...(evmReceiver ? { evmRecipient: evmReceiver } : {}),\n        }, captured, sdk.composition);\n    }\n    const captured = Object.freeze({\n        ...config,\n        ...(capturedEvmReceiver ? { evm: capturedEvmReceiver } : {}),\n        ...(capturedSolanaReceiver ? { solana: capturedSolanaReceiver } : {}),\n    });\n    if (!managedEvm) {\n        const receiver = {\n            config: captured,\n            getAddress(vm) {\n                if (vm === 'evm' && evmReceiver)\n                    return evmReceiver;\n                if (vm === 'solana' && solanaReceiver)\n                    return solanaReceiver;\n                throw new AccountVmNotConfiguredError(String(vm));\n            },\n        };\n        return Object.freeze(receiver);\n    }\n    const compatibilityConfig = createLegacyAccountConfig(managedEvm, sdk.snapshot);\n    assertAccountOwnersConfigured(materializeAccountInvocationContext(sdk.composition.config, compatibilityConfig, 'get-address').account);\n    const managedCaptured = Object.freeze({\n        ...config,\n        evm: compatibilityConfig,\n        ...(capturedSolana ? { solana: capturedSolana } : {}),\n    });\n    return createAccountFacade(compatibilityConfig, managedCaptured, sdk.composition);\n}\n","/**\n * Internal webcrypto alias.\n * We prefer WebCrypto aka globalThis.crypto, which exists in node.js 16+.\n * Falls back to Node.js built-in crypto for Node.js <=v14.\n * See utils.ts for details.\n * @module\n */\n// @ts-ignore\nimport * as nc from 'node:crypto';\nexport const crypto: any =\n  nc && typeof nc === 'object' && 'webcrypto' in nc\n    ? (nc.webcrypto as any)\n    : nc && typeof nc === 'object' && 'randomBytes' in nc\n      ? nc\n      : undefined;\n","/**\n * Utilities for hex, bytes, CSPRNG.\n * @module\n */\n/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n\n// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// node.js versions earlier than v19 don't declare it in global scope.\n// For node.js, package.json#exports field mapping rewrites import\n// from `crypto` to `cryptoNode`, which imports native module.\n// Makes the utils un-importable in browsers without a bundler.\n// Once node.js 18 is deprecated (2025-04-30), we can just drop the import.\nimport { crypto } from '@noble/hashes/crypto';\n\n/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */\nexport function isBytes(a: unknown): a is Uint8Array {\n  return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n\n/** Asserts something is positive integer. */\nexport function anumber(n: number): void {\n  if (!Number.isSafeInteger(n) || n < 0) throw new Error('positive integer expected, got ' + n);\n}\n\n/** Asserts something is Uint8Array. */\nexport function abytes(b: Uint8Array | undefined, ...lengths: number[]): void {\n  if (!isBytes(b)) throw new Error('Uint8Array expected');\n  if (lengths.length > 0 && !lengths.includes(b.length))\n    throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);\n}\n\n/** Asserts something is hash */\nexport function ahash(h: IHash): void {\n  if (typeof h !== 'function' || typeof h.create !== 'function')\n    throw new Error('Hash should be wrapped by utils.createHasher');\n  anumber(h.outputLen);\n  anumber(h.blockLen);\n}\n\n/** Asserts a hash instance has not been destroyed / finished */\nexport function aexists(instance: any, checkFinished = true): void {\n  if (instance.destroyed) throw new Error('Hash instance has been destroyed');\n  if (checkFinished && instance.finished) throw new Error('Hash#digest() has already been called');\n}\n\n/** Asserts output is properly-sized byte array */\nexport function aoutput(out: any, instance: any): void {\n  abytes(out);\n  const min = instance.outputLen;\n  if (out.length < min) {\n    throw new Error('digestInto() expects output buffer of length at least ' + min);\n  }\n}\n\n/** Generic type encompassing 8/16/32-byte arrays - but not 64-byte. */\n// prettier-ignore\nexport type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array |\n  Uint16Array | Int16Array | Uint32Array | Int32Array;\n\n/** Cast u8 / u16 / u32 to u8. */\nexport function u8(arr: TypedArray): Uint8Array {\n  return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n\n/** Cast u8 / u16 / u32 to u32. */\nexport function u32(arr: TypedArray): Uint32Array {\n  return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n}\n\n/** Zeroize a byte array. Warning: JS provides no guarantees. */\nexport function clean(...arrays: TypedArray[]): void {\n  for (let i = 0; i < arrays.length; i++) {\n    arrays[i].fill(0);\n  }\n}\n\n/** Create DataView of an array for easy byte-level manipulation. */\nexport function createView(arr: TypedArray): DataView {\n  return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n\n/** The rotate right (circular right shift) operation for uint32 */\nexport function rotr(word: number, shift: number): number {\n  return (word << (32 - shift)) | (word >>> shift);\n}\n\n/** The rotate left (circular left shift) operation for uint32 */\nexport function rotl(word: number, shift: number): number {\n  return (word << shift) | ((word >>> (32 - shift)) >>> 0);\n}\n\n/** Is current platform little-endian? Most are. Big-Endian platform: IBM */\nexport const isLE: boolean = /* @__PURE__ */ (() =>\n  new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n\n/** The byte swap operation for uint32 */\nexport function byteSwap(word: number): number {\n  return (\n    ((word << 24) & 0xff000000) |\n    ((word << 8) & 0xff0000) |\n    ((word >>> 8) & 0xff00) |\n    ((word >>> 24) & 0xff)\n  );\n}\n/** Conditionally byte swap if on a big-endian platform */\nexport const swap8IfBE: (n: number) => number = isLE\n  ? (n: number) => n\n  : (n: number) => byteSwap(n);\n\n/** @deprecated */\nexport const byteSwapIfBE: typeof swap8IfBE = swap8IfBE;\n/** In place byte swap for Uint32Array */\nexport function byteSwap32(arr: Uint32Array): Uint32Array {\n  for (let i = 0; i < arr.length; i++) {\n    arr[i] = byteSwap(arr[i]);\n  }\n  return arr;\n}\n\nexport const swap32IfBE: (u: Uint32Array) => Uint32Array = isLE\n  ? (u: Uint32Array) => u\n  : byteSwap32;\n\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin: boolean = /* @__PURE__ */ (() =>\n  // @ts-ignore\n  typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();\n\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) =>\n  i.toString(16).padStart(2, '0')\n);\n\n/**\n * Convert byte array to hex string. Uses built-in function, when available.\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes: Uint8Array): string {\n  abytes(bytes);\n  // @ts-ignore\n  if (hasHexBuiltin) return bytes.toHex();\n  // pre-caching improves the speed 6x\n  let hex = '';\n  for (let i = 0; i < bytes.length; i++) {\n    hex += hexes[bytes[i]];\n  }\n  return hex;\n}\n\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 } as const;\nfunction asciiToBase16(ch: number): number | undefined {\n  if (ch >= asciis._0 && ch <= asciis._9) return ch - asciis._0; // '2' => 50-48\n  if (ch >= asciis.A && ch <= asciis.F) return ch - (asciis.A - 10); // 'B' => 66-(65-10)\n  if (ch >= asciis.a && ch <= asciis.f) return ch - (asciis.a - 10); // 'b' => 98-(97-10)\n  return;\n}\n\n/**\n * Convert hex string to byte array. Uses built-in function, when available.\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex: string): Uint8Array {\n  if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);\n  // @ts-ignore\n  if (hasHexBuiltin) return Uint8Array.fromHex(hex);\n  const hl = hex.length;\n  const al = hl / 2;\n  if (hl % 2) throw new Error('hex string expected, got unpadded hex of length ' + hl);\n  const array = new Uint8Array(al);\n  for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n    const n1 = asciiToBase16(hex.charCodeAt(hi));\n    const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n    if (n1 === undefined || n2 === undefined) {\n      const char = hex[hi] + hex[hi + 1];\n      throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n    }\n    array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163\n  }\n  return array;\n}\n\n/**\n * There is no setImmediate in browser and setTimeout is slow.\n * Call of async fn will return Promise, which will be fullfiled only on\n * next scheduler queue processing step and this is exactly what we need.\n */\nexport const nextTick = async (): Promise<void> => {};\n\n/** Returns control to thread each 'tick' ms to avoid blocking. */\nexport async function asyncLoop(\n  iters: number,\n  tick: number,\n  cb: (i: number) => void\n): Promise<void> {\n  let ts = Date.now();\n  for (let i = 0; i < iters; i++) {\n    cb(i);\n    // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n    const diff = Date.now() - ts;\n    if (diff >= 0 && diff < tick) continue;\n    await nextTick();\n    ts += diff;\n  }\n}\n\n// Global symbols, but ts doesn't see them: https://github.com/microsoft/TypeScript/issues/31535\ndeclare const TextEncoder: any;\ndeclare const TextDecoder: any;\n\n/**\n * Converts string to bytes using UTF8 encoding.\n * @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99])\n */\nexport function utf8ToBytes(str: string): Uint8Array {\n  if (typeof str !== 'string') throw new Error('string expected');\n  return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n\n/**\n * Converts bytes to string using UTF8 encoding.\n * @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'\n */\nexport function bytesToUtf8(bytes: Uint8Array): string {\n  return new TextDecoder().decode(bytes);\n}\n\n/** Accepted input of hash functions. Strings are converted to byte arrays. */\nexport type Input = string | Uint8Array;\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nexport function toBytes(data: Input): Uint8Array {\n  if (typeof data === 'string') data = utf8ToBytes(data);\n  abytes(data);\n  return data;\n}\n\n/** KDFs can accept string or Uint8Array for user convenience. */\nexport type KDFInput = string | Uint8Array;\n/**\n * Helper for KDFs: consumes uint8array or string.\n * When string is passed, does utf8 decoding, using TextDecoder.\n */\nexport function kdfInputToBytes(data: KDFInput): Uint8Array {\n  if (typeof data === 'string') data = utf8ToBytes(data);\n  abytes(data);\n  return data;\n}\n\n/** Copies several Uint8Arrays into one. */\nexport function concatBytes(...arrays: Uint8Array[]): Uint8Array {\n  let sum = 0;\n  for (let i = 0; i < arrays.length; i++) {\n    const a = arrays[i];\n    abytes(a);\n    sum += a.length;\n  }\n  const res = new Uint8Array(sum);\n  for (let i = 0, pad = 0; i < arrays.length; i++) {\n    const a = arrays[i];\n    res.set(a, pad);\n    pad += a.length;\n  }\n  return res;\n}\n\ntype EmptyObj = {};\nexport function checkOpts<T1 extends EmptyObj, T2 extends EmptyObj>(\n  defaults: T1,\n  opts?: T2\n): T1 & T2 {\n  if (opts !== undefined && {}.toString.call(opts) !== '[object Object]')\n    throw new Error('options should be object or undefined');\n  const merged = Object.assign(defaults, opts);\n  return merged as T1 & T2;\n}\n\n/** Hash interface. */\nexport type IHash = {\n  (data: Uint8Array): Uint8Array;\n  blockLen: number;\n  outputLen: number;\n  create: any;\n};\n\n/** For runtime check if class implements interface */\nexport abstract class Hash<T extends Hash<T>> {\n  abstract blockLen: number; // Bytes per block\n  abstract outputLen: number; // Bytes in output\n  abstract update(buf: Input): this;\n  // Writes digest into buf\n  abstract digestInto(buf: Uint8Array): void;\n  abstract digest(): Uint8Array;\n  /**\n   * Resets internal state. Makes Hash instance unusable.\n   * Reset is impossible for keyed hashes if key is consumed into state. If digest is not consumed\n   * by user, they will need to manually call `destroy()` when zeroing is necessary.\n   */\n  abstract destroy(): void;\n  /**\n   * Clones hash instance. Unsafe: doesn't check whether `to` is valid. Can be used as `clone()`\n   * when no options are passed.\n   * Reasons to use `_cloneInto` instead of clone: 1) performance 2) reuse instance => all internal\n   * buffers are overwritten => causes buffer overwrite which is used for digest in some cases.\n   * There are no guarantees for clean-up because it's impossible in JS.\n   */\n  abstract _cloneInto(to?: T): T;\n  // Safe version that clones internal state\n  abstract clone(): T;\n}\n\n/**\n * XOF: streaming API to read digest in chunks.\n * Same as 'squeeze' in keccak/k12 and 'seek' in blake3, but more generic name.\n * When hash used in XOF mode it is up to user to call '.destroy' afterwards, since we cannot\n * destroy state, next call can require more bytes.\n */\nexport type HashXOF<T extends Hash<T>> = Hash<T> & {\n  xof(bytes: number): Uint8Array; // Read 'bytes' bytes from digest stream\n  xofInto(buf: Uint8Array): Uint8Array; // read buf.length bytes from digest stream into buf\n};\n\n/** Hash function */\nexport type CHash = ReturnType<typeof createHasher>;\n/** Hash function with output */\nexport type CHashO = ReturnType<typeof createOptHasher>;\n/** XOF with output */\nexport type CHashXO = ReturnType<typeof createXOFer>;\n\n/** Wraps hash function, creating an interface on top of it */\nexport function createHasher<T extends Hash<T>>(\n  hashCons: () => Hash<T>\n): {\n  (msg: Input): Uint8Array;\n  outputLen: number;\n  blockLen: number;\n  create(): Hash<T>;\n} {\n  const hashC = (msg: Input): Uint8Array => hashCons().update(toBytes(msg)).digest();\n  const tmp = hashCons();\n  hashC.outputLen = tmp.outputLen;\n  hashC.blockLen = tmp.blockLen;\n  hashC.create = () => hashCons();\n  return hashC;\n}\n\nexport function createOptHasher<H extends Hash<H>, T extends Object>(\n  hashCons: (opts?: T) => Hash<H>\n): {\n  (msg: Input, opts?: T): Uint8Array;\n  outputLen: number;\n  blockLen: number;\n  create(opts?: T): Hash<H>;\n} {\n  const hashC = (msg: Input, opts?: T): Uint8Array => hashCons(opts).update(toBytes(msg)).digest();\n  const tmp = hashCons({} as T);\n  hashC.outputLen = tmp.outputLen;\n  hashC.blockLen = tmp.blockLen;\n  hashC.create = (opts?: T) => hashCons(opts);\n  return hashC;\n}\n\nexport function createXOFer<H extends HashXOF<H>, T extends Object>(\n  hashCons: (opts?: T) => HashXOF<H>\n): {\n  (msg: Input, opts?: T): Uint8Array;\n  outputLen: number;\n  blockLen: number;\n  create(opts?: T): HashXOF<H>;\n} {\n  const hashC = (msg: Input, opts?: T): Uint8Array => hashCons(opts).update(toBytes(msg)).digest();\n  const tmp = hashCons({} as T);\n  hashC.outputLen = tmp.outputLen;\n  hashC.blockLen = tmp.blockLen;\n  hashC.create = (opts?: T) => hashCons(opts);\n  return hashC;\n}\nexport const wrapConstructor: typeof createHasher = createHasher;\nexport const wrapConstructorWithOpts: typeof createOptHasher = createOptHasher;\nexport const wrapXOFConstructorWithOpts: typeof createXOFer = createXOFer;\n\n/** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */\nexport function randomBytes(bytesLength = 32): Uint8Array {\n  if (crypto && typeof crypto.getRandomValues === 'function') {\n    return crypto.getRandomValues(new Uint8Array(bytesLength));\n  }\n  // Legacy Node.js compatibility\n  if (crypto && typeof crypto.randomBytes === 'function') {\n    return Uint8Array.from(crypto.randomBytes(bytesLength));\n  }\n  throw new Error('crypto.getRandomValues must be defined');\n}\n","/**\n * Internal Merkle-Damgard hash utils.\n * @module\n */\nimport { type Input, Hash, abytes, aexists, aoutput, clean, createView, toBytes } from './utils.ts';\n\n/** Polyfill for Safari 14. https://caniuse.com/mdn-javascript_builtins_dataview_setbiguint64 */\nexport function setBigUint64(\n  view: DataView,\n  byteOffset: number,\n  value: bigint,\n  isLE: boolean\n): void {\n  if (typeof view.setBigUint64 === 'function') return view.setBigUint64(byteOffset, value, isLE);\n  const _32n = BigInt(32);\n  const _u32_max = BigInt(0xffffffff);\n  const wh = Number((value >> _32n) & _u32_max);\n  const wl = Number(value & _u32_max);\n  const h = isLE ? 4 : 0;\n  const l = isLE ? 0 : 4;\n  view.setUint32(byteOffset + h, wh, isLE);\n  view.setUint32(byteOffset + l, wl, isLE);\n}\n\n/** Choice: a ? b : c */\nexport function Chi(a: number, b: number, c: number): number {\n  return (a & b) ^ (~a & c);\n}\n\n/** Majority function, true if any two inputs is true. */\nexport function Maj(a: number, b: number, c: number): number {\n  return (a & b) ^ (a & c) ^ (b & c);\n}\n\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n */\nexport abstract class HashMD<T extends HashMD<T>> extends Hash<T> {\n  protected abstract process(buf: DataView, offset: number): void;\n  protected abstract get(): number[];\n  protected abstract set(...args: number[]): void;\n  abstract destroy(): void;\n  protected abstract roundClean(): void;\n\n  readonly blockLen: number;\n  readonly outputLen: number;\n  readonly padOffset: number;\n  readonly isLE: boolean;\n\n  // For partial updates less than block size\n  protected buffer: Uint8Array;\n  protected view: DataView;\n  protected finished = false;\n  protected length = 0;\n  protected pos = 0;\n  protected destroyed = false;\n\n  constructor(blockLen: number, outputLen: number, padOffset: number, isLE: boolean) {\n    super();\n    this.blockLen = blockLen;\n    this.outputLen = outputLen;\n    this.padOffset = padOffset;\n    this.isLE = isLE;\n    this.buffer = new Uint8Array(blockLen);\n    this.view = createView(this.buffer);\n  }\n  update(data: Input): this {\n    aexists(this);\n    data = toBytes(data);\n    abytes(data);\n    const { view, buffer, blockLen } = this;\n    const len = data.length;\n    for (let pos = 0; pos < len; ) {\n      const take = Math.min(blockLen - this.pos, len - pos);\n      // Fast path: we have at least one block in input, cast it to view and process\n      if (take === blockLen) {\n        const dataView = createView(data);\n        for (; blockLen <= len - pos; pos += blockLen) this.process(dataView, pos);\n        continue;\n      }\n      buffer.set(data.subarray(pos, pos + take), this.pos);\n      this.pos += take;\n      pos += take;\n      if (this.pos === blockLen) {\n        this.process(view, 0);\n        this.pos = 0;\n      }\n    }\n    this.length += data.length;\n    this.roundClean();\n    return this;\n  }\n  digestInto(out: Uint8Array): void {\n    aexists(this);\n    aoutput(out, this);\n    this.finished = true;\n    // Padding\n    // We can avoid allocation of buffer for padding completely if it\n    // was previously not allocated here. But it won't change performance.\n    const { buffer, view, blockLen, isLE } = this;\n    let { pos } = this;\n    // append the bit '1' to the message\n    buffer[pos++] = 0b10000000;\n    clean(this.buffer.subarray(pos));\n    // we have less than padOffset left in buffer, so we cannot put length in\n    // current block, need process it and pad again\n    if (this.padOffset > blockLen - pos) {\n      this.process(view, 0);\n      pos = 0;\n    }\n    // Pad until full block byte with zeros\n    for (let i = pos; i < blockLen; i++) buffer[i] = 0;\n    // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that\n    // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.\n    // So we just write lowest 64 bits of that value.\n    setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);\n    this.process(view, 0);\n    const oview = createView(out);\n    const len = this.outputLen;\n    // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT\n    if (len % 4) throw new Error('_sha2: outputLen should be aligned to 32bit');\n    const outLen = len / 4;\n    const state = this.get();\n    if (outLen > state.length) throw new Error('_sha2: outputLen bigger than state');\n    for (let i = 0; i < outLen; i++) oview.setUint32(4 * i, state[i], isLE);\n  }\n  digest(): Uint8Array {\n    const { buffer, outputLen } = this;\n    this.digestInto(buffer);\n    const res = buffer.slice(0, outputLen);\n    this.destroy();\n    return res;\n  }\n  _cloneInto(to?: T): T {\n    to ||= new (this.constructor as any)() as T;\n    to.set(...this.get());\n    const { blockLen, buffer, length, finished, destroyed, pos } = this;\n    to.destroyed = destroyed;\n    to.finished = finished;\n    to.length = length;\n    to.pos = pos;\n    if (length % blockLen) to.buffer.set(buffer);\n    return to;\n  }\n  clone(): T {\n    return this._cloneInto();\n  }\n}\n\n/**\n * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.\n * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.\n */\n\n/** Initial SHA256 state. Bits 0..32 of frac part of sqrt of primes 2..19 */\nexport const SHA256_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n  0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n]);\n\n/** Initial SHA224 state. Bits 32..64 of frac part of sqrt of primes 23..53 */\nexport const SHA224_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n  0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,\n]);\n\n/** Initial SHA384 state. Bits 0..64 of frac part of sqrt of primes 23..53 */\nexport const SHA384_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n  0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,\n  0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,\n]);\n\n/** Initial SHA512 state. Bits 0..64 of frac part of sqrt of primes 2..19 */\nexport const SHA512_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n  0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,\n  0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,\n]);\n","/**\n * Internal helpers for u64. BigUint64Array is too slow as per 2025, so we implement it using Uint32Array.\n * @todo re-check https://issues.chromium.org/issues/42212588\n * @module\n */\nconst U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);\nconst _32n = /* @__PURE__ */ BigInt(32);\n\nfunction fromBig(\n  n: bigint,\n  le = false\n): {\n  h: number;\n  l: number;\n} {\n  if (le) return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };\n  return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };\n}\n\nfunction split(lst: bigint[], le = false): Uint32Array[] {\n  const len = lst.length;\n  let Ah = new Uint32Array(len);\n  let Al = new Uint32Array(len);\n  for (let i = 0; i < len; i++) {\n    const { h, l } = fromBig(lst[i], le);\n    [Ah[i], Al[i]] = [h, l];\n  }\n  return [Ah, Al];\n}\n\nconst toBig = (h: number, l: number): bigint => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// for Shift in [0, 32)\nconst shrSH = (h: number, _l: number, s: number): number => h >>> s;\nconst shrSL = (h: number, l: number, s: number): number => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in [1, 32)\nconst rotrSH = (h: number, l: number, s: number): number => (h >>> s) | (l << (32 - s));\nconst rotrSL = (h: number, l: number, s: number): number => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotrBH = (h: number, l: number, s: number): number => (h << (64 - s)) | (l >>> (s - 32));\nconst rotrBL = (h: number, l: number, s: number): number => (h >>> (s - 32)) | (l << (64 - s));\n// Right rotate for shift===32 (just swaps l&h)\nconst rotr32H = (_h: number, l: number): number => l;\nconst rotr32L = (h: number, _l: number): number => h;\n// Left rotate for Shift in [1, 32)\nconst rotlSH = (h: number, l: number, s: number): number => (h << s) | (l >>> (32 - s));\nconst rotlSL = (h: number, l: number, s: number): number => (l << s) | (h >>> (32 - s));\n// Left rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotlBH = (h: number, l: number, s: number): number => (l << (s - 32)) | (h >>> (64 - s));\nconst rotlBL = (h: number, l: number, s: number): number => (h << (s - 32)) | (l >>> (64 - s));\n\n// JS uses 32-bit signed integers for bitwise operations which means we cannot\n// simple take carry out of low bit sum by shift, we need to use division.\nfunction add(\n  Ah: number,\n  Al: number,\n  Bh: number,\n  Bl: number\n): {\n  h: number;\n  l: number;\n} {\n  const l = (Al >>> 0) + (Bl >>> 0);\n  return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };\n}\n// Addition with more than 2 elements\nconst add3L = (Al: number, Bl: number, Cl: number): number => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\nconst add3H = (low: number, Ah: number, Bh: number, Ch: number): number =>\n  (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\nconst add4L = (Al: number, Bl: number, Cl: number, Dl: number): number =>\n  (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\nconst add4H = (low: number, Ah: number, Bh: number, Ch: number, Dh: number): number =>\n  (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\nconst add5L = (Al: number, Bl: number, Cl: number, Dl: number, El: number): number =>\n  (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);\nconst add5H = (low: number, Ah: number, Bh: number, Ch: number, Dh: number, Eh: number): number =>\n  (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n\n// prettier-ignore\nexport {\n  add, add3H, add3L, add4H, add4L, add5H, add5L, fromBig, rotlBH, rotlBL, rotlSH, rotlSL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, shrSH, shrSL, split, toBig\n};\n// prettier-ignore\nconst u64: { fromBig: typeof fromBig; split: typeof split; toBig: (h: number, l: number) => bigint; shrSH: (h: number, _l: number, s: number) => number; shrSL: (h: number, l: number, s: number) => number; rotrSH: (h: number, l: number, s: number) => number; rotrSL: (h: number, l: number, s: number) => number; rotrBH: (h: number, l: number, s: number) => number; rotrBL: (h: number, l: number, s: number) => number; rotr32H: (_h: number, l: number) => number; rotr32L: (h: number, _l: number) => number; rotlSH: (h: number, l: number, s: number) => number; rotlSL: (h: number, l: number, s: number) => number; rotlBH: (h: number, l: number, s: number) => number; rotlBL: (h: number, l: number, s: number) => number; add: typeof add; add3L: (Al: number, Bl: number, Cl: number) => number; add3H: (low: number, Ah: number, Bh: number, Ch: number) => number; add4L: (Al: number, Bl: number, Cl: number, Dl: number) => number; add4H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number) => number; add5H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number, Eh: number) => number; add5L: (Al: number, Bl: number, Cl: number, Dl: number, El: number) => number; } = {\n  fromBig, split, toBig,\n  shrSH, shrSL,\n  rotrSH, rotrSL, rotrBH, rotrBL,\n  rotr32H, rotr32L,\n  rotlSH, rotlSL, rotlBH, rotlBL,\n  add, add3L, add3H, add4L, add4H, add5H, add5L,\n};\nexport default u64;\n","/**\n * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.\n * SHA256 is the fastest hash implementable in JS, even faster than Blake3.\n * Check out [RFC 4634](https://datatracker.ietf.org/doc/html/rfc4634) and\n * [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).\n * @module\n */\nimport { Chi, HashMD, Maj, SHA224_IV, SHA256_IV, SHA384_IV, SHA512_IV } from './_md.ts';\nimport * as u64 from './_u64.ts';\nimport { type CHash, clean, createHasher, rotr } from './utils.ts';\n\n/**\n * Round constants:\n * First 32 bits of fractional parts of the cube roots of the first 64 primes 2..311)\n */\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ Uint32Array.from([\n  0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n  0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n  0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n  0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n  0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n  0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n  0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n  0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n\n/** Reusable temporary buffer. \"W\" comes straight from spec. */\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\nexport class SHA256 extends HashMD<SHA256> {\n  // We cannot use array here since array allows indexing by variable\n  // which means optimizer/compiler cannot use registers.\n  protected A: number = SHA256_IV[0] | 0;\n  protected B: number = SHA256_IV[1] | 0;\n  protected C: number = SHA256_IV[2] | 0;\n  protected D: number = SHA256_IV[3] | 0;\n  protected E: number = SHA256_IV[4] | 0;\n  protected F: number = SHA256_IV[5] | 0;\n  protected G: number = SHA256_IV[6] | 0;\n  protected H: number = SHA256_IV[7] | 0;\n\n  constructor(outputLen: number = 32) {\n    super(64, outputLen, 8, false);\n  }\n  protected get(): [number, number, number, number, number, number, number, number] {\n    const { A, B, C, D, E, F, G, H } = this;\n    return [A, B, C, D, E, F, G, H];\n  }\n  // prettier-ignore\n  protected set(\n    A: number, B: number, C: number, D: number, E: number, F: number, G: number, H: number\n  ): void {\n    this.A = A | 0;\n    this.B = B | 0;\n    this.C = C | 0;\n    this.D = D | 0;\n    this.E = E | 0;\n    this.F = F | 0;\n    this.G = G | 0;\n    this.H = H | 0;\n  }\n  protected process(view: DataView, offset: number): void {\n    // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n    for (let i = 0; i < 16; i++, offset += 4) SHA256_W[i] = view.getUint32(offset, false);\n    for (let i = 16; i < 64; i++) {\n      const W15 = SHA256_W[i - 15];\n      const W2 = SHA256_W[i - 2];\n      const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);\n      const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);\n      SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n    }\n    // Compression function main loop, 64 rounds\n    let { A, B, C, D, E, F, G, H } = this;\n    for (let i = 0; i < 64; i++) {\n      const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);\n      const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n      const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);\n      const T2 = (sigma0 + Maj(A, B, C)) | 0;\n      H = G;\n      G = F;\n      F = E;\n      E = (D + T1) | 0;\n      D = C;\n      C = B;\n      B = A;\n      A = (T1 + T2) | 0;\n    }\n    // Add the compressed chunk to the current hash value\n    A = (A + this.A) | 0;\n    B = (B + this.B) | 0;\n    C = (C + this.C) | 0;\n    D = (D + this.D) | 0;\n    E = (E + this.E) | 0;\n    F = (F + this.F) | 0;\n    G = (G + this.G) | 0;\n    H = (H + this.H) | 0;\n    this.set(A, B, C, D, E, F, G, H);\n  }\n  protected roundClean(): void {\n    clean(SHA256_W);\n  }\n  destroy(): void {\n    this.set(0, 0, 0, 0, 0, 0, 0, 0);\n    clean(this.buffer);\n  }\n}\n\nexport class SHA224 extends SHA256 {\n  protected A: number = SHA224_IV[0] | 0;\n  protected B: number = SHA224_IV[1] | 0;\n  protected C: number = SHA224_IV[2] | 0;\n  protected D: number = SHA224_IV[3] | 0;\n  protected E: number = SHA224_IV[4] | 0;\n  protected F: number = SHA224_IV[5] | 0;\n  protected G: number = SHA224_IV[6] | 0;\n  protected H: number = SHA224_IV[7] | 0;\n  constructor() {\n    super(28);\n  }\n}\n\n// SHA2-512 is slower than sha256 in js because u64 operations are slow.\n\n// Round contants\n// First 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409\n// prettier-ignore\nconst K512 = /* @__PURE__ */ (() => u64.split([\n  '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n  '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n  '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n  '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n  '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n  '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n  '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n  '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n  '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n  '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n  '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n  '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n  '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n  '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n  '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n  '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n  '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n  '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n  '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n  '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\nconst SHA512_Kh = /* @__PURE__ */ (() => K512[0])();\nconst SHA512_Kl = /* @__PURE__ */ (() => K512[1])();\n\n// Reusable temporary buffers\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\n\nexport class SHA512 extends HashMD<SHA512> {\n  // We cannot use array here since array allows indexing by variable\n  // which means optimizer/compiler cannot use registers.\n  // h -- high 32 bits, l -- low 32 bits\n  protected Ah: number = SHA512_IV[0] | 0;\n  protected Al: number = SHA512_IV[1] | 0;\n  protected Bh: number = SHA512_IV[2] | 0;\n  protected Bl: number = SHA512_IV[3] | 0;\n  protected Ch: number = SHA512_IV[4] | 0;\n  protected Cl: number = SHA512_IV[5] | 0;\n  protected Dh: number = SHA512_IV[6] | 0;\n  protected Dl: number = SHA512_IV[7] | 0;\n  protected Eh: number = SHA512_IV[8] | 0;\n  protected El: number = SHA512_IV[9] | 0;\n  protected Fh: number = SHA512_IV[10] | 0;\n  protected Fl: number = SHA512_IV[11] | 0;\n  protected Gh: number = SHA512_IV[12] | 0;\n  protected Gl: number = SHA512_IV[13] | 0;\n  protected Hh: number = SHA512_IV[14] | 0;\n  protected Hl: number = SHA512_IV[15] | 0;\n\n  constructor(outputLen: number = 64) {\n    super(128, outputLen, 16, false);\n  }\n  // prettier-ignore\n  protected get(): [\n    number, number, number, number, number, number, number, number,\n    number, number, number, number, number, number, number, number\n  ] {\n    const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n    return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n  }\n  // prettier-ignore\n  protected set(\n    Ah: number, Al: number, Bh: number, Bl: number, Ch: number, Cl: number, Dh: number, Dl: number,\n    Eh: number, El: number, Fh: number, Fl: number, Gh: number, Gl: number, Hh: number, Hl: number\n  ): void {\n    this.Ah = Ah | 0;\n    this.Al = Al | 0;\n    this.Bh = Bh | 0;\n    this.Bl = Bl | 0;\n    this.Ch = Ch | 0;\n    this.Cl = Cl | 0;\n    this.Dh = Dh | 0;\n    this.Dl = Dl | 0;\n    this.Eh = Eh | 0;\n    this.El = El | 0;\n    this.Fh = Fh | 0;\n    this.Fl = Fl | 0;\n    this.Gh = Gh | 0;\n    this.Gl = Gl | 0;\n    this.Hh = Hh | 0;\n    this.Hl = Hl | 0;\n  }\n  protected process(view: DataView, offset: number): void {\n    // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n    for (let i = 0; i < 16; i++, offset += 4) {\n      SHA512_W_H[i] = view.getUint32(offset);\n      SHA512_W_L[i] = view.getUint32((offset += 4));\n    }\n    for (let i = 16; i < 80; i++) {\n      // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n      const W15h = SHA512_W_H[i - 15] | 0;\n      const W15l = SHA512_W_L[i - 15] | 0;\n      const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);\n      const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);\n      // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n      const W2h = SHA512_W_H[i - 2] | 0;\n      const W2l = SHA512_W_L[i - 2] | 0;\n      const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);\n      const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);\n      // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];\n      const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n      const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n      SHA512_W_H[i] = SUMh | 0;\n      SHA512_W_L[i] = SUMl | 0;\n    }\n    let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n    // Compression function main loop, 80 rounds\n    for (let i = 0; i < 80; i++) {\n      // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n      const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);\n      const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);\n      //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n      const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n      const CHIl = (El & Fl) ^ (~El & Gl);\n      // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n      // prettier-ignore\n      const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n      const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n      const T1l = T1ll | 0;\n      // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n      const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);\n      const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);\n      const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n      const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n      Hh = Gh | 0;\n      Hl = Gl | 0;\n      Gh = Fh | 0;\n      Gl = Fl | 0;\n      Fh = Eh | 0;\n      Fl = El | 0;\n      ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n      Dh = Ch | 0;\n      Dl = Cl | 0;\n      Ch = Bh | 0;\n      Cl = Bl | 0;\n      Bh = Ah | 0;\n      Bl = Al | 0;\n      const All = u64.add3L(T1l, sigma0l, MAJl);\n      Ah = u64.add3H(All, T1h, sigma0h, MAJh);\n      Al = All | 0;\n    }\n    // Add the compressed chunk to the current hash value\n    ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n    ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n    ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n    ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n    ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n    ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n    ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n    ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n    this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n  }\n  protected roundClean(): void {\n    clean(SHA512_W_H, SHA512_W_L);\n  }\n  destroy(): void {\n    clean(this.buffer);\n    this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n  }\n}\n\nexport class SHA384 extends SHA512 {\n  protected Ah: number = SHA384_IV[0] | 0;\n  protected Al: number = SHA384_IV[1] | 0;\n  protected Bh: number = SHA384_IV[2] | 0;\n  protected Bl: number = SHA384_IV[3] | 0;\n  protected Ch: number = SHA384_IV[4] | 0;\n  protected Cl: number = SHA384_IV[5] | 0;\n  protected Dh: number = SHA384_IV[6] | 0;\n  protected Dl: number = SHA384_IV[7] | 0;\n  protected Eh: number = SHA384_IV[8] | 0;\n  protected El: number = SHA384_IV[9] | 0;\n  protected Fh: number = SHA384_IV[10] | 0;\n  protected Fl: number = SHA384_IV[11] | 0;\n  protected Gh: number = SHA384_IV[12] | 0;\n  protected Gl: number = SHA384_IV[13] | 0;\n  protected Hh: number = SHA384_IV[14] | 0;\n  protected Hl: number = SHA384_IV[15] | 0;\n\n  constructor() {\n    super(48);\n  }\n}\n\n/**\n * Truncated SHA512/256 and SHA512/224.\n * SHA512_IV is XORed with 0xa5a5a5a5a5a5a5a5, then used as \"intermediary\" IV of SHA512/t.\n * Then t hashes string to produce result IV.\n * See `test/misc/sha2-gen-iv.js`.\n */\n\n/** SHA512/224 IV */\nconst T224_IV = /* @__PURE__ */ Uint32Array.from([\n  0x8c3d37c8, 0x19544da2, 0x73e19966, 0x89dcd4d6, 0x1dfab7ae, 0x32ff9c82, 0x679dd514, 0x582f9fcf,\n  0x0f6d2b69, 0x7bd44da8, 0x77e36f73, 0x04c48942, 0x3f9d85a8, 0x6a1d36c8, 0x1112e6ad, 0x91d692a1,\n]);\n\n/** SHA512/256 IV */\nconst T256_IV = /* @__PURE__ */ Uint32Array.from([\n  0x22312194, 0xfc2bf72c, 0x9f555fa3, 0xc84c64c2, 0x2393b86b, 0x6f53b151, 0x96387719, 0x5940eabd,\n  0x96283ee2, 0xa88effe3, 0xbe5e1e25, 0x53863992, 0x2b0199fc, 0x2c85b8aa, 0x0eb72ddc, 0x81c52ca2,\n]);\n\nexport class SHA512_224 extends SHA512 {\n  protected Ah: number = T224_IV[0] | 0;\n  protected Al: number = T224_IV[1] | 0;\n  protected Bh: number = T224_IV[2] | 0;\n  protected Bl: number = T224_IV[3] | 0;\n  protected Ch: number = T224_IV[4] | 0;\n  protected Cl: number = T224_IV[5] | 0;\n  protected Dh: number = T224_IV[6] | 0;\n  protected Dl: number = T224_IV[7] | 0;\n  protected Eh: number = T224_IV[8] | 0;\n  protected El: number = T224_IV[9] | 0;\n  protected Fh: number = T224_IV[10] | 0;\n  protected Fl: number = T224_IV[11] | 0;\n  protected Gh: number = T224_IV[12] | 0;\n  protected Gl: number = T224_IV[13] | 0;\n  protected Hh: number = T224_IV[14] | 0;\n  protected Hl: number = T224_IV[15] | 0;\n\n  constructor() {\n    super(28);\n  }\n}\n\nexport class SHA512_256 extends SHA512 {\n  protected Ah: number = T256_IV[0] | 0;\n  protected Al: number = T256_IV[1] | 0;\n  protected Bh: number = T256_IV[2] | 0;\n  protected Bl: number = T256_IV[3] | 0;\n  protected Ch: number = T256_IV[4] | 0;\n  protected Cl: number = T256_IV[5] | 0;\n  protected Dh: number = T256_IV[6] | 0;\n  protected Dl: number = T256_IV[7] | 0;\n  protected Eh: number = T256_IV[8] | 0;\n  protected El: number = T256_IV[9] | 0;\n  protected Fh: number = T256_IV[10] | 0;\n  protected Fl: number = T256_IV[11] | 0;\n  protected Gh: number = T256_IV[12] | 0;\n  protected Gl: number = T256_IV[13] | 0;\n  protected Hh: number = T256_IV[14] | 0;\n  protected Hl: number = T256_IV[15] | 0;\n\n  constructor() {\n    super(32);\n  }\n}\n\n/**\n * SHA2-256 hash function from RFC 4634.\n *\n * It is the fastest JS hash, even faster than Blake3.\n * To break sha256 using birthday attack, attackers need to try 2^128 hashes.\n * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n */\nexport const sha256: CHash = /* @__PURE__ */ createHasher(() => new SHA256());\n/** SHA2-224 hash function from RFC 4634 */\nexport const sha224: CHash = /* @__PURE__ */ createHasher(() => new SHA224());\n\n/** SHA2-512 hash function from RFC 4634. */\nexport const sha512: CHash = /* @__PURE__ */ createHasher(() => new SHA512());\n/** SHA2-384 hash function from RFC 4634. */\nexport const sha384: CHash = /* @__PURE__ */ createHasher(() => new SHA384());\n\n/**\n * SHA2-512/256 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_256: CHash = /* @__PURE__ */ createHasher(() => new SHA512_256());\n/**\n * SHA2-512/224 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_224: CHash = /* @__PURE__ */ createHasher(() => new SHA512_224());\n","/**\n * Hex, bytes and number utilities.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport {\n  abytes as abytes_,\n  bytesToHex as bytesToHex_,\n  concatBytes as concatBytes_,\n  hexToBytes as hexToBytes_,\n  isBytes as isBytes_,\n} from '@noble/hashes/utils.js';\nexport {\n  abytes,\n  anumber,\n  bytesToHex,\n  bytesToUtf8,\n  concatBytes,\n  hexToBytes,\n  isBytes,\n  randomBytes,\n  utf8ToBytes,\n} from '@noble/hashes/utils.js';\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\nexport type Hex = Uint8Array | string; // hex strings are accepted for simplicity\nexport type PrivKey = Hex | bigint; // bigints are accepted to ease learning curve\nexport type CHash = {\n  (message: Uint8Array | string): Uint8Array;\n  blockLen: number;\n  outputLen: number;\n  create(opts?: { dkLen?: number }): any; // For shake\n};\nexport type FHash = (message: Uint8Array | string) => Uint8Array;\n\nexport function abool(title: string, value: boolean): void {\n  if (typeof value !== 'boolean') throw new Error(title + ' boolean expected, got ' + value);\n}\n\n// tmp name until v2\nexport function _abool2(value: boolean, title: string = ''): boolean {\n  if (typeof value !== 'boolean') {\n    const prefix = title && `\"${title}\"`;\n    throw new Error(prefix + 'expected boolean, got type=' + typeof value);\n  }\n  return value;\n}\n\n// tmp name until v2\n/** Asserts something is Uint8Array. */\nexport function _abytes2(value: Uint8Array, length?: number, title: string = ''): Uint8Array {\n  const bytes = isBytes_(value);\n  const len = value?.length;\n  const needsLen = length !== undefined;\n  if (!bytes || (needsLen && len !== length)) {\n    const prefix = title && `\"${title}\" `;\n    const ofLen = needsLen ? ` of length ${length}` : '';\n    const got = bytes ? `length=${len}` : `type=${typeof value}`;\n    throw new Error(prefix + 'expected Uint8Array' + ofLen + ', got ' + got);\n  }\n  return value;\n}\n\n// Used in weierstrass, der\nexport function numberToHexUnpadded(num: number | bigint): string {\n  const hex = num.toString(16);\n  return hex.length & 1 ? '0' + hex : hex;\n}\n\nexport function hexToNumber(hex: string): bigint {\n  if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);\n  return hex === '' ? _0n : BigInt('0x' + hex); // Big Endian\n}\n\n// BE: Big Endian, LE: Little Endian\nexport function bytesToNumberBE(bytes: Uint8Array): bigint {\n  return hexToNumber(bytesToHex_(bytes));\n}\nexport function bytesToNumberLE(bytes: Uint8Array): bigint {\n  abytes_(bytes);\n  return hexToNumber(bytesToHex_(Uint8Array.from(bytes).reverse()));\n}\n\nexport function numberToBytesBE(n: number | bigint, len: number): Uint8Array {\n  return hexToBytes_(n.toString(16).padStart(len * 2, '0'));\n}\nexport function numberToBytesLE(n: number | bigint, len: number): Uint8Array {\n  return numberToBytesBE(n, len).reverse();\n}\n// Unpadded, rarely used\nexport function numberToVarBytesBE(n: number | bigint): Uint8Array {\n  return hexToBytes_(numberToHexUnpadded(n));\n}\n\n/**\n * Takes hex string or Uint8Array, converts to Uint8Array.\n * Validates output length.\n * Will throw error for other types.\n * @param title descriptive title for an error e.g. 'secret key'\n * @param hex hex string or Uint8Array\n * @param expectedLength optional, will compare to result array's length\n * @returns\n */\nexport function ensureBytes(title: string, hex: Hex, expectedLength?: number): Uint8Array {\n  let res: Uint8Array;\n  if (typeof hex === 'string') {\n    try {\n      res = hexToBytes_(hex);\n    } catch (e) {\n      throw new Error(title + ' must be hex string or Uint8Array, cause: ' + e);\n    }\n  } else if (isBytes_(hex)) {\n    // Uint8Array.from() instead of hash.slice() because node.js Buffer\n    // is instance of Uint8Array, and its slice() creates **mutable** copy\n    res = Uint8Array.from(hex);\n  } else {\n    throw new Error(title + ' must be hex string or Uint8Array');\n  }\n  const len = res.length;\n  if (typeof expectedLength === 'number' && len !== expectedLength)\n    throw new Error(title + ' of length ' + expectedLength + ' expected, got ' + len);\n  return res;\n}\n\n// Compares 2 u8a-s in kinda constant time\nexport function equalBytes(a: Uint8Array, b: Uint8Array): boolean {\n  if (a.length !== b.length) return false;\n  let diff = 0;\n  for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];\n  return diff === 0;\n}\n/**\n * Copies Uint8Array. We can't use u8a.slice(), because u8a can be Buffer,\n * and Buffer#slice creates mutable copy. Never use Buffers!\n */\nexport function copyBytes(bytes: Uint8Array): Uint8Array {\n  return Uint8Array.from(bytes);\n}\n\n/**\n * Decodes 7-bit ASCII string to Uint8Array, throws on non-ascii symbols\n * Should be safe to use for things expected to be ASCII.\n * Returns exact same result as utf8ToBytes for ASCII or throws.\n */\nexport function asciiToBytes(ascii: string): Uint8Array {\n  return Uint8Array.from(ascii, (c, i) => {\n    const charCode = c.charCodeAt(0);\n    if (c.length !== 1 || charCode > 127) {\n      throw new Error(\n        `string contains non-ASCII character \"${ascii[i]}\" with code ${charCode} at position ${i}`\n      );\n    }\n    return charCode;\n  });\n}\n\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\n// export const utf8ToBytes: typeof utf8ToBytes_ = utf8ToBytes_;\n/**\n * Converts bytes to string using UTF8 encoding.\n * @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'\n */\n// export const bytesToUtf8: typeof bytesToUtf8_ = bytesToUtf8_;\n\n// Is positive bigint\nconst isPosBig = (n: bigint) => typeof n === 'bigint' && _0n <= n;\n\nexport function inRange(n: bigint, min: bigint, max: bigint): boolean {\n  return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;\n}\n\n/**\n * Asserts min <= n < max. NOTE: It's < max and not <= max.\n * @example\n * aInRange('x', x, 1n, 256n); // would assume x is in (1n..255n)\n */\nexport function aInRange(title: string, n: bigint, min: bigint, max: bigint): void {\n  // Why min <= n < max and not a (min < n < max) OR b (min <= n <= max)?\n  // consider P=256n, min=0n, max=P\n  // - a for min=0 would require -1:          `inRange('x', x, -1n, P)`\n  // - b would commonly require subtraction:  `inRange('x', x, 0n, P - 1n)`\n  // - our way is the cleanest:               `inRange('x', x, 0n, P)\n  if (!inRange(n, min, max))\n    throw new Error('expected valid ' + title + ': ' + min + ' <= n < ' + max + ', got ' + n);\n}\n\n// Bit operations\n\n/**\n * Calculates amount of bits in a bigint.\n * Same as `n.toString(2).length`\n * TODO: merge with nLength in modular\n */\nexport function bitLen(n: bigint): number {\n  let len;\n  for (len = 0; n > _0n; n >>= _1n, len += 1);\n  return len;\n}\n\n/**\n * Gets single bit at position.\n * NOTE: first bit position is 0 (same as arrays)\n * Same as `!!+Array.from(n.toString(2)).reverse()[pos]`\n */\nexport function bitGet(n: bigint, pos: number): bigint {\n  return (n >> BigInt(pos)) & _1n;\n}\n\n/**\n * Sets single bit at position.\n */\nexport function bitSet(n: bigint, pos: number, value: boolean): bigint {\n  return n | ((value ? _1n : _0n) << BigInt(pos));\n}\n\n/**\n * Calculate mask for N bits. Not using ** operator with bigints because of old engines.\n * Same as BigInt(`0b${Array(i).fill('1').join('')}`)\n */\nexport const bitMask = (n: number): bigint => (_1n << BigInt(n)) - _1n;\n\n// DRBG\n\ntype Pred<T> = (v: Uint8Array) => T | undefined;\n/**\n * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n * @returns function that will call DRBG until 2nd arg returns something meaningful\n * @example\n *   const drbg = createHmacDRBG<Key>(32, 32, hmac);\n *   drbg(seed, bytesToKey); // bytesToKey must return Key or undefined\n */\nexport function createHmacDrbg<T>(\n  hashLen: number,\n  qByteLen: number,\n  hmacFn: (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array\n): (seed: Uint8Array, predicate: Pred<T>) => T {\n  if (typeof hashLen !== 'number' || hashLen < 2) throw new Error('hashLen must be a number');\n  if (typeof qByteLen !== 'number' || qByteLen < 2) throw new Error('qByteLen must be a number');\n  if (typeof hmacFn !== 'function') throw new Error('hmacFn must be a function');\n  // Step B, Step C: set hashLen to 8*ceil(hlen/8)\n  const u8n = (len: number) => new Uint8Array(len); // creates Uint8Array\n  const u8of = (byte: number) => Uint8Array.of(byte); // another shortcut\n  let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n  let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same\n  let i = 0; // Iterations counter, will throw when over 1000\n  const reset = () => {\n    v.fill(1);\n    k.fill(0);\n    i = 0;\n  };\n  const h = (...b: Uint8Array[]) => hmacFn(k, v, ...b); // hmac(k)(v, ...values)\n  const reseed = (seed = u8n(0)) => {\n    // HMAC-DRBG reseed() function. Steps D-G\n    k = h(u8of(0x00), seed); // k = hmac(k || v || 0x00 || seed)\n    v = h(); // v = hmac(k || v)\n    if (seed.length === 0) return;\n    k = h(u8of(0x01), seed); // k = hmac(k || v || 0x01 || seed)\n    v = h(); // v = hmac(k || v)\n  };\n  const gen = () => {\n    // HMAC-DRBG generate() function\n    if (i++ >= 1000) throw new Error('drbg: tried 1000 values');\n    let len = 0;\n    const out: Uint8Array[] = [];\n    while (len < qByteLen) {\n      v = h();\n      const sl = v.slice();\n      out.push(sl);\n      len += v.length;\n    }\n    return concatBytes_(...out);\n  };\n  const genUntil = (seed: Uint8Array, pred: Pred<T>): T => {\n    reset();\n    reseed(seed); // Steps D-G\n    let res: T | undefined = undefined; // Step H: grind until k is in [1..n-1]\n    while (!(res = pred(gen()))) reseed();\n    reset();\n    return res;\n  };\n  return genUntil;\n}\n\n// Validating curves and fields\n\nconst validatorFns = {\n  bigint: (val: any): boolean => typeof val === 'bigint',\n  function: (val: any): boolean => typeof val === 'function',\n  boolean: (val: any): boolean => typeof val === 'boolean',\n  string: (val: any): boolean => typeof val === 'string',\n  stringOrUint8Array: (val: any): boolean => typeof val === 'string' || isBytes_(val),\n  isSafeInteger: (val: any): boolean => Number.isSafeInteger(val),\n  array: (val: any): boolean => Array.isArray(val),\n  field: (val: any, object: any): any => (object as any).Fp.isValid(val),\n  hash: (val: any): boolean => typeof val === 'function' && Number.isSafeInteger(val.outputLen),\n} as const;\ntype Validator = keyof typeof validatorFns;\ntype ValMap<T extends Record<string, any>> = { [K in keyof T]?: Validator };\n// type Record<K extends string | number | symbol, T> = { [P in K]: T; }\n\nexport function validateObject<T extends Record<string, any>>(\n  object: T,\n  validators: ValMap<T>,\n  optValidators: ValMap<T> = {}\n): T {\n  const checkField = (fieldName: keyof T, type: Validator, isOptional: boolean) => {\n    const checkVal = validatorFns[type];\n    if (typeof checkVal !== 'function') throw new Error('invalid validator function');\n\n    const val = object[fieldName as keyof typeof object];\n    if (isOptional && val === undefined) return;\n    if (!checkVal(val, object)) {\n      throw new Error(\n        'param ' + String(fieldName) + ' is invalid. Expected ' + type + ', got ' + val\n      );\n    }\n  };\n  for (const [fieldName, type] of Object.entries(validators)) checkField(fieldName, type!, false);\n  for (const [fieldName, type] of Object.entries(optValidators)) checkField(fieldName, type!, true);\n  return object;\n}\n// validate type tests\n// const o: { a: number; b: number; c: number } = { a: 1, b: 5, c: 6 };\n// const z0 = validateObject(o, { a: 'isSafeInteger' }, { c: 'bigint' }); // Ok!\n// // Should fail type-check\n// const z1 = validateObject(o, { a: 'tmp' }, { c: 'zz' });\n// const z2 = validateObject(o, { a: 'isSafeInteger' }, { c: 'zz' });\n// const z3 = validateObject(o, { test: 'boolean', z: 'bug' });\n// const z4 = validateObject(o, { a: 'boolean', z: 'bug' });\n\nexport function isHash(val: CHash): boolean {\n  return typeof val === 'function' && Number.isSafeInteger(val.outputLen);\n}\nexport function _validateObject(\n  object: Record<string, any>,\n  fields: Record<string, string>,\n  optFields: Record<string, string> = {}\n): void {\n  if (!object || typeof object !== 'object') throw new Error('expected valid options object');\n  type Item = keyof typeof object;\n  function checkField(fieldName: Item, expectedType: string, isOpt: boolean) {\n    const val = object[fieldName];\n    if (isOpt && val === undefined) return;\n    const current = typeof val;\n    if (current !== expectedType || val === null)\n      throw new Error(`param \"${fieldName}\" is invalid: expected ${expectedType}, got ${current}`);\n  }\n  Object.entries(fields).forEach(([k, v]) => checkField(k, v, false));\n  Object.entries(optFields).forEach(([k, v]) => checkField(k, v, true));\n}\n\n/**\n * throws not implemented error\n */\nexport const notImplemented = (): never => {\n  throw new Error('not implemented');\n};\n\n/**\n * Memoizes (caches) computation result.\n * Uses WeakMap: the value is going auto-cleaned by GC after last reference is removed.\n */\nexport function memoized<T extends object, R, O extends any[]>(\n  fn: (arg: T, ...args: O) => R\n): (arg: T, ...args: O) => R {\n  const map = new WeakMap<T, R>();\n  return (arg: T, ...args: O): R => {\n    const val = map.get(arg);\n    if (val !== undefined) return val;\n    const computed = fn(arg, ...args);\n    map.set(arg, computed);\n    return computed;\n  };\n}\n","/**\n * Utils for modular division and fields.\n * Field over 11 is a finite (Galois) field is integer number operations `mod 11`.\n * There is no division: it is replaced by modular multiplicative inverse.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport {\n  _validateObject,\n  anumber,\n  bitMask,\n  bytesToNumberBE,\n  bytesToNumberLE,\n  ensureBytes,\n  numberToBytesBE,\n  numberToBytesLE,\n} from '../utils.ts';\n\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = /* @__PURE__ */ BigInt(2), _3n = /* @__PURE__ */ BigInt(3);\n// prettier-ignore\nconst _4n = /* @__PURE__ */ BigInt(4), _5n = /* @__PURE__ */ BigInt(5), _7n = /* @__PURE__ */ BigInt(7);\n// prettier-ignore\nconst _8n = /* @__PURE__ */ BigInt(8), _9n = /* @__PURE__ */ BigInt(9), _16n = /* @__PURE__ */ BigInt(16);\n\n// Calculates a modulo b\nexport function mod(a: bigint, b: bigint): bigint {\n  const result = a % b;\n  return result >= _0n ? result : b + result;\n}\n/**\n * Efficiently raise num to power and do modular division.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n * @example\n * pow(2n, 6n, 11n) // 64n % 11n == 9n\n */\nexport function pow(num: bigint, power: bigint, modulo: bigint): bigint {\n  return FpPow(Field(modulo), num, power);\n}\n\n/** Does `x^(2^power)` mod p. `pow2(30, 4)` == `30^(2^4)` */\nexport function pow2(x: bigint, power: bigint, modulo: bigint): bigint {\n  let res = x;\n  while (power-- > _0n) {\n    res *= res;\n    res %= modulo;\n  }\n  return res;\n}\n\n/**\n * Inverses number over modulo.\n * Implemented using [Euclidean GCD](https://brilliant.org/wiki/extended-euclidean-algorithm/).\n */\nexport function invert(number: bigint, modulo: bigint): bigint {\n  if (number === _0n) throw new Error('invert: expected non-zero number');\n  if (modulo <= _0n) throw new Error('invert: expected positive modulus, got ' + modulo);\n  // Fermat's little theorem \"CT-like\" version inv(n) = n^(m-2) mod m is 30x slower.\n  let a = mod(number, modulo);\n  let b = modulo;\n  // prettier-ignore\n  let x = _0n, y = _1n, u = _1n, v = _0n;\n  while (a !== _0n) {\n    // JIT applies optimization if those two lines follow each other\n    const q = b / a;\n    const r = b % a;\n    const m = x - u * q;\n    const n = y - v * q;\n    // prettier-ignore\n    b = a, a = r, x = u, y = v, u = m, v = n;\n  }\n  const gcd = b;\n  if (gcd !== _1n) throw new Error('invert: does not exist');\n  return mod(x, modulo);\n}\n\nfunction assertIsSquare<T>(Fp: IField<T>, root: T, n: T): void {\n  if (!Fp.eql(Fp.sqr(root), n)) throw new Error('Cannot find square root');\n}\n\n// Not all roots are possible! Example which will throw:\n// const NUM =\n// n = 72057594037927816n;\n// Fp = Field(BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab'));\nfunction sqrt3mod4<T>(Fp: IField<T>, n: T) {\n  const p1div4 = (Fp.ORDER + _1n) / _4n;\n  const root = Fp.pow(n, p1div4);\n  assertIsSquare(Fp, root, n);\n  return root;\n}\n\nfunction sqrt5mod8<T>(Fp: IField<T>, n: T) {\n  const p5div8 = (Fp.ORDER - _5n) / _8n;\n  const n2 = Fp.mul(n, _2n);\n  const v = Fp.pow(n2, p5div8);\n  const nv = Fp.mul(n, v);\n  const i = Fp.mul(Fp.mul(nv, _2n), v);\n  const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));\n  assertIsSquare(Fp, root, n);\n  return root;\n}\n\n// Based on RFC9380, Kong algorithm\n// prettier-ignore\nfunction sqrt9mod16(P: bigint): <T>(Fp: IField<T>, n: T) => T {\n  const Fp_ = Field(P);\n  const tn = tonelliShanks(P);\n  const c1 = tn(Fp_, Fp_.neg(Fp_.ONE));//  1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F\n  const c2 = tn(Fp_, c1);              //  2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F\n  const c3 = tn(Fp_, Fp_.neg(c1));     //  3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F\n  const c4 = (P + _7n) / _16n;         //  4. c4 = (q + 7) / 16        # Integer arithmetic\n  return <T>(Fp: IField<T>, n: T) => {\n    let tv1 = Fp.pow(n, c4);           //  1. tv1 = x^c4\n    let tv2 = Fp.mul(tv1, c1);         //  2. tv2 = c1 * tv1\n    const tv3 = Fp.mul(tv1, c2);       //  3. tv3 = c2 * tv1\n    const tv4 = Fp.mul(tv1, c3);       //  4. tv4 = c3 * tv1\n    const e1 = Fp.eql(Fp.sqr(tv2), n); //  5.  e1 = (tv2^2) == x\n    const e2 = Fp.eql(Fp.sqr(tv3), n); //  6.  e2 = (tv3^2) == x\n    tv1 = Fp.cmov(tv1, tv2, e1);       //  7. tv1 = CMOV(tv1, tv2, e1)  # Select tv2 if (tv2^2) == x\n    tv2 = Fp.cmov(tv4, tv3, e2);       //  8. tv2 = CMOV(tv4, tv3, e2)  # Select tv3 if (tv3^2) == x\n    const e3 = Fp.eql(Fp.sqr(tv2), n); //  9.  e3 = (tv2^2) == x\n    const root = Fp.cmov(tv1, tv2, e3);// 10.  z = CMOV(tv1, tv2, e3)   # Select sqrt from tv1 & tv2\n    assertIsSquare(Fp, root, n);\n    return root;\n  };\n}\n\n/**\n * Tonelli-Shanks square root search algorithm.\n * 1. https://eprint.iacr.org/2012/685.pdf (page 12)\n * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks\n * @param P field order\n * @returns function that takes field Fp (created from P) and number n\n */\nexport function tonelliShanks(P: bigint): <T>(Fp: IField<T>, n: T) => T {\n  // Initialization (precomputation).\n  // Caching initialization could boost perf by 7%.\n  if (P < _3n) throw new Error('sqrt is not defined for small field');\n  // Factor P - 1 = Q * 2^S, where Q is odd\n  let Q = P - _1n;\n  let S = 0;\n  while (Q % _2n === _0n) {\n    Q /= _2n;\n    S++;\n  }\n\n  // Find the first quadratic non-residue Z >= 2\n  let Z = _2n;\n  const _Fp = Field(P);\n  while (FpLegendre(_Fp, Z) === 1) {\n    // Basic primality test for P. After x iterations, chance of\n    // not finding quadratic non-residue is 2^x, so 2^1000.\n    if (Z++ > 1000) throw new Error('Cannot find square root: probably non-prime P');\n  }\n  // Fast-path; usually done before Z, but we do \"primality test\".\n  if (S === 1) return sqrt3mod4;\n\n  // Slow-path\n  // TODO: test on Fp2 and others\n  let cc = _Fp.pow(Z, Q); // c = z^Q\n  const Q1div2 = (Q + _1n) / _2n;\n  return function tonelliSlow<T>(Fp: IField<T>, n: T): T {\n    if (Fp.is0(n)) return n;\n    // Check if n is a quadratic residue using Legendre symbol\n    if (FpLegendre(Fp, n) !== 1) throw new Error('Cannot find square root');\n\n    // Initialize variables for the main loop\n    let M = S;\n    let c = Fp.mul(Fp.ONE, cc); // c = z^Q, move cc from field _Fp into field Fp\n    let t = Fp.pow(n, Q); // t = n^Q, first guess at the fudge factor\n    let R = Fp.pow(n, Q1div2); // R = n^((Q+1)/2), first guess at the square root\n\n    // Main loop\n    // while t != 1\n    while (!Fp.eql(t, Fp.ONE)) {\n      if (Fp.is0(t)) return Fp.ZERO; // if t=0 return R=0\n      let i = 1;\n\n      // Find the smallest i >= 1 such that t^(2^i) ≡ 1 (mod P)\n      let t_tmp = Fp.sqr(t); // t^(2^1)\n      while (!Fp.eql(t_tmp, Fp.ONE)) {\n        i++;\n        t_tmp = Fp.sqr(t_tmp); // t^(2^2)...\n        if (i === M) throw new Error('Cannot find square root');\n      }\n\n      // Calculate the exponent for b: 2^(M - i - 1)\n      const exponent = _1n << BigInt(M - i - 1); // bigint is important\n      const b = Fp.pow(c, exponent); // b = 2^(M - i - 1)\n\n      // Update variables\n      M = i;\n      c = Fp.sqr(b); // c = b^2\n      t = Fp.mul(t, c); // t = (t * b^2)\n      R = Fp.mul(R, b); // R = R*b\n    }\n    return R;\n  };\n}\n\n/**\n * Square root for a finite field. Will try optimized versions first:\n *\n * 1. P ≡ 3 (mod 4)\n * 2. P ≡ 5 (mod 8)\n * 3. P ≡ 9 (mod 16)\n * 4. Tonelli-Shanks algorithm\n *\n * Different algorithms can give different roots, it is up to user to decide which one they want.\n * For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).\n */\nexport function FpSqrt(P: bigint): <T>(Fp: IField<T>, n: T) => T {\n  // P ≡ 3 (mod 4) => √n = n^((P+1)/4)\n  if (P % _4n === _3n) return sqrt3mod4;\n  // P ≡ 5 (mod 8) => Atkin algorithm, page 10 of https://eprint.iacr.org/2012/685.pdf\n  if (P % _8n === _5n) return sqrt5mod8;\n  // P ≡ 9 (mod 16) => Kong algorithm, page 11 of https://eprint.iacr.org/2012/685.pdf (algorithm 4)\n  if (P % _16n === _9n) return sqrt9mod16(P);\n  // Tonelli-Shanks algorithm\n  return tonelliShanks(P);\n}\n\n// Little-endian check for first LE bit (last BE bit);\nexport const isNegativeLE = (num: bigint, modulo: bigint): boolean =>\n  (mod(num, modulo) & _1n) === _1n;\n\n/** Field is not always over prime: for example, Fp2 has ORDER(q)=p^m. */\nexport interface IField<T> {\n  ORDER: bigint;\n  isLE: boolean;\n  BYTES: number;\n  BITS: number;\n  MASK: bigint;\n  ZERO: T;\n  ONE: T;\n  // 1-arg\n  create: (num: T) => T;\n  isValid: (num: T) => boolean;\n  is0: (num: T) => boolean;\n  isValidNot0: (num: T) => boolean;\n  neg(num: T): T;\n  inv(num: T): T;\n  sqrt(num: T): T;\n  sqr(num: T): T;\n  // 2-args\n  eql(lhs: T, rhs: T): boolean;\n  add(lhs: T, rhs: T): T;\n  sub(lhs: T, rhs: T): T;\n  mul(lhs: T, rhs: T | bigint): T;\n  pow(lhs: T, power: bigint): T;\n  div(lhs: T, rhs: T | bigint): T;\n  // N for NonNormalized (for now)\n  addN(lhs: T, rhs: T): T;\n  subN(lhs: T, rhs: T): T;\n  mulN(lhs: T, rhs: T | bigint): T;\n  sqrN(num: T): T;\n\n  // Optional\n  // Should be same as sgn0 function in\n  // [RFC9380](https://www.rfc-editor.org/rfc/rfc9380#section-4.1).\n  // NOTE: sgn0 is 'negative in LE', which is same as odd. And negative in LE is kinda strange definition anyway.\n  isOdd?(num: T): boolean; // Odd instead of even since we have it for Fp2\n  allowedLengths?: number[];\n  // legendre?(num: T): T;\n  invertBatch: (lst: T[]) => T[];\n  toBytes(num: T): Uint8Array;\n  fromBytes(bytes: Uint8Array, skipValidation?: boolean): T;\n  // If c is False, CMOV returns a, otherwise it returns b.\n  cmov(a: T, b: T, c: boolean): T;\n}\n// prettier-ignore\nconst FIELD_FIELDS = [\n  'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr',\n  'eql', 'add', 'sub', 'mul', 'pow', 'div',\n  'addN', 'subN', 'mulN', 'sqrN'\n] as const;\nexport function validateField<T>(field: IField<T>): IField<T> {\n  const initial = {\n    ORDER: 'bigint',\n    MASK: 'bigint',\n    BYTES: 'number',\n    BITS: 'number',\n  } as Record<string, string>;\n  const opts = FIELD_FIELDS.reduce((map, val: string) => {\n    map[val] = 'function';\n    return map;\n  }, initial);\n  _validateObject(field, opts);\n  // const max = 16384;\n  // if (field.BYTES < 1 || field.BYTES > max) throw new Error('invalid field');\n  // if (field.BITS < 1 || field.BITS > 8 * max) throw new Error('invalid field');\n  return field;\n}\n\n// Generic field functions\n\n/**\n * Same as `pow` but for Fp: non-constant-time.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n */\nexport function FpPow<T>(Fp: IField<T>, num: T, power: bigint): T {\n  if (power < _0n) throw new Error('invalid exponent, negatives unsupported');\n  if (power === _0n) return Fp.ONE;\n  if (power === _1n) return num;\n  let p = Fp.ONE;\n  let d = num;\n  while (power > _0n) {\n    if (power & _1n) p = Fp.mul(p, d);\n    d = Fp.sqr(d);\n    power >>= _1n;\n  }\n  return p;\n}\n\n/**\n * Efficiently invert an array of Field elements.\n * Exception-free. Will return `undefined` for 0 elements.\n * @param passZero map 0 to 0 (instead of undefined)\n */\nexport function FpInvertBatch<T>(Fp: IField<T>, nums: T[], passZero = false): T[] {\n  const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : undefined);\n  // Walk from first to last, multiply them by each other MOD p\n  const multipliedAcc = nums.reduce((acc, num, i) => {\n    if (Fp.is0(num)) return acc;\n    inverted[i] = acc;\n    return Fp.mul(acc, num);\n  }, Fp.ONE);\n  // Invert last element\n  const invertedAcc = Fp.inv(multipliedAcc);\n  // Walk from last to first, multiply them by inverted each other MOD p\n  nums.reduceRight((acc, num, i) => {\n    if (Fp.is0(num)) return acc;\n    inverted[i] = Fp.mul(acc, inverted[i]);\n    return Fp.mul(acc, num);\n  }, invertedAcc);\n  return inverted;\n}\n\n// TODO: remove\nexport function FpDiv<T>(Fp: IField<T>, lhs: T, rhs: T | bigint): T {\n  return Fp.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, Fp.ORDER) : Fp.inv(rhs));\n}\n\n/**\n * Legendre symbol.\n * Legendre constant is used to calculate Legendre symbol (a | p)\n * which denotes the value of a^((p-1)/2) (mod p).\n *\n * * (a | p) ≡ 1    if a is a square (mod p), quadratic residue\n * * (a | p) ≡ -1   if a is not a square (mod p), quadratic non residue\n * * (a | p) ≡ 0    if a ≡ 0 (mod p)\n */\nexport function FpLegendre<T>(Fp: IField<T>, n: T): -1 | 0 | 1 {\n  // We can use 3rd argument as optional cache of this value\n  // but seems unneeded for now. The operation is very fast.\n  const p1mod2 = (Fp.ORDER - _1n) / _2n;\n  const powered = Fp.pow(n, p1mod2);\n  const yes = Fp.eql(powered, Fp.ONE);\n  const zero = Fp.eql(powered, Fp.ZERO);\n  const no = Fp.eql(powered, Fp.neg(Fp.ONE));\n  if (!yes && !zero && !no) throw new Error('invalid Legendre symbol result');\n  return yes ? 1 : zero ? 0 : -1;\n}\n\n// This function returns True whenever the value x is a square in the field F.\nexport function FpIsSquare<T>(Fp: IField<T>, n: T): boolean {\n  const l = FpLegendre(Fp, n);\n  return l === 1;\n}\n\nexport type NLength = { nByteLength: number; nBitLength: number };\n// CURVE.n lengths\nexport function nLength(n: bigint, nBitLength?: number): NLength {\n  // Bit size, byte size of CURVE.n\n  if (nBitLength !== undefined) anumber(nBitLength);\n  const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length;\n  const nByteLength = Math.ceil(_nBitLength / 8);\n  return { nBitLength: _nBitLength, nByteLength };\n}\n\ntype FpField = IField<bigint> & Required<Pick<IField<bigint>, 'isOdd'>>;\ntype SqrtFn = (n: bigint) => bigint;\ntype FieldOpts = Partial<{\n  sqrt: SqrtFn;\n  isLE: boolean;\n  BITS: number;\n  modFromBytes: boolean; // bls12-381 requires mod(n) instead of rejecting keys >= n\n  allowedLengths?: readonly number[]; // for P521 (adds padding for smaller sizes)\n}>;\n/**\n * Creates a finite field. Major performance optimizations:\n * * 1. Denormalized operations like mulN instead of mul.\n * * 2. Identical object shape: never add or remove keys.\n * * 3. `Object.freeze`.\n * Fragile: always run a benchmark on a change.\n * Security note: operations don't check 'isValid' for all elements for performance reasons,\n * it is caller responsibility to check this.\n * This is low-level code, please make sure you know what you're doing.\n *\n * Note about field properties:\n * * CHARACTERISTIC p = prime number, number of elements in main subgroup.\n * * ORDER q = similar to cofactor in curves, may be composite `q = p^m`.\n *\n * @param ORDER field order, probably prime, or could be composite\n * @param bitLen how many bits the field consumes\n * @param isLE (default: false) if encoding / decoding should be in little-endian\n * @param redef optional faster redefinitions of sqrt and other methods\n */\nexport function Field(\n  ORDER: bigint,\n  bitLenOrOpts?: number | FieldOpts, // TODO: use opts only in v2?\n  isLE = false,\n  opts: { sqrt?: SqrtFn } = {}\n): Readonly<FpField> {\n  if (ORDER <= _0n) throw new Error('invalid field: expected ORDER > 0, got ' + ORDER);\n  let _nbitLength: number | undefined = undefined;\n  let _sqrt: SqrtFn | undefined = undefined;\n  let modFromBytes: boolean = false;\n  let allowedLengths: undefined | readonly number[] = undefined;\n  if (typeof bitLenOrOpts === 'object' && bitLenOrOpts != null) {\n    if (opts.sqrt || isLE) throw new Error('cannot specify opts in two arguments');\n    const _opts = bitLenOrOpts;\n    if (_opts.BITS) _nbitLength = _opts.BITS;\n    if (_opts.sqrt) _sqrt = _opts.sqrt;\n    if (typeof _opts.isLE === 'boolean') isLE = _opts.isLE;\n    if (typeof _opts.modFromBytes === 'boolean') modFromBytes = _opts.modFromBytes;\n    allowedLengths = _opts.allowedLengths;\n  } else {\n    if (typeof bitLenOrOpts === 'number') _nbitLength = bitLenOrOpts;\n    if (opts.sqrt) _sqrt = opts.sqrt;\n  }\n  const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, _nbitLength);\n  if (BYTES > 2048) throw new Error('invalid field: expected ORDER of <= 2048 bytes');\n  let sqrtP: ReturnType<typeof FpSqrt>; // cached sqrtP\n  const f: Readonly<FpField> = Object.freeze({\n    ORDER,\n    isLE,\n    BITS,\n    BYTES,\n    MASK: bitMask(BITS),\n    ZERO: _0n,\n    ONE: _1n,\n    allowedLengths: allowedLengths,\n    create: (num) => mod(num, ORDER),\n    isValid: (num) => {\n      if (typeof num !== 'bigint')\n        throw new Error('invalid field element: expected bigint, got ' + typeof num);\n      return _0n <= num && num < ORDER; // 0 is valid element, but it's not invertible\n    },\n    is0: (num) => num === _0n,\n    // is valid and invertible\n    isValidNot0: (num: bigint) => !f.is0(num) && f.isValid(num),\n    isOdd: (num) => (num & _1n) === _1n,\n    neg: (num) => mod(-num, ORDER),\n    eql: (lhs, rhs) => lhs === rhs,\n\n    sqr: (num) => mod(num * num, ORDER),\n    add: (lhs, rhs) => mod(lhs + rhs, ORDER),\n    sub: (lhs, rhs) => mod(lhs - rhs, ORDER),\n    mul: (lhs, rhs) => mod(lhs * rhs, ORDER),\n    pow: (num, power) => FpPow(f, num, power),\n    div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),\n\n    // Same as above, but doesn't normalize\n    sqrN: (num) => num * num,\n    addN: (lhs, rhs) => lhs + rhs,\n    subN: (lhs, rhs) => lhs - rhs,\n    mulN: (lhs, rhs) => lhs * rhs,\n\n    inv: (num) => invert(num, ORDER),\n    sqrt:\n      _sqrt ||\n      ((n) => {\n        if (!sqrtP) sqrtP = FpSqrt(ORDER);\n        return sqrtP(f, n);\n      }),\n    toBytes: (num) => (isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES)),\n    fromBytes: (bytes, skipValidation = true) => {\n      if (allowedLengths) {\n        if (!allowedLengths.includes(bytes.length) || bytes.length > BYTES) {\n          throw new Error(\n            'Field.fromBytes: expected ' + allowedLengths + ' bytes, got ' + bytes.length\n          );\n        }\n        const padded = new Uint8Array(BYTES);\n        // isLE add 0 to right, !isLE to the left.\n        padded.set(bytes, isLE ? 0 : padded.length - bytes.length);\n        bytes = padded;\n      }\n      if (bytes.length !== BYTES)\n        throw new Error('Field.fromBytes: expected ' + BYTES + ' bytes, got ' + bytes.length);\n      let scalar = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);\n      if (modFromBytes) scalar = mod(scalar, ORDER);\n      if (!skipValidation)\n        if (!f.isValid(scalar)) throw new Error('invalid field element: outside of range 0..ORDER');\n      // NOTE: we don't validate scalar here, please use isValid. This done such way because some\n      // protocol may allow non-reduced scalar that reduced later or changed some other way.\n      return scalar;\n    },\n    // TODO: we don't need it here, move out to separate fn\n    invertBatch: (lst) => FpInvertBatch(f, lst),\n    // We can't move this out because Fp6, Fp12 implement it\n    // and it's unclear what to return in there.\n    cmov: (a, b, c) => (c ? b : a),\n  } as FpField);\n  return Object.freeze(f);\n}\n\n// Generic random scalar, we can do same for other fields if via Fp2.mul(Fp2.ONE, Fp2.random)?\n// This allows unsafe methods like ignore bias or zero. These unsafe, but often used in different protocols (if deterministic RNG).\n// which mean we cannot force this via opts.\n// Not sure what to do with randomBytes, we can accept it inside opts if wanted.\n// Probably need to export getMinHashLength somewhere?\n// random(bytes?: Uint8Array, unsafeAllowZero = false, unsafeAllowBias = false) {\n//   const LEN = !unsafeAllowBias ? getMinHashLength(ORDER) : BYTES;\n//   if (bytes === undefined) bytes = randomBytes(LEN); // _opts.randomBytes?\n//   const num = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);\n//   // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0\n//   const reduced = unsafeAllowZero ? mod(num, ORDER) : mod(num, ORDER - _1n) + _1n;\n//   return reduced;\n// },\n\nexport function FpSqrtOdd<T>(Fp: IField<T>, elm: T): T {\n  if (!Fp.isOdd) throw new Error(\"Field doesn't have isOdd\");\n  const root = Fp.sqrt(elm);\n  return Fp.isOdd(root) ? root : Fp.neg(root);\n}\n\nexport function FpSqrtEven<T>(Fp: IField<T>, elm: T): T {\n  if (!Fp.isOdd) throw new Error(\"Field doesn't have isOdd\");\n  const root = Fp.sqrt(elm);\n  return Fp.isOdd(root) ? Fp.neg(root) : root;\n}\n\n/**\n * \"Constant-time\" private key generation utility.\n * Same as mapKeyToField, but accepts less bytes (40 instead of 48 for 32-byte field).\n * Which makes it slightly more biased, less secure.\n * @deprecated use `mapKeyToField` instead\n */\nexport function hashToPrivateScalar(\n  hash: string | Uint8Array,\n  groupOrder: bigint,\n  isLE = false\n): bigint {\n  hash = ensureBytes('privateHash', hash);\n  const hashLen = hash.length;\n  const minLen = nLength(groupOrder).nByteLength + 8;\n  if (minLen < 24 || hashLen < minLen || hashLen > 1024)\n    throw new Error(\n      'hashToPrivateScalar: expected ' + minLen + '-1024 bytes of input, got ' + hashLen\n    );\n  const num = isLE ? bytesToNumberLE(hash) : bytesToNumberBE(hash);\n  return mod(num, groupOrder - _1n) + _1n;\n}\n\n/**\n * Returns total number of bytes consumed by the field element.\n * For example, 32 bytes for usual 256-bit weierstrass curve.\n * @param fieldOrder number of field elements, usually CURVE.n\n * @returns byte length of field\n */\nexport function getFieldBytesLength(fieldOrder: bigint): number {\n  if (typeof fieldOrder !== 'bigint') throw new Error('field order must be bigint');\n  const bitLength = fieldOrder.toString(2).length;\n  return Math.ceil(bitLength / 8);\n}\n\n/**\n * Returns minimal amount of bytes that can be safely reduced\n * by field order.\n * Should be 2^-128 for 128-bit curve such as P256.\n * @param fieldOrder number of field elements, usually CURVE.n\n * @returns byte length of target hash\n */\nexport function getMinHashLength(fieldOrder: bigint): number {\n  const length = getFieldBytesLength(fieldOrder);\n  return length + Math.ceil(length / 2);\n}\n\n/**\n * \"Constant-time\" private key generation utility.\n * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF\n * and convert them into private scalar, with the modulo bias being negligible.\n * Needs at least 48 bytes of input for 32-byte private key.\n * https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/\n * FIPS 186-5, A.2 https://csrc.nist.gov/publications/detail/fips/186/5/final\n * RFC 9380, https://www.rfc-editor.org/rfc/rfc9380#section-5\n * @param hash hash output from SHA3 or a similar function\n * @param groupOrder size of subgroup - (e.g. secp256k1.CURVE.n)\n * @param isLE interpret hash bytes as LE num\n * @returns valid private scalar\n */\nexport function mapHashToField(key: Uint8Array, fieldOrder: bigint, isLE = false): Uint8Array {\n  const len = key.length;\n  const fieldLen = getFieldBytesLength(fieldOrder);\n  const minLen = getMinHashLength(fieldOrder);\n  // No small numbers: need to understand bias story. No huge numbers: easier to detect JS timings.\n  if (len < 16 || len < minLen || len > 1024)\n    throw new Error('expected ' + minLen + '-1024 bytes of input, got ' + len);\n  const num = isLE ? bytesToNumberLE(key) : bytesToNumberBE(key);\n  // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0\n  const reduced = mod(num, fieldOrder - _1n) + _1n;\n  return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);\n}\n","/**\n * Methods for elliptic curve multiplication by scalars.\n * Contains wNAF, pippenger.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { bitLen, bitMask, validateObject } from '../utils.ts';\nimport { Field, FpInvertBatch, nLength, validateField, type IField } from './modular.ts';\n\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\n\nexport type AffinePoint<T> = {\n  x: T;\n  y: T;\n} & { Z?: never };\n\n// This was initialy do this way to re-use montgomery ladder in field (add->mul,double->sqr), but\n// that didn't happen and there is probably not much reason to have separate Group like this?\nexport interface Group<T extends Group<T>> {\n  double(): T;\n  negate(): T;\n  add(other: T): T;\n  subtract(other: T): T;\n  equals(other: T): boolean;\n  multiply(scalar: bigint): T;\n  toAffine?(invertedZ?: any): AffinePoint<any>;\n}\n\n// We can't \"abstract out\" coordinates (X, Y, Z; and T in Edwards): argument names of constructor\n// are not accessible. See Typescript gh-56093, gh-41594.\n//\n// We have to use recursive types, so it will return actual point, not constained `CurvePoint`.\n// If, at any point, P is `any`, it will erase all types and replace it\n// with `any`, because of recursion, `any implements CurvePoint`,\n// but we lose all constrains on methods.\n\n/** Base interface for all elliptic curve Points. */\nexport interface CurvePoint<F, P extends CurvePoint<F, P>> extends Group<P> {\n  /** Affine x coordinate. Different from projective / extended X coordinate. */\n  x: F;\n  /** Affine y coordinate. Different from projective / extended Y coordinate. */\n  y: F;\n  Z?: F;\n  double(): P;\n  negate(): P;\n  add(other: P): P;\n  subtract(other: P): P;\n  equals(other: P): boolean;\n  multiply(scalar: bigint): P;\n  assertValidity(): void;\n  clearCofactor(): P;\n  is0(): boolean;\n  isTorsionFree(): boolean;\n  isSmallOrder(): boolean;\n  multiplyUnsafe(scalar: bigint): P;\n  /**\n   * Massively speeds up `p.multiply(n)` by using precompute tables (caching). See {@link wNAF}.\n   * @param isLazy calculate cache now. Default (true) ensures it's deferred to first `multiply()`\n   */\n  precompute(windowSize?: number, isLazy?: boolean): P;\n  /** Converts point to 2D xy affine coordinates */\n  toAffine(invertedZ?: F): AffinePoint<F>;\n  toBytes(): Uint8Array;\n  toHex(): string;\n}\n\n/** Base interface for all elliptic curve Point constructors. */\nexport interface CurvePointCons<P extends CurvePoint<any, P>> {\n  [Symbol.hasInstance]: (item: unknown) => boolean;\n  BASE: P;\n  ZERO: P;\n  /** Field for basic curve math */\n  Fp: IField<P_F<P>>;\n  /** Scalar field, for scalars in multiply and others */\n  Fn: IField<bigint>;\n  /** Creates point from x, y. Does NOT validate if the point is valid. Use `.assertValidity()`. */\n  fromAffine(p: AffinePoint<P_F<P>>): P;\n  fromBytes(bytes: Uint8Array): P;\n  fromHex(hex: Uint8Array | string): P;\n}\n\n// Type inference helpers: PC - PointConstructor, P - Point, Fp - Field element\n// Short names, because we use them a lot in result types:\n// * we can't do 'P = GetCurvePoint<PC>': this is default value and doesn't constrain anything\n// * we can't do 'type X = GetCurvePoint<PC>': it won't be accesible for arguments/return types\n// * `CurvePointCons<P extends CurvePoint<any, P>>` constraints from interface definition\n//   won't propagate, if `PC extends CurvePointCons<any>`: the P would be 'any', which is incorrect\n// * PC could be super specific with super specific P, which implements CurvePoint<any, P>.\n//   this means we need to do stuff like\n//   `function test<P extends CurvePoint<any, P>, PC extends CurvePointCons<P>>(`\n//   if we want type safety around P, otherwise PC_P<PC> will be any\n\n/** Returns Fp type from Point (P_F<P> == P.F) */\nexport type P_F<P extends CurvePoint<any, P>> = P extends CurvePoint<infer F, P> ? F : never;\n/** Returns Fp type from PointCons (PC_F<PC> == PC.P.F) */\nexport type PC_F<PC extends CurvePointCons<CurvePoint<any, any>>> = PC['Fp']['ZERO'];\n/** Returns Point type from PointCons (PC_P<PC> == PC.P) */\nexport type PC_P<PC extends CurvePointCons<CurvePoint<any, any>>> = PC['ZERO'];\n\n// Ugly hack to get proper type inference, because in typescript fails to infer resursively.\n// The hack allows to do up to 10 chained operations without applying type erasure.\n//\n// Types which won't work:\n// * `CurvePointCons<CurvePoint<any, any>>`, will return `any` after 1 operation\n// * `CurvePointCons<any>: WeierstrassPointCons<bigint> extends CurvePointCons<any> = false`\n// * `P extends CurvePoint, PC extends CurvePointCons<P>`\n//     * It can't infer P from PC alone\n//     * Too many relations between F, P & PC\n//     * It will infer P/F if `arg: CurvePointCons<F, P>`, but will fail if PC is generic\n//     * It will work correctly if there is an additional argument of type P\n//     * But generally, we don't want to parametrize `CurvePointCons` over `F`: it will complicate\n//       types, making them un-inferable\n// prettier-ignore\nexport type PC_ANY = CurvePointCons<\n  CurvePoint<any,\n  CurvePoint<any,\n  CurvePoint<any,\n  CurvePoint<any,\n  CurvePoint<any,\n  CurvePoint<any,\n  CurvePoint<any,\n  CurvePoint<any,\n  CurvePoint<any,\n  CurvePoint<any, any>\n  >>>>>>>>>\n>;\n\nexport interface CurveLengths {\n  secretKey?: number;\n  publicKey?: number;\n  publicKeyUncompressed?: number;\n  publicKeyHasPrefix?: boolean;\n  signature?: number;\n  seed?: number;\n}\nexport type GroupConstructor<T> = {\n  BASE: T;\n  ZERO: T;\n};\n/** @deprecated */\nexport type ExtendedGroupConstructor<T> = GroupConstructor<T> & {\n  Fp: IField<any>;\n  Fn: IField<bigint>;\n  fromAffine(ap: AffinePoint<any>): T;\n};\nexport type Mapper<T> = (i: T[]) => T[];\n\nexport function negateCt<T extends { negate: () => T }>(condition: boolean, item: T): T {\n  const neg = item.negate();\n  return condition ? neg : item;\n}\n\n/**\n * Takes a bunch of Projective Points but executes only one\n * inversion on all of them. Inversion is very slow operation,\n * so this improves performance massively.\n * Optimization: converts a list of projective points to a list of identical points with Z=1.\n */\nexport function normalizeZ<P extends CurvePoint<any, P>, PC extends CurvePointCons<P>>(\n  c: PC,\n  points: P[]\n): P[] {\n  const invertedZs = FpInvertBatch(\n    c.Fp,\n    points.map((p) => p.Z!)\n  );\n  return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));\n}\n\nfunction validateW(W: number, bits: number) {\n  if (!Number.isSafeInteger(W) || W <= 0 || W > bits)\n    throw new Error('invalid window size, expected [1..' + bits + '], got W=' + W);\n}\n\n/** Internal wNAF opts for specific W and scalarBits */\nexport type WOpts = {\n  windows: number;\n  windowSize: number;\n  mask: bigint;\n  maxNumber: number;\n  shiftBy: bigint;\n};\n\nfunction calcWOpts(W: number, scalarBits: number): WOpts {\n  validateW(W, scalarBits);\n  const windows = Math.ceil(scalarBits / W) + 1; // W=8 33. Not 32, because we skip zero\n  const windowSize = 2 ** (W - 1); // W=8 128. Not 256, because we skip zero\n  const maxNumber = 2 ** W; // W=8 256\n  const mask = bitMask(W); // W=8 255 == mask 0b11111111\n  const shiftBy = BigInt(W); // W=8 8\n  return { windows, windowSize, mask, maxNumber, shiftBy };\n}\n\nfunction calcOffsets(n: bigint, window: number, wOpts: WOpts) {\n  const { windowSize, mask, maxNumber, shiftBy } = wOpts;\n  let wbits = Number(n & mask); // extract W bits.\n  let nextN = n >> shiftBy; // shift number by W bits.\n\n  // What actually happens here:\n  // const highestBit = Number(mask ^ (mask >> 1n));\n  // let wbits2 = wbits - 1; // skip zero\n  // if (wbits2 & highestBit) { wbits2 ^= Number(mask); // (~);\n\n  // split if bits > max: +224 => 256-32\n  if (wbits > windowSize) {\n    // we skip zero, which means instead of `>= size-1`, we do `> size`\n    wbits -= maxNumber; // -32, can be maxNumber - wbits, but then we need to set isNeg here.\n    nextN += _1n; // +256 (carry)\n  }\n  const offsetStart = window * windowSize;\n  const offset = offsetStart + Math.abs(wbits) - 1; // -1 because we skip zero\n  const isZero = wbits === 0; // is current window slice a 0?\n  const isNeg = wbits < 0; // is current window slice negative?\n  const isNegF = window % 2 !== 0; // fake random statement for noise\n  const offsetF = offsetStart; // fake offset for noise\n  return { nextN, offset, isZero, isNeg, isNegF, offsetF };\n}\n\nfunction validateMSMPoints(points: any[], c: any) {\n  if (!Array.isArray(points)) throw new Error('array expected');\n  points.forEach((p, i) => {\n    if (!(p instanceof c)) throw new Error('invalid point at index ' + i);\n  });\n}\nfunction validateMSMScalars(scalars: any[], field: any) {\n  if (!Array.isArray(scalars)) throw new Error('array of scalars expected');\n  scalars.forEach((s, i) => {\n    if (!field.isValid(s)) throw new Error('invalid scalar at index ' + i);\n  });\n}\n\n// Since points in different groups cannot be equal (different object constructor),\n// we can have single place to store precomputes.\n// Allows to make points frozen / immutable.\nconst pointPrecomputes = new WeakMap<any, any[]>();\nconst pointWindowSizes = new WeakMap<any, number>();\n\nfunction getW(P: any): number {\n  // To disable precomputes:\n  // return 1;\n  return pointWindowSizes.get(P) || 1;\n}\n\nfunction assert0(n: bigint): void {\n  if (n !== _0n) throw new Error('invalid wNAF');\n}\n\n/**\n * Elliptic curve multiplication of Point by scalar. Fragile.\n * Table generation takes **30MB of ram and 10ms on high-end CPU**,\n * but may take much longer on slow devices. Actual generation will happen on\n * first call of `multiply()`. By default, `BASE` point is precomputed.\n *\n * Scalars should always be less than curve order: this should be checked inside of a curve itself.\n * Creates precomputation tables for fast multiplication:\n * - private scalar is split by fixed size windows of W bits\n * - every window point is collected from window's table & added to accumulator\n * - since windows are different, same point inside tables won't be accessed more than once per calc\n * - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar)\n * - +1 window is neccessary for wNAF\n * - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication\n *\n * @todo Research returning 2d JS array of windows, instead of a single window.\n * This would allow windows to be in different memory locations\n */\nexport class wNAF<PC extends PC_ANY> {\n  private readonly BASE: PC_P<PC>;\n  private readonly ZERO: PC_P<PC>;\n  private readonly Fn: PC['Fn'];\n  readonly bits: number;\n\n  // Parametrized with a given Point class (not individual point)\n  constructor(Point: PC, bits: number) {\n    this.BASE = Point.BASE;\n    this.ZERO = Point.ZERO;\n    this.Fn = Point.Fn;\n    this.bits = bits;\n  }\n\n  // non-const time multiplication ladder\n  _unsafeLadder(elm: PC_P<PC>, n: bigint, p: PC_P<PC> = this.ZERO): PC_P<PC> {\n    let d: PC_P<PC> = elm;\n    while (n > _0n) {\n      if (n & _1n) p = p.add(d);\n      d = d.double();\n      n >>= _1n;\n    }\n    return p;\n  }\n\n  /**\n   * Creates a wNAF precomputation window. Used for caching.\n   * Default window size is set by `utils.precompute()` and is equal to 8.\n   * Number of precomputed points depends on the curve size:\n   * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:\n   * - 𝑊 is the window size\n   * - 𝑛 is the bitlength of the curve order.\n   * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.\n   * @param point Point instance\n   * @param W window size\n   * @returns precomputed point tables flattened to a single array\n   */\n  private precomputeWindow(point: PC_P<PC>, W: number): PC_P<PC>[] {\n    const { windows, windowSize } = calcWOpts(W, this.bits);\n    const points: PC_P<PC>[] = [];\n    let p: PC_P<PC> = point;\n    let base = p;\n    for (let window = 0; window < windows; window++) {\n      base = p;\n      points.push(base);\n      // i=1, bc we skip 0\n      for (let i = 1; i < windowSize; i++) {\n        base = base.add(p);\n        points.push(base);\n      }\n      p = base.double();\n    }\n    return points;\n  }\n\n  /**\n   * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.\n   * More compact implementation:\n   * https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541\n   * @returns real and fake (for const-time) points\n   */\n  private wNAF(W: number, precomputes: PC_P<PC>[], n: bigint): { p: PC_P<PC>; f: PC_P<PC> } {\n    // Scalar should be smaller than field order\n    if (!this.Fn.isValid(n)) throw new Error('invalid scalar');\n    // Accumulators\n    let p = this.ZERO;\n    let f = this.BASE;\n    // This code was first written with assumption that 'f' and 'p' will never be infinity point:\n    // since each addition is multiplied by 2 ** W, it cannot cancel each other. However,\n    // there is negate now: it is possible that negated element from low value\n    // would be the same as high element, which will create carry into next window.\n    // It's not obvious how this can fail, but still worth investigating later.\n    const wo = calcWOpts(W, this.bits);\n    for (let window = 0; window < wo.windows; window++) {\n      // (n === _0n) is handled and not early-exited. isEven and offsetF are used for noise\n      const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);\n      n = nextN;\n      if (isZero) {\n        // bits are 0: add garbage to fake point\n        // Important part for const-time getPublicKey: add random \"noise\" point to f.\n        f = f.add(negateCt(isNegF, precomputes[offsetF]));\n      } else {\n        // bits are 1: add to result point\n        p = p.add(negateCt(isNeg, precomputes[offset]));\n      }\n    }\n    assert0(n);\n    // Return both real and fake points: JIT won't eliminate f.\n    // At this point there is a way to F be infinity-point even if p is not,\n    // which makes it less const-time: around 1 bigint multiply.\n    return { p, f };\n  }\n\n  /**\n   * Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.\n   * @param acc accumulator point to add result of multiplication\n   * @returns point\n   */\n  private wNAFUnsafe(\n    W: number,\n    precomputes: PC_P<PC>[],\n    n: bigint,\n    acc: PC_P<PC> = this.ZERO\n  ): PC_P<PC> {\n    const wo = calcWOpts(W, this.bits);\n    for (let window = 0; window < wo.windows; window++) {\n      if (n === _0n) break; // Early-exit, skip 0 value\n      const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);\n      n = nextN;\n      if (isZero) {\n        // Window bits are 0: skip processing.\n        // Move to next window.\n        continue;\n      } else {\n        const item = precomputes[offset];\n        acc = acc.add(isNeg ? item.negate() : item); // Re-using acc allows to save adds in MSM\n      }\n    }\n    assert0(n);\n    return acc;\n  }\n\n  private getPrecomputes(W: number, point: PC_P<PC>, transform?: Mapper<PC_P<PC>>): PC_P<PC>[] {\n    // Calculate precomputes on a first run, reuse them after\n    let comp = pointPrecomputes.get(point);\n    if (!comp) {\n      comp = this.precomputeWindow(point, W) as PC_P<PC>[];\n      if (W !== 1) {\n        // Doing transform outside of if brings 15% perf hit\n        if (typeof transform === 'function') comp = transform(comp);\n        pointPrecomputes.set(point, comp);\n      }\n    }\n    return comp;\n  }\n\n  cached(\n    point: PC_P<PC>,\n    scalar: bigint,\n    transform?: Mapper<PC_P<PC>>\n  ): { p: PC_P<PC>; f: PC_P<PC> } {\n    const W = getW(point);\n    return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);\n  }\n\n  unsafe(point: PC_P<PC>, scalar: bigint, transform?: Mapper<PC_P<PC>>, prev?: PC_P<PC>): PC_P<PC> {\n    const W = getW(point);\n    if (W === 1) return this._unsafeLadder(point, scalar, prev); // For W=1 ladder is ~x2 faster\n    return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);\n  }\n\n  // We calculate precomputes for elliptic curve point multiplication\n  // using windowed method. This specifies window size and\n  // stores precomputed values. Usually only base point would be precomputed.\n  createCache(P: PC_P<PC>, W: number): void {\n    validateW(W, this.bits);\n    pointWindowSizes.set(P, W);\n    pointPrecomputes.delete(P);\n  }\n\n  hasCache(elm: PC_P<PC>): boolean {\n    return getW(elm) !== 1;\n  }\n}\n\n/**\n * Endomorphism-specific multiplication for Koblitz curves.\n * Cost: 128 dbl, 0-256 adds.\n */\nexport function mulEndoUnsafe<P extends CurvePoint<any, P>, PC extends CurvePointCons<P>>(\n  Point: PC,\n  point: P,\n  k1: bigint,\n  k2: bigint\n): { p1: P; p2: P } {\n  let acc = point;\n  let p1 = Point.ZERO;\n  let p2 = Point.ZERO;\n  while (k1 > _0n || k2 > _0n) {\n    if (k1 & _1n) p1 = p1.add(acc);\n    if (k2 & _1n) p2 = p2.add(acc);\n    acc = acc.double();\n    k1 >>= _1n;\n    k2 >>= _1n;\n  }\n  return { p1, p2 };\n}\n\n/**\n * Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n * 30x faster vs naive addition on L=4096, 10x faster than precomputes.\n * For N=254bit, L=1, it does: 1024 ADD + 254 DBL. For L=5: 1536 ADD + 254 DBL.\n * Algorithmically constant-time (for same L), even when 1 point + scalar, or when scalar = 0.\n * @param c Curve Point constructor\n * @param fieldN field over CURVE.N - important that it's not over CURVE.P\n * @param points array of L curve points\n * @param scalars array of L scalars (aka secret keys / bigints)\n */\nexport function pippenger<P extends CurvePoint<any, P>, PC extends CurvePointCons<P>>(\n  c: PC,\n  fieldN: IField<bigint>,\n  points: P[],\n  scalars: bigint[]\n): P {\n  // If we split scalars by some window (let's say 8 bits), every chunk will only\n  // take 256 buckets even if there are 4096 scalars, also re-uses double.\n  // TODO:\n  // - https://eprint.iacr.org/2024/750.pdf\n  // - https://tches.iacr.org/index.php/TCHES/article/view/10287\n  // 0 is accepted in scalars\n  validateMSMPoints(points, c);\n  validateMSMScalars(scalars, fieldN);\n  const plength = points.length;\n  const slength = scalars.length;\n  if (plength !== slength) throw new Error('arrays of points and scalars must have equal length');\n  // if (plength === 0) throw new Error('array must be of length >= 2');\n  const zero = c.ZERO;\n  const wbits = bitLen(BigInt(plength));\n  let windowSize = 1; // bits\n  if (wbits > 12) windowSize = wbits - 3;\n  else if (wbits > 4) windowSize = wbits - 2;\n  else if (wbits > 0) windowSize = 2;\n  const MASK = bitMask(windowSize);\n  const buckets = new Array(Number(MASK) + 1).fill(zero); // +1 for zero array\n  const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize;\n  let sum = zero;\n  for (let i = lastBits; i >= 0; i -= windowSize) {\n    buckets.fill(zero);\n    for (let j = 0; j < slength; j++) {\n      const scalar = scalars[j];\n      const wbits = Number((scalar >> BigInt(i)) & MASK);\n      buckets[wbits] = buckets[wbits].add(points[j]);\n    }\n    let resI = zero; // not using this will do small speed-up, but will lose ct\n    // Skip first bucket, because it is zero\n    for (let j = buckets.length - 1, sumI = zero; j > 0; j--) {\n      sumI = sumI.add(buckets[j]);\n      resI = resI.add(sumI);\n    }\n    sum = sum.add(resI);\n    if (i !== 0) for (let j = 0; j < windowSize; j++) sum = sum.double();\n  }\n  return sum as P;\n}\n/**\n * Precomputed multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n * @param c Curve Point constructor\n * @param fieldN field over CURVE.N - important that it's not over CURVE.P\n * @param points array of L curve points\n * @returns function which multiplies points with scaars\n */\nexport function precomputeMSMUnsafe<P extends CurvePoint<any, P>, PC extends CurvePointCons<P>>(\n  c: PC,\n  fieldN: IField<bigint>,\n  points: P[],\n  windowSize: number\n): (scalars: bigint[]) => P {\n  /**\n   * Performance Analysis of Window-based Precomputation\n   *\n   * Base Case (256-bit scalar, 8-bit window):\n   * - Standard precomputation requires:\n   *   - 31 additions per scalar × 256 scalars = 7,936 ops\n   *   - Plus 255 summary additions = 8,191 total ops\n   *   Note: Summary additions can be optimized via accumulator\n   *\n   * Chunked Precomputation Analysis:\n   * - Using 32 chunks requires:\n   *   - 255 additions per chunk\n   *   - 256 doublings\n   *   - Total: (255 × 32) + 256 = 8,416 ops\n   *\n   * Memory Usage Comparison:\n   * Window Size | Standard Points | Chunked Points\n   * ------------|-----------------|---------------\n   *     4-bit   |     520         |      15\n   *     8-bit   |    4,224        |     255\n   *    10-bit   |   13,824        |   1,023\n   *    16-bit   |  557,056        |  65,535\n   *\n   * Key Advantages:\n   * 1. Enables larger window sizes due to reduced memory overhead\n   * 2. More efficient for smaller scalar counts:\n   *    - 16 chunks: (16 × 255) + 256 = 4,336 ops\n   *    - ~2x faster than standard 8,191 ops\n   *\n   * Limitations:\n   * - Not suitable for plain precomputes (requires 256 constant doublings)\n   * - Performance degrades with larger scalar counts:\n   *   - Optimal for ~256 scalars\n   *   - Less efficient for 4096+ scalars (Pippenger preferred)\n   */\n  validateW(windowSize, fieldN.BITS);\n  validateMSMPoints(points, c);\n  const zero = c.ZERO;\n  const tableSize = 2 ** windowSize - 1; // table size (without zero)\n  const chunks = Math.ceil(fieldN.BITS / windowSize); // chunks of item\n  const MASK = bitMask(windowSize);\n  const tables = points.map((p: P) => {\n    const res = [];\n    for (let i = 0, acc = p; i < tableSize; i++) {\n      res.push(acc);\n      acc = acc.add(p);\n    }\n    return res;\n  });\n  return (scalars: bigint[]): P => {\n    validateMSMScalars(scalars, fieldN);\n    if (scalars.length > points.length)\n      throw new Error('array of scalars must be smaller than array of points');\n    let res = zero;\n    for (let i = 0; i < chunks; i++) {\n      // No need to double if accumulator is still zero.\n      if (res !== zero) for (let j = 0; j < windowSize; j++) res = res.double();\n      const shiftBy = BigInt(chunks * windowSize - (i + 1) * windowSize);\n      for (let j = 0; j < scalars.length; j++) {\n        const n = scalars[j];\n        const curr = Number((n >> shiftBy) & MASK);\n        if (!curr) continue; // skip zero scalars chunks\n        res = res.add(tables[j][curr - 1]);\n      }\n    }\n    return res;\n  };\n}\n\n// TODO: remove\n/**\n * Generic BasicCurve interface: works even for polynomial fields (BLS): P, n, h would be ok.\n * Though generator can be different (Fp2 / Fp6 for BLS).\n */\nexport type BasicCurve<T> = {\n  Fp: IField<T>; // Field over which we'll do calculations (Fp)\n  n: bigint; // Curve order, total count of valid points in the field\n  nBitLength?: number; // bit length of curve order\n  nByteLength?: number; // byte length of curve order\n  h: bigint; // cofactor. we can assign default=1, but users will just ignore it w/o validation\n  hEff?: bigint; // Number to multiply to clear cofactor\n  Gx: T; // base point X coordinate\n  Gy: T; // base point Y coordinate\n  allowInfinityPoint?: boolean; // bls12-381 requires it. ZERO point is valid, but invalid pubkey\n};\n\n// TODO: remove\n/** @deprecated */\nexport function validateBasic<FP, T>(\n  curve: BasicCurve<FP> & T\n): Readonly<\n  {\n    readonly nBitLength: number;\n    readonly nByteLength: number;\n  } & BasicCurve<FP> &\n    T & {\n      p: bigint;\n    }\n> {\n  validateField(curve.Fp);\n  validateObject(\n    curve,\n    {\n      n: 'bigint',\n      h: 'bigint',\n      Gx: 'field',\n      Gy: 'field',\n    },\n    {\n      nBitLength: 'isSafeInteger',\n      nByteLength: 'isSafeInteger',\n    }\n  );\n  // Set defaults\n  return Object.freeze({\n    ...nLength(curve.n, curve.nBitLength),\n    ...curve,\n    ...{ p: curve.Fp.ORDER },\n  } as const);\n}\n\nexport type ValidCurveParams<T> = {\n  p: bigint;\n  n: bigint;\n  h: bigint;\n  a: T;\n  b?: T;\n  d?: T;\n  Gx: T;\n  Gy: T;\n};\n\nfunction createField<T>(order: bigint, field?: IField<T>, isLE?: boolean): IField<T> {\n  if (field) {\n    if (field.ORDER !== order) throw new Error('Field.ORDER must match order: Fp == p, Fn == n');\n    validateField(field);\n    return field;\n  } else {\n    return Field(order, { isLE }) as unknown as IField<T>;\n  }\n}\nexport type FpFn<T> = { Fp: IField<T>; Fn: IField<bigint> };\n\n/** Validates CURVE opts and creates fields */\nexport function _createCurveFields<T>(\n  type: 'weierstrass' | 'edwards',\n  CURVE: ValidCurveParams<T>,\n  curveOpts: Partial<FpFn<T>> = {},\n  FpFnLE?: boolean\n): FpFn<T> & { CURVE: ValidCurveParams<T> } {\n  if (FpFnLE === undefined) FpFnLE = type === 'edwards';\n  if (!CURVE || typeof CURVE !== 'object') throw new Error(`expected valid ${type} CURVE object`);\n  for (const p of ['p', 'n', 'h'] as const) {\n    const val = CURVE[p];\n    if (!(typeof val === 'bigint' && val > _0n))\n      throw new Error(`CURVE.${p} must be positive bigint`);\n  }\n  const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE);\n  const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);\n  const _b: 'b' | 'd' = type === 'weierstrass' ? 'b' : 'd';\n  const params = ['Gx', 'Gy', 'a', _b] as const;\n  for (const p of params) {\n    // @ts-ignore\n    if (!Fp.isValid(CURVE[p]))\n      throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);\n  }\n  CURVE = Object.freeze(Object.assign({}, CURVE));\n  return { CURVE, Fp, Fn };\n}\n","/**\n * Twisted Edwards curve. The formula is: ax² + y² = 1 + dx²y².\n * For design rationale of types / exports, see weierstrass module documentation.\n * Untwisted Edwards curves exist, but they aren't used in real-world protocols.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport {\n  _validateObject,\n  _abool2 as abool,\n  _abytes2 as abytes,\n  aInRange,\n  bytesToHex,\n  bytesToNumberLE,\n  concatBytes,\n  copyBytes,\n  ensureBytes,\n  isBytes,\n  memoized,\n  notImplemented,\n  randomBytes as randomBytesWeb,\n  type FHash,\n  type Hex,\n} from '../utils.ts';\nimport {\n  _createCurveFields,\n  normalizeZ,\n  pippenger,\n  wNAF,\n  type AffinePoint,\n  type BasicCurve,\n  type CurveLengths,\n  type CurvePoint,\n  type CurvePointCons,\n} from './curve.ts';\nimport { Field, type IField, type NLength } from './modular.ts';\n\n// Be friendly to bad ECMAScript parsers by not using bigint literals\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _8n = BigInt(8);\n\nexport type UVRatio = (u: bigint, v: bigint) => { isValid: boolean; value: bigint };\n\n/** Instance of Extended Point with coordinates in X, Y, Z, T. */\nexport interface EdwardsPoint extends CurvePoint<bigint, EdwardsPoint> {\n  /** extended X coordinate. Different from affine x. */\n  readonly X: bigint;\n  /** extended Y coordinate. Different from affine y. */\n  readonly Y: bigint;\n  /** extended Z coordinate */\n  readonly Z: bigint;\n  /** extended T coordinate */\n  readonly T: bigint;\n\n  /** @deprecated use `toBytes` */\n  toRawBytes(): Uint8Array;\n  /** @deprecated use `p.precompute(windowSize)` */\n  _setWindowSize(windowSize: number): void;\n  /** @deprecated use .X */\n  readonly ex: bigint;\n  /** @deprecated use .Y */\n  readonly ey: bigint;\n  /** @deprecated use .Z */\n  readonly ez: bigint;\n  /** @deprecated use .T */\n  readonly et: bigint;\n}\n/** Static methods of Extended Point with coordinates in X, Y, Z, T. */\nexport interface EdwardsPointCons extends CurvePointCons<EdwardsPoint> {\n  new (X: bigint, Y: bigint, Z: bigint, T: bigint): EdwardsPoint;\n  CURVE(): EdwardsOpts;\n  fromBytes(bytes: Uint8Array, zip215?: boolean): EdwardsPoint;\n  fromHex(hex: Hex, zip215?: boolean): EdwardsPoint;\n  /** @deprecated use `import { pippenger } from '@noble/curves/abstract/curve.js';` */\n  msm(points: EdwardsPoint[], scalars: bigint[]): EdwardsPoint;\n}\n/** @deprecated use EdwardsPoint */\nexport type ExtPointType = EdwardsPoint;\n/** @deprecated use EdwardsPointCons */\nexport type ExtPointConstructor = EdwardsPointCons;\n\n/**\n * Twisted Edwards curve options.\n *\n * * a: formula param\n * * d: formula param\n * * p: prime characteristic (order) of finite field, in which arithmetics is done\n * * n: order of prime subgroup a.k.a total amount of valid curve points\n * * h: cofactor. h*n is group order; n is subgroup order\n * * Gx: x coordinate of generator point a.k.a. base point\n * * Gy: y coordinate of generator point\n */\nexport type EdwardsOpts = Readonly<{\n  p: bigint;\n  n: bigint;\n  h: bigint;\n  a: bigint;\n  d: bigint;\n  Gx: bigint;\n  Gy: bigint;\n}>;\n\n/**\n * Extra curve options for Twisted Edwards.\n *\n * * Fp: redefined Field over curve.p\n * * Fn: redefined Field over curve.n\n * * uvRatio: helper function for decompression, calculating √(u/v)\n */\nexport type EdwardsExtraOpts = Partial<{\n  Fp: IField<bigint>;\n  Fn: IField<bigint>;\n  FpFnLE: boolean;\n  uvRatio: (u: bigint, v: bigint) => { isValid: boolean; value: bigint };\n}>;\n\n/**\n * EdDSA (Edwards Digital Signature algorithm) options.\n *\n * * hash: hash function used to hash secret keys and messages\n * * adjustScalarBytes: clears bits to get valid field element\n * * domain: Used for hashing\n * * mapToCurve: for hash-to-curve standard\n * * prehash: RFC 8032 pre-hashing of messages to sign() / verify()\n * * randomBytes: function generating random bytes, used for randomSecretKey\n */\nexport type EdDSAOpts = Partial<{\n  adjustScalarBytes: (bytes: Uint8Array) => Uint8Array;\n  domain: (data: Uint8Array, ctx: Uint8Array, phflag: boolean) => Uint8Array;\n  mapToCurve: (scalar: bigint[]) => AffinePoint<bigint>;\n  prehash: FHash;\n  randomBytes: (bytesLength?: number) => Uint8Array;\n}>;\n\n/**\n * EdDSA (Edwards Digital Signature algorithm) interface.\n *\n * Allows to create and verify signatures, create public and secret keys.\n */\nexport interface EdDSA {\n  keygen: (seed?: Uint8Array) => { secretKey: Uint8Array; publicKey: Uint8Array };\n  getPublicKey: (secretKey: Hex) => Uint8Array;\n  sign: (message: Hex, secretKey: Hex, options?: { context?: Hex }) => Uint8Array;\n  verify: (\n    sig: Hex,\n    message: Hex,\n    publicKey: Hex,\n    options?: { context?: Hex; zip215: boolean }\n  ) => boolean;\n  Point: EdwardsPointCons;\n  utils: {\n    randomSecretKey: (seed?: Uint8Array) => Uint8Array;\n    isValidSecretKey: (secretKey: Uint8Array) => boolean;\n    isValidPublicKey: (publicKey: Uint8Array, zip215?: boolean) => boolean;\n\n    /**\n     * Converts ed public key to x public key.\n     *\n     * There is NO `fromMontgomery`:\n     * - There are 2 valid ed25519 points for every x25519, with flipped coordinate\n     * - Sometimes there are 0 valid ed25519 points, because x25519 *additionally*\n     *   accepts inputs on the quadratic twist, which can't be moved to ed25519\n     *\n     * @example\n     * ```js\n     * const someonesPub = ed25519.getPublicKey(ed25519.utils.randomSecretKey());\n     * const aPriv = x25519.utils.randomSecretKey();\n     * x25519.getSharedSecret(aPriv, ed25519.utils.toMontgomery(someonesPub))\n     * ```\n     */\n    toMontgomery: (publicKey: Uint8Array) => Uint8Array;\n    /**\n     * Converts ed secret key to x secret key.\n     * @example\n     * ```js\n     * const someonesPub = x25519.getPublicKey(x25519.utils.randomSecretKey());\n     * const aPriv = ed25519.utils.randomSecretKey();\n     * x25519.getSharedSecret(ed25519.utils.toMontgomerySecret(aPriv), someonesPub)\n     * ```\n     */\n    toMontgomerySecret: (privateKey: Uint8Array) => Uint8Array;\n    getExtendedPublicKey: (key: Hex) => {\n      head: Uint8Array;\n      prefix: Uint8Array;\n      scalar: bigint;\n      point: EdwardsPoint;\n      pointBytes: Uint8Array;\n    };\n\n    /** @deprecated use `randomSecretKey` */\n    randomPrivateKey: (seed?: Uint8Array) => Uint8Array;\n    /** @deprecated use `point.precompute()` */\n    precompute: (windowSize?: number, point?: EdwardsPoint) => EdwardsPoint;\n  };\n  lengths: CurveLengths;\n}\n\nfunction isEdValidXY(Fp: IField<bigint>, CURVE: EdwardsOpts, x: bigint, y: bigint): boolean {\n  const x2 = Fp.sqr(x);\n  const y2 = Fp.sqr(y);\n  const left = Fp.add(Fp.mul(CURVE.a, x2), y2);\n  const right = Fp.add(Fp.ONE, Fp.mul(CURVE.d, Fp.mul(x2, y2)));\n  return Fp.eql(left, right);\n}\n\nexport function edwards(params: EdwardsOpts, extraOpts: EdwardsExtraOpts = {}): EdwardsPointCons {\n  const validated = _createCurveFields('edwards', params, extraOpts, extraOpts.FpFnLE);\n  const { Fp, Fn } = validated;\n  let CURVE = validated.CURVE as EdwardsOpts;\n  const { h: cofactor } = CURVE;\n  _validateObject(extraOpts, {}, { uvRatio: 'function' });\n\n  // Important:\n  // There are some places where Fp.BYTES is used instead of nByteLength.\n  // So far, everything has been tested with curves of Fp.BYTES == nByteLength.\n  // TODO: test and find curves which behave otherwise.\n  const MASK = _2n << (BigInt(Fn.BYTES * 8) - _1n);\n  const modP = (n: bigint) => Fp.create(n); // Function overrides\n\n  // sqrt(u/v)\n  const uvRatio =\n    extraOpts.uvRatio ||\n    ((u: bigint, v: bigint) => {\n      try {\n        return { isValid: true, value: Fp.sqrt(Fp.div(u, v)) };\n      } catch (e) {\n        return { isValid: false, value: _0n };\n      }\n    });\n\n  // Validate whether the passed curve params are valid.\n  // equation ax² + y² = 1 + dx²y² should work for generator point.\n  if (!isEdValidXY(Fp, CURVE, CURVE.Gx, CURVE.Gy))\n    throw new Error('bad curve params: generator point');\n\n  /**\n   * Asserts coordinate is valid: 0 <= n < MASK.\n   * Coordinates >= Fp.ORDER are allowed for zip215.\n   */\n  function acoord(title: string, n: bigint, banZero = false) {\n    const min = banZero ? _1n : _0n;\n    aInRange('coordinate ' + title, n, min, MASK);\n    return n;\n  }\n\n  function aextpoint(other: unknown) {\n    if (!(other instanceof Point)) throw new Error('ExtendedPoint expected');\n  }\n  // Converts Extended point to default (x, y) coordinates.\n  // Can accept precomputed Z^-1 - for example, from invertBatch.\n  const toAffineMemo = memoized((p: Point, iz?: bigint): AffinePoint<bigint> => {\n    const { X, Y, Z } = p;\n    const is0 = p.is0();\n    if (iz == null) iz = is0 ? _8n : (Fp.inv(Z) as bigint); // 8 was chosen arbitrarily\n    const x = modP(X * iz);\n    const y = modP(Y * iz);\n    const zz = Fp.mul(Z, iz);\n    if (is0) return { x: _0n, y: _1n };\n    if (zz !== _1n) throw new Error('invZ was invalid');\n    return { x, y };\n  });\n  const assertValidMemo = memoized((p: Point) => {\n    const { a, d } = CURVE;\n    if (p.is0()) throw new Error('bad point: ZERO'); // TODO: optimize, with vars below?\n    // Equation in affine coordinates: ax² + y² = 1 + dx²y²\n    // Equation in projective coordinates (X/Z, Y/Z, Z):  (aX² + Y²)Z² = Z⁴ + dX²Y²\n    const { X, Y, Z, T } = p;\n    const X2 = modP(X * X); // X²\n    const Y2 = modP(Y * Y); // Y²\n    const Z2 = modP(Z * Z); // Z²\n    const Z4 = modP(Z2 * Z2); // Z⁴\n    const aX2 = modP(X2 * a); // aX²\n    const left = modP(Z2 * modP(aX2 + Y2)); // (aX² + Y²)Z²\n    const right = modP(Z4 + modP(d * modP(X2 * Y2))); // Z⁴ + dX²Y²\n    if (left !== right) throw new Error('bad point: equation left != right (1)');\n    // In Extended coordinates we also have T, which is x*y=T/Z: check X*Y == Z*T\n    const XY = modP(X * Y);\n    const ZT = modP(Z * T);\n    if (XY !== ZT) throw new Error('bad point: equation left != right (2)');\n    return true;\n  });\n\n  // Extended Point works in extended coordinates: (X, Y, Z, T) ∋ (x=X/Z, y=Y/Z, T=xy).\n  // https://en.wikipedia.org/wiki/Twisted_Edwards_curve#Extended_coordinates\n  class Point implements EdwardsPoint {\n    // base / generator point\n    static readonly BASE = new Point(CURVE.Gx, CURVE.Gy, _1n, modP(CURVE.Gx * CURVE.Gy));\n    // zero / infinity / identity point\n    static readonly ZERO = new Point(_0n, _1n, _1n, _0n); // 0, 1, 1, 0\n    // math field\n    static readonly Fp = Fp;\n    // scalar field\n    static readonly Fn = Fn;\n\n    readonly X: bigint;\n    readonly Y: bigint;\n    readonly Z: bigint;\n    readonly T: bigint;\n\n    constructor(X: bigint, Y: bigint, Z: bigint, T: bigint) {\n      this.X = acoord('x', X);\n      this.Y = acoord('y', Y);\n      this.Z = acoord('z', Z, true);\n      this.T = acoord('t', T);\n      Object.freeze(this);\n    }\n\n    static CURVE(): EdwardsOpts {\n      return CURVE;\n    }\n\n    static fromAffine(p: AffinePoint<bigint>): Point {\n      if (p instanceof Point) throw new Error('extended point not allowed');\n      const { x, y } = p || {};\n      acoord('x', x);\n      acoord('y', y);\n      return new Point(x, y, _1n, modP(x * y));\n    }\n\n    // Uses algo from RFC8032 5.1.3.\n    static fromBytes(bytes: Uint8Array, zip215 = false): Point {\n      const len = Fp.BYTES;\n      const { a, d } = CURVE;\n      bytes = copyBytes(abytes(bytes, len, 'point'));\n      abool(zip215, 'zip215');\n      const normed = copyBytes(bytes); // copy again, we'll manipulate it\n      const lastByte = bytes[len - 1]; // select last byte\n      normed[len - 1] = lastByte & ~0x80; // clear last bit\n      const y = bytesToNumberLE(normed);\n\n      // zip215=true is good for consensus-critical apps. =false follows RFC8032 / NIST186-5.\n      // RFC8032 prohibits >= p, but ZIP215 doesn't\n      // zip215=true:  0 <= y < MASK (2^256 for ed25519)\n      // zip215=false: 0 <= y < P (2^255-19 for ed25519)\n      const max = zip215 ? MASK : Fp.ORDER;\n      aInRange('point.y', y, _0n, max);\n\n      // Ed25519: x² = (y²-1)/(dy²+1) mod p. Ed448: x² = (y²-1)/(dy²-1) mod p. Generic case:\n      // ax²+y²=1+dx²y² => y²-1=dx²y²-ax² => y²-1=x²(dy²-a) => x²=(y²-1)/(dy²-a)\n      const y2 = modP(y * y); // denominator is always non-0 mod p.\n      const u = modP(y2 - _1n); // u = y² - 1\n      const v = modP(d * y2 - a); // v = d y² + 1.\n      let { isValid, value: x } = uvRatio(u, v); // √(u/v)\n      if (!isValid) throw new Error('bad point: invalid y coordinate');\n      const isXOdd = (x & _1n) === _1n; // There are 2 square roots. Use x_0 bit to select proper\n      const isLastByteOdd = (lastByte & 0x80) !== 0; // x_0, last bit\n      if (!zip215 && x === _0n && isLastByteOdd)\n        // if x=0 and x_0 = 1, fail\n        throw new Error('bad point: x=0 and x_0=1');\n      if (isLastByteOdd !== isXOdd) x = modP(-x); // if x_0 != x mod 2, set x = p-x\n      return Point.fromAffine({ x, y });\n    }\n    static fromHex(bytes: Uint8Array, zip215 = false): Point {\n      return Point.fromBytes(ensureBytes('point', bytes), zip215);\n    }\n\n    get x(): bigint {\n      return this.toAffine().x;\n    }\n    get y(): bigint {\n      return this.toAffine().y;\n    }\n\n    precompute(windowSize: number = 8, isLazy = true) {\n      wnaf.createCache(this, windowSize);\n      if (!isLazy) this.multiply(_2n); // random number\n      return this;\n    }\n\n    // Useful in fromAffine() - not for fromBytes(), which always created valid points.\n    assertValidity(): void {\n      assertValidMemo(this);\n    }\n\n    // Compare one point to another.\n    equals(other: Point): boolean {\n      aextpoint(other);\n      const { X: X1, Y: Y1, Z: Z1 } = this;\n      const { X: X2, Y: Y2, Z: Z2 } = other;\n      const X1Z2 = modP(X1 * Z2);\n      const X2Z1 = modP(X2 * Z1);\n      const Y1Z2 = modP(Y1 * Z2);\n      const Y2Z1 = modP(Y2 * Z1);\n      return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;\n    }\n\n    is0(): boolean {\n      return this.equals(Point.ZERO);\n    }\n\n    negate(): Point {\n      // Flips point sign to a negative one (-x, y in affine coords)\n      return new Point(modP(-this.X), this.Y, this.Z, modP(-this.T));\n    }\n\n    // Fast algo for doubling Extended Point.\n    // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd\n    // Cost: 4M + 4S + 1*a + 6add + 1*2.\n    double(): Point {\n      const { a } = CURVE;\n      const { X: X1, Y: Y1, Z: Z1 } = this;\n      const A = modP(X1 * X1); // A = X12\n      const B = modP(Y1 * Y1); // B = Y12\n      const C = modP(_2n * modP(Z1 * Z1)); // C = 2*Z12\n      const D = modP(a * A); // D = a*A\n      const x1y1 = X1 + Y1;\n      const E = modP(modP(x1y1 * x1y1) - A - B); // E = (X1+Y1)2-A-B\n      const G = D + B; // G = D+B\n      const F = G - C; // F = G-C\n      const H = D - B; // H = D-B\n      const X3 = modP(E * F); // X3 = E*F\n      const Y3 = modP(G * H); // Y3 = G*H\n      const T3 = modP(E * H); // T3 = E*H\n      const Z3 = modP(F * G); // Z3 = F*G\n      return new Point(X3, Y3, Z3, T3);\n    }\n\n    // Fast algo for adding 2 Extended Points.\n    // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#addition-add-2008-hwcd\n    // Cost: 9M + 1*a + 1*d + 7add.\n    add(other: Point) {\n      aextpoint(other);\n      const { a, d } = CURVE;\n      const { X: X1, Y: Y1, Z: Z1, T: T1 } = this;\n      const { X: X2, Y: Y2, Z: Z2, T: T2 } = other;\n      const A = modP(X1 * X2); // A = X1*X2\n      const B = modP(Y1 * Y2); // B = Y1*Y2\n      const C = modP(T1 * d * T2); // C = T1*d*T2\n      const D = modP(Z1 * Z2); // D = Z1*Z2\n      const E = modP((X1 + Y1) * (X2 + Y2) - A - B); // E = (X1+Y1)*(X2+Y2)-A-B\n      const F = D - C; // F = D-C\n      const G = D + C; // G = D+C\n      const H = modP(B - a * A); // H = B-a*A\n      const X3 = modP(E * F); // X3 = E*F\n      const Y3 = modP(G * H); // Y3 = G*H\n      const T3 = modP(E * H); // T3 = E*H\n      const Z3 = modP(F * G); // Z3 = F*G\n      return new Point(X3, Y3, Z3, T3);\n    }\n\n    subtract(other: Point): Point {\n      return this.add(other.negate());\n    }\n\n    // Constant-time multiplication.\n    multiply(scalar: bigint): Point {\n      // 1 <= scalar < L\n      if (!Fn.isValidNot0(scalar)) throw new Error('invalid scalar: expected 1 <= sc < curve.n');\n      const { p, f } = wnaf.cached(this, scalar, (p) => normalizeZ(Point, p));\n      return normalizeZ(Point, [p, f])[0];\n    }\n\n    // Non-constant-time multiplication. Uses double-and-add algorithm.\n    // It's faster, but should only be used when you don't care about\n    // an exposed private key e.g. sig verification.\n    // Does NOT allow scalars higher than CURVE.n.\n    // Accepts optional accumulator to merge with multiply (important for sparse scalars)\n    multiplyUnsafe(scalar: bigint, acc = Point.ZERO): Point {\n      // 0 <= scalar < L\n      if (!Fn.isValid(scalar)) throw new Error('invalid scalar: expected 0 <= sc < curve.n');\n      if (scalar === _0n) return Point.ZERO;\n      if (this.is0() || scalar === _1n) return this;\n      return wnaf.unsafe(this, scalar, (p) => normalizeZ(Point, p), acc);\n    }\n\n    // Checks if point is of small order.\n    // If you add something to small order point, you will have \"dirty\"\n    // point with torsion component.\n    // Multiplies point by cofactor and checks if the result is 0.\n    isSmallOrder(): boolean {\n      return this.multiplyUnsafe(cofactor).is0();\n    }\n\n    // Multiplies point by curve order and checks if the result is 0.\n    // Returns `false` is the point is dirty.\n    isTorsionFree(): boolean {\n      return wnaf.unsafe(this, CURVE.n).is0();\n    }\n\n    // Converts Extended point to default (x, y) coordinates.\n    // Can accept precomputed Z^-1 - for example, from invertBatch.\n    toAffine(invertedZ?: bigint): AffinePoint<bigint> {\n      return toAffineMemo(this, invertedZ);\n    }\n\n    clearCofactor(): Point {\n      if (cofactor === _1n) return this;\n      return this.multiplyUnsafe(cofactor);\n    }\n\n    toBytes(): Uint8Array {\n      const { x, y } = this.toAffine();\n      // Fp.toBytes() allows non-canonical encoding of y (>= p).\n      const bytes = Fp.toBytes(y);\n      // Each y has 2 valid points: (x, y), (x,-y).\n      // When compressing, it's enough to store y and use the last byte to encode sign of x\n      bytes[bytes.length - 1] |= x & _1n ? 0x80 : 0;\n      return bytes;\n    }\n    toHex(): string {\n      return bytesToHex(this.toBytes());\n    }\n\n    toString() {\n      return `<Point ${this.is0() ? 'ZERO' : this.toHex()}>`;\n    }\n\n    // TODO: remove\n    get ex(): bigint {\n      return this.X;\n    }\n    get ey(): bigint {\n      return this.Y;\n    }\n    get ez(): bigint {\n      return this.Z;\n    }\n    get et(): bigint {\n      return this.T;\n    }\n    static normalizeZ(points: Point[]): Point[] {\n      return normalizeZ(Point, points);\n    }\n    static msm(points: Point[], scalars: bigint[]): Point {\n      return pippenger(Point, Fn, points, scalars);\n    }\n    _setWindowSize(windowSize: number) {\n      this.precompute(windowSize);\n    }\n    toRawBytes(): Uint8Array {\n      return this.toBytes();\n    }\n  }\n  const wnaf = new wNAF(Point, Fn.BITS);\n  Point.BASE.precompute(8); // Enable precomputes. Slows down first publicKey computation by 20ms.\n  return Point;\n}\n\n/**\n * Base class for prime-order points like Ristretto255 and Decaf448.\n * These points eliminate cofactor issues by representing equivalence classes\n * of Edwards curve points.\n */\nexport abstract class PrimeEdwardsPoint<T extends PrimeEdwardsPoint<T>>\n  implements CurvePoint<bigint, T>\n{\n  static BASE: PrimeEdwardsPoint<any>;\n  static ZERO: PrimeEdwardsPoint<any>;\n  static Fp: IField<bigint>;\n  static Fn: IField<bigint>;\n\n  protected readonly ep: EdwardsPoint;\n\n  constructor(ep: EdwardsPoint) {\n    this.ep = ep;\n  }\n\n  // Abstract methods that must be implemented by subclasses\n  abstract toBytes(): Uint8Array;\n  abstract equals(other: T): boolean;\n\n  // Static methods that must be implemented by subclasses\n  static fromBytes(_bytes: Uint8Array): any {\n    notImplemented();\n  }\n\n  static fromHex(_hex: Hex): any {\n    notImplemented();\n  }\n\n  get x(): bigint {\n    return this.toAffine().x;\n  }\n  get y(): bigint {\n    return this.toAffine().y;\n  }\n\n  // Common implementations\n  clearCofactor(): T {\n    // no-op for prime-order groups\n    return this as any;\n  }\n\n  assertValidity(): void {\n    this.ep.assertValidity();\n  }\n\n  toAffine(invertedZ?: bigint): AffinePoint<bigint> {\n    return this.ep.toAffine(invertedZ);\n  }\n\n  toHex(): string {\n    return bytesToHex(this.toBytes());\n  }\n\n  toString(): string {\n    return this.toHex();\n  }\n\n  isTorsionFree(): boolean {\n    return true;\n  }\n\n  isSmallOrder(): boolean {\n    return false;\n  }\n\n  add(other: T): T {\n    this.assertSame(other);\n    return this.init(this.ep.add(other.ep));\n  }\n\n  subtract(other: T): T {\n    this.assertSame(other);\n    return this.init(this.ep.subtract(other.ep));\n  }\n\n  multiply(scalar: bigint): T {\n    return this.init(this.ep.multiply(scalar));\n  }\n\n  multiplyUnsafe(scalar: bigint): T {\n    return this.init(this.ep.multiplyUnsafe(scalar));\n  }\n\n  double(): T {\n    return this.init(this.ep.double());\n  }\n\n  negate(): T {\n    return this.init(this.ep.negate());\n  }\n\n  precompute(windowSize?: number, isLazy?: boolean): T {\n    return this.init(this.ep.precompute(windowSize, isLazy));\n  }\n\n  // Helper methods\n  abstract is0(): boolean;\n  protected abstract assertSame(other: T): void;\n  protected abstract init(ep: EdwardsPoint): T;\n\n  /** @deprecated use `toBytes` */\n  toRawBytes(): Uint8Array {\n    return this.toBytes();\n  }\n}\n\n/**\n * Initializes EdDSA signatures over given Edwards curve.\n */\nexport function eddsa(Point: EdwardsPointCons, cHash: FHash, eddsaOpts: EdDSAOpts = {}): EdDSA {\n  if (typeof cHash !== 'function') throw new Error('\"hash\" function param is required');\n  _validateObject(\n    eddsaOpts,\n    {},\n    {\n      adjustScalarBytes: 'function',\n      randomBytes: 'function',\n      domain: 'function',\n      prehash: 'function',\n      mapToCurve: 'function',\n    }\n  );\n\n  const { prehash } = eddsaOpts;\n  const { BASE, Fp, Fn } = Point;\n\n  const randomBytes = eddsaOpts.randomBytes || randomBytesWeb;\n  const adjustScalarBytes = eddsaOpts.adjustScalarBytes || ((bytes: Uint8Array) => bytes);\n  const domain =\n    eddsaOpts.domain ||\n    ((data: Uint8Array, ctx: Uint8Array, phflag: boolean) => {\n      abool(phflag, 'phflag');\n      if (ctx.length || phflag) throw new Error('Contexts/pre-hash are not supported');\n      return data;\n    }); // NOOP\n\n  // Little-endian SHA512 with modulo n\n  function modN_LE(hash: Uint8Array): bigint {\n    return Fn.create(bytesToNumberLE(hash)); // Not Fn.fromBytes: it has length limit\n  }\n\n  // Get the hashed private scalar per RFC8032 5.1.5\n  function getPrivateScalar(key: Hex) {\n    const len = lengths.secretKey;\n    key = ensureBytes('private key', key, len);\n    // Hash private key with curve's hash function to produce uniformingly random input\n    // Check byte lengths: ensure(64, h(ensure(32, key)))\n    const hashed = ensureBytes('hashed private key', cHash(key), 2 * len);\n    const head = adjustScalarBytes(hashed.slice(0, len)); // clear first half bits, produce FE\n    const prefix = hashed.slice(len, 2 * len); // second half is called key prefix (5.1.6)\n    const scalar = modN_LE(head); // The actual private scalar\n    return { head, prefix, scalar };\n  }\n\n  /** Convenience method that creates public key from scalar. RFC8032 5.1.5 */\n  function getExtendedPublicKey(secretKey: Hex) {\n    const { head, prefix, scalar } = getPrivateScalar(secretKey);\n    const point = BASE.multiply(scalar); // Point on Edwards curve aka public key\n    const pointBytes = point.toBytes();\n    return { head, prefix, scalar, point, pointBytes };\n  }\n\n  /** Calculates EdDSA pub key. RFC8032 5.1.5. */\n  function getPublicKey(secretKey: Hex): Uint8Array {\n    return getExtendedPublicKey(secretKey).pointBytes;\n  }\n\n  // int('LE', SHA512(dom2(F, C) || msgs)) mod N\n  function hashDomainToScalar(context: Hex = Uint8Array.of(), ...msgs: Uint8Array[]) {\n    const msg = concatBytes(...msgs);\n    return modN_LE(cHash(domain(msg, ensureBytes('context', context), !!prehash)));\n  }\n\n  /** Signs message with privateKey. RFC8032 5.1.6 */\n  function sign(msg: Hex, secretKey: Hex, options: { context?: Hex } = {}): Uint8Array {\n    msg = ensureBytes('message', msg);\n    if (prehash) msg = prehash(msg); // for ed25519ph etc.\n    const { prefix, scalar, pointBytes } = getExtendedPublicKey(secretKey);\n    const r = hashDomainToScalar(options.context, prefix, msg); // r = dom2(F, C) || prefix || PH(M)\n    const R = BASE.multiply(r).toBytes(); // R = rG\n    const k = hashDomainToScalar(options.context, R, pointBytes, msg); // R || A || PH(M)\n    const s = Fn.create(r + k * scalar); // S = (r + k * s) mod L\n    if (!Fn.isValid(s)) throw new Error('sign failed: invalid s'); // 0 <= s < L\n    const rs = concatBytes(R, Fn.toBytes(s));\n    return abytes(rs, lengths.signature, 'result');\n  }\n\n  // verification rule is either zip215 or rfc8032 / nist186-5. Consult fromHex:\n  const verifyOpts: { context?: Hex; zip215?: boolean } = { zip215: true };\n\n  /**\n   * Verifies EdDSA signature against message and public key. RFC8032 5.1.7.\n   * An extended group equation is checked.\n   */\n  function verify(sig: Hex, msg: Hex, publicKey: Hex, options = verifyOpts): boolean {\n    const { context, zip215 } = options;\n    const len = lengths.signature;\n    sig = ensureBytes('signature', sig, len);\n    msg = ensureBytes('message', msg);\n    publicKey = ensureBytes('publicKey', publicKey, lengths.publicKey);\n    if (zip215 !== undefined) abool(zip215, 'zip215');\n    if (prehash) msg = prehash(msg); // for ed25519ph, etc\n\n    const mid = len / 2;\n    const r = sig.subarray(0, mid);\n    const s = bytesToNumberLE(sig.subarray(mid, len));\n    let A, R, SB;\n    try {\n      // zip215=true is good for consensus-critical apps. =false follows RFC8032 / NIST186-5.\n      // zip215=true:  0 <= y < MASK (2^256 for ed25519)\n      // zip215=false: 0 <= y < P (2^255-19 for ed25519)\n      A = Point.fromBytes(publicKey, zip215);\n      R = Point.fromBytes(r, zip215);\n      SB = BASE.multiplyUnsafe(s); // 0 <= s < l is done inside\n    } catch (error) {\n      return false;\n    }\n    if (!zip215 && A.isSmallOrder()) return false; // zip215 allows public keys of small order\n\n    const k = hashDomainToScalar(context, R.toBytes(), A.toBytes(), msg);\n    const RkA = R.add(A.multiplyUnsafe(k));\n    // Extended group equation\n    // [8][S]B = [8]R + [8][k]A'\n    return RkA.subtract(SB).clearCofactor().is0();\n  }\n\n  const _size = Fp.BYTES; // 32 for ed25519, 57 for ed448\n  const lengths = {\n    secretKey: _size,\n    publicKey: _size,\n    signature: 2 * _size,\n    seed: _size,\n  };\n  function randomSecretKey(seed = randomBytes(lengths.seed)): Uint8Array {\n    return abytes(seed, lengths.seed, 'seed');\n  }\n  function keygen(seed?: Uint8Array) {\n    const secretKey = utils.randomSecretKey(seed);\n    return { secretKey, publicKey: getPublicKey(secretKey) };\n  }\n  function isValidSecretKey(key: Uint8Array): boolean {\n    return isBytes(key) && key.length === Fn.BYTES;\n  }\n  function isValidPublicKey(key: Uint8Array, zip215?: boolean): boolean {\n    try {\n      return !!Point.fromBytes(key, zip215);\n    } catch (error) {\n      return false;\n    }\n  }\n\n  const utils = {\n    getExtendedPublicKey,\n    randomSecretKey,\n    isValidSecretKey,\n    isValidPublicKey,\n    /**\n     * Converts ed public key to x public key. Uses formula:\n     * - ed25519:\n     *   - `(u, v) = ((1+y)/(1-y), sqrt(-486664)*u/x)`\n     *   - `(x, y) = (sqrt(-486664)*u/v, (u-1)/(u+1))`\n     * - ed448:\n     *   - `(u, v) = ((y-1)/(y+1), sqrt(156324)*u/x)`\n     *   - `(x, y) = (sqrt(156324)*u/v, (1+u)/(1-u))`\n     */\n    toMontgomery(publicKey: Uint8Array): Uint8Array {\n      const { y } = Point.fromBytes(publicKey);\n      const size = lengths.publicKey;\n      const is25519 = size === 32;\n      if (!is25519 && size !== 57) throw new Error('only defined for 25519 and 448');\n      const u = is25519 ? Fp.div(_1n + y, _1n - y) : Fp.div(y - _1n, y + _1n);\n      return Fp.toBytes(u);\n    },\n\n    toMontgomerySecret(secretKey: Uint8Array): Uint8Array {\n      const size = lengths.secretKey;\n      abytes(secretKey, size);\n      const hashed = cHash(secretKey.subarray(0, size));\n      return adjustScalarBytes(hashed).subarray(0, size);\n    },\n\n    /** @deprecated */\n    randomPrivateKey: randomSecretKey,\n    /** @deprecated */\n    precompute(windowSize = 8, point: EdwardsPoint = Point.BASE): EdwardsPoint {\n      return point.precompute(windowSize, false);\n    },\n  };\n\n  return Object.freeze({\n    keygen,\n    getPublicKey,\n    sign,\n    verify,\n    utils,\n    Point,\n    lengths,\n  });\n}\n\n// TODO: remove everything below\nexport type CurveType = BasicCurve<bigint> & {\n  a: bigint; // curve param a\n  d: bigint; // curve param d\n  /** @deprecated the property will be removed in next release */\n  hash: FHash; // Hashing\n  randomBytes?: (bytesLength?: number) => Uint8Array; // CSPRNG\n  adjustScalarBytes?: (bytes: Uint8Array) => Uint8Array; // clears bits to get valid field elemtn\n  domain?: (data: Uint8Array, ctx: Uint8Array, phflag: boolean) => Uint8Array; // Used for hashing\n  uvRatio?: UVRatio; // Ratio √(u/v)\n  prehash?: FHash; // RFC 8032 pre-hashing of messages to sign() / verify()\n  mapToCurve?: (scalar: bigint[]) => AffinePoint<bigint>; // for hash-to-curve standard\n};\nexport type CurveTypeWithLength = Readonly<CurveType & Partial<NLength>>;\nexport type CurveFn = {\n  /** @deprecated the property will be removed in next release */\n  CURVE: CurveType;\n  keygen: EdDSA['keygen'];\n  getPublicKey: EdDSA['getPublicKey'];\n  sign: EdDSA['sign'];\n  verify: EdDSA['verify'];\n  Point: EdwardsPointCons;\n  /** @deprecated use `Point` */\n  ExtendedPoint: EdwardsPointCons;\n  utils: EdDSA['utils'];\n  lengths: CurveLengths;\n};\nexport type EdComposed = {\n  CURVE: EdwardsOpts;\n  curveOpts: EdwardsExtraOpts;\n  hash: FHash;\n  eddsaOpts: EdDSAOpts;\n};\nfunction _eddsa_legacy_opts_to_new(c: CurveTypeWithLength): EdComposed {\n  const CURVE: EdwardsOpts = {\n    a: c.a,\n    d: c.d,\n    p: c.Fp.ORDER,\n    n: c.n,\n    h: c.h,\n    Gx: c.Gx,\n    Gy: c.Gy,\n  };\n  const Fp = c.Fp;\n  const Fn = Field(CURVE.n, c.nBitLength, true);\n  const curveOpts: EdwardsExtraOpts = { Fp, Fn, uvRatio: c.uvRatio };\n  const eddsaOpts: EdDSAOpts = {\n    randomBytes: c.randomBytes,\n    adjustScalarBytes: c.adjustScalarBytes,\n    domain: c.domain,\n    prehash: c.prehash,\n    mapToCurve: c.mapToCurve,\n  };\n  return { CURVE, curveOpts, hash: c.hash, eddsaOpts };\n}\nfunction _eddsa_new_output_to_legacy(c: CurveTypeWithLength, eddsa: EdDSA): CurveFn {\n  const Point = eddsa.Point;\n  const legacy = Object.assign({}, eddsa, {\n    ExtendedPoint: Point,\n    CURVE: c,\n    nBitLength: Point.Fn.BITS,\n    nByteLength: Point.Fn.BYTES,\n  });\n  return legacy;\n}\n// TODO: remove. Use eddsa\nexport function twistedEdwards(c: CurveTypeWithLength): CurveFn {\n  const { CURVE, curveOpts, hash, eddsaOpts } = _eddsa_legacy_opts_to_new(c);\n  const Point = edwards(CURVE, curveOpts);\n  const EDDSA = eddsa(Point, hash, eddsaOpts);\n  return _eddsa_new_output_to_legacy(c, EDDSA);\n}\n","/**\n * ed25519 Twisted Edwards curve with following addons:\n * - X25519 ECDH\n * - Ristretto cofactor elimination\n * - Elligator hash-to-group / point indistinguishability\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha512 } from '@noble/hashes/sha2.js';\nimport { abytes, concatBytes, utf8ToBytes } from '@noble/hashes/utils.js';\nimport { pippenger, type AffinePoint } from './abstract/curve.ts';\nimport {\n  PrimeEdwardsPoint,\n  twistedEdwards,\n  type CurveFn,\n  type EdwardsOpts,\n  type EdwardsPoint,\n} from './abstract/edwards.ts';\nimport {\n  _DST_scalar,\n  createHasher,\n  expand_message_xmd,\n  type H2CHasher,\n  type H2CHasherBase,\n  type H2CMethod,\n  type htfBasicOpts,\n} from './abstract/hash-to-curve.ts';\nimport {\n  Field,\n  FpInvertBatch,\n  FpSqrtEven,\n  isNegativeLE,\n  mod,\n  pow2,\n  type IField,\n} from './abstract/modular.ts';\nimport { montgomery, type MontgomeryECDH as XCurveFn } from './abstract/montgomery.ts';\nimport { bytesToNumberLE, ensureBytes, equalBytes, type Hex } from './utils.ts';\n\n// prettier-ignore\nconst _0n = /* @__PURE__ */ BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3);\n// prettier-ignore\nconst _5n = BigInt(5), _8n = BigInt(8);\n\n// P = 2n**255n-19n\nconst ed25519_CURVE_p = BigInt(\n  '0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed'\n);\n\n// N = 2n**252n + 27742317777372353535851937790883648493n\n// a = Fp.create(BigInt(-1))\n// d = -121665/121666 a.k.a. Fp.neg(121665 * Fp.inv(121666))\nconst ed25519_CURVE: EdwardsOpts = /* @__PURE__ */ (() => ({\n  p: ed25519_CURVE_p,\n  n: BigInt('0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed'),\n  h: _8n,\n  a: BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec'),\n  d: BigInt('0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3'),\n  Gx: BigInt('0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a'),\n  Gy: BigInt('0x6666666666666666666666666666666666666666666666666666666666666658'),\n}))();\n\nfunction ed25519_pow_2_252_3(x: bigint) {\n  // prettier-ignore\n  const _10n = BigInt(10), _20n = BigInt(20), _40n = BigInt(40), _80n = BigInt(80);\n  const P = ed25519_CURVE_p;\n  const x2 = (x * x) % P;\n  const b2 = (x2 * x) % P; // x^3, 11\n  const b4 = (pow2(b2, _2n, P) * b2) % P; // x^15, 1111\n  const b5 = (pow2(b4, _1n, P) * x) % P; // x^31\n  const b10 = (pow2(b5, _5n, P) * b5) % P;\n  const b20 = (pow2(b10, _10n, P) * b10) % P;\n  const b40 = (pow2(b20, _20n, P) * b20) % P;\n  const b80 = (pow2(b40, _40n, P) * b40) % P;\n  const b160 = (pow2(b80, _80n, P) * b80) % P;\n  const b240 = (pow2(b160, _80n, P) * b80) % P;\n  const b250 = (pow2(b240, _10n, P) * b10) % P;\n  const pow_p_5_8 = (pow2(b250, _2n, P) * x) % P;\n  // ^ To pow to (p+3)/8, multiply it by x.\n  return { pow_p_5_8, b2 };\n}\n\nfunction adjustScalarBytes(bytes: Uint8Array): Uint8Array {\n  // Section 5: For X25519, in order to decode 32 random bytes as an integer scalar,\n  // set the three least significant bits of the first byte\n  bytes[0] &= 248; // 0b1111_1000\n  // and the most significant bit of the last to zero,\n  bytes[31] &= 127; // 0b0111_1111\n  // set the second most significant bit of the last byte to 1\n  bytes[31] |= 64; // 0b0100_0000\n  return bytes;\n}\n\n// √(-1) aka √(a) aka 2^((p-1)/4)\n// Fp.sqrt(Fp.neg(1))\nconst ED25519_SQRT_M1 = /* @__PURE__ */ BigInt(\n  '19681161376707505956807079304988542015446066515923890162744021073123829784752'\n);\n// sqrt(u/v)\nfunction uvRatio(u: bigint, v: bigint): { isValid: boolean; value: bigint } {\n  const P = ed25519_CURVE_p;\n  const v3 = mod(v * v * v, P); // v³\n  const v7 = mod(v3 * v3 * v, P); // v⁷\n  // (p+3)/8 and (p-5)/8\n  const pow = ed25519_pow_2_252_3(u * v7).pow_p_5_8;\n  let x = mod(u * v3 * pow, P); // (uv³)(uv⁷)^(p-5)/8\n  const vx2 = mod(v * x * x, P); // vx²\n  const root1 = x; // First root candidate\n  const root2 = mod(x * ED25519_SQRT_M1, P); // Second root candidate\n  const useRoot1 = vx2 === u; // If vx² = u (mod p), x is a square root\n  const useRoot2 = vx2 === mod(-u, P); // If vx² = -u, set x <-- x * 2^((p-1)/4)\n  const noRoot = vx2 === mod(-u * ED25519_SQRT_M1, P); // There is no valid root, vx² = -u√(-1)\n  if (useRoot1) x = root1;\n  if (useRoot2 || noRoot) x = root2; // We return root2 anyway, for const-time\n  if (isNegativeLE(x, P)) x = mod(-x, P);\n  return { isValid: useRoot1 || useRoot2, value: x };\n}\n\nconst Fp = /* @__PURE__ */ (() => Field(ed25519_CURVE.p, { isLE: true }))();\nconst Fn = /* @__PURE__ */ (() => Field(ed25519_CURVE.n, { isLE: true }))();\n\nconst ed25519Defaults = /* @__PURE__ */ (() => ({\n  ...ed25519_CURVE,\n  Fp,\n  hash: sha512,\n  adjustScalarBytes,\n  // dom2\n  // Ratio of u to v. Allows us to combine inversion and square root. Uses algo from RFC8032 5.1.3.\n  // Constant-time, u/√v\n  uvRatio,\n}))();\n\n/**\n * ed25519 curve with EdDSA signatures.\n * @example\n * import { ed25519 } from '@noble/curves/ed25519';\n * const { secretKey, publicKey } = ed25519.keygen();\n * const msg = new TextEncoder().encode('hello');\n * const sig = ed25519.sign(msg, priv);\n * ed25519.verify(sig, msg, pub); // Default mode: follows ZIP215\n * ed25519.verify(sig, msg, pub, { zip215: false }); // RFC8032 / FIPS 186-5\n */\nexport const ed25519: CurveFn = /* @__PURE__ */ (() => twistedEdwards(ed25519Defaults))();\n\nfunction ed25519_domain(data: Uint8Array, ctx: Uint8Array, phflag: boolean) {\n  if (ctx.length > 255) throw new Error('Context is too big');\n  return concatBytes(\n    utf8ToBytes('SigEd25519 no Ed25519 collisions'),\n    new Uint8Array([phflag ? 1 : 0, ctx.length]),\n    ctx,\n    data\n  );\n}\n\n/** Context of ed25519. Uses context for domain separation. */\nexport const ed25519ctx: CurveFn = /* @__PURE__ */ (() =>\n  twistedEdwards({\n    ...ed25519Defaults,\n    domain: ed25519_domain,\n  }))();\n\n/** Prehashed version of ed25519. Accepts already-hashed messages in sign() and verify(). */\nexport const ed25519ph: CurveFn = /* @__PURE__ */ (() =>\n  twistedEdwards(\n    Object.assign({}, ed25519Defaults, {\n      domain: ed25519_domain,\n      prehash: sha512,\n    })\n  ))();\n\n/**\n * ECDH using curve25519 aka x25519.\n * @example\n * import { x25519 } from '@noble/curves/ed25519';\n * const priv = 'a546e36bf0527c9d3b16154b82465edd62144c0ac1fc5a18506a2244ba449ac4';\n * const pub = 'e6db6867583030db3594c1a424b15f7c726624ec26b3353b10a903a6d0ab1c4c';\n * x25519.getSharedSecret(priv, pub) === x25519.scalarMult(priv, pub); // aliases\n * x25519.getPublicKey(priv) === x25519.scalarMultBase(priv);\n * x25519.getPublicKey(x25519.utils.randomSecretKey());\n */\nexport const x25519: XCurveFn = /* @__PURE__ */ (() => {\n  const P = Fp.ORDER;\n  return montgomery({\n    P,\n    type: 'x25519',\n    powPminus2: (x: bigint): bigint => {\n      // x^(p-2) aka x^(2^255-21)\n      const { pow_p_5_8, b2 } = ed25519_pow_2_252_3(x);\n      return mod(pow2(pow_p_5_8, _3n, P) * b2, P);\n    },\n    adjustScalarBytes,\n  });\n})();\n\n// Hash To Curve Elligator2 Map (NOTE: different from ristretto255 elligator)\n// NOTE: very important part is usage of FpSqrtEven for ELL2_C1_EDWARDS, since\n// SageMath returns different root first and everything falls apart\nconst ELL2_C1 = /* @__PURE__ */ (() => (ed25519_CURVE_p + _3n) / _8n)(); // 1. c1 = (q + 3) / 8       # Integer arithmetic\nconst ELL2_C2 = /* @__PURE__ */ (() => Fp.pow(_2n, ELL2_C1))(); // 2. c2 = 2^c1\nconst ELL2_C3 = /* @__PURE__ */ (() => Fp.sqrt(Fp.neg(Fp.ONE)))(); // 3. c3 = sqrt(-1)\n\n// prettier-ignore\nfunction map_to_curve_elligator2_curve25519(u: bigint) {\n  const ELL2_C4 = (ed25519_CURVE_p - _5n) / _8n; // 4. c4 = (q - 5) / 8       # Integer arithmetic\n  const ELL2_J = BigInt(486662);\n\n  let tv1 = Fp.sqr(u);          //  1.  tv1 = u^2\n  tv1 = Fp.mul(tv1, _2n);       //  2.  tv1 = 2 * tv1\n  let xd = Fp.add(tv1, Fp.ONE); //  3.   xd = tv1 + 1         # Nonzero: -1 is square (mod p), tv1 is not\n  let x1n = Fp.neg(ELL2_J);     //  4.  x1n = -J              # x1 = x1n / xd = -J / (1 + 2 * u^2)\n  let tv2 = Fp.sqr(xd);         //  5.  tv2 = xd^2\n  let gxd = Fp.mul(tv2, xd);    //  6.  gxd = tv2 * xd        # gxd = xd^3\n  let gx1 = Fp.mul(tv1, ELL2_J);//  7.  gx1 = J * tv1         # x1n + J * xd\n  gx1 = Fp.mul(gx1, x1n);       //  8.  gx1 = gx1 * x1n       # x1n^2 + J * x1n * xd\n  gx1 = Fp.add(gx1, tv2);       //  9.  gx1 = gx1 + tv2       # x1n^2 + J * x1n * xd + xd^2\n  gx1 = Fp.mul(gx1, x1n);       //  10. gx1 = gx1 * x1n       # x1n^3 + J * x1n^2 * xd + x1n * xd^2\n  let tv3 = Fp.sqr(gxd);        //  11. tv3 = gxd^2\n  tv2 = Fp.sqr(tv3);            //  12. tv2 = tv3^2           # gxd^4\n  tv3 = Fp.mul(tv3, gxd);       //  13. tv3 = tv3 * gxd       # gxd^3\n  tv3 = Fp.mul(tv3, gx1);       //  14. tv3 = tv3 * gx1       # gx1 * gxd^3\n  tv2 = Fp.mul(tv2, tv3);       //  15. tv2 = tv2 * tv3       # gx1 * gxd^7\n  let y11 = Fp.pow(tv2, ELL2_C4); //  16. y11 = tv2^c4        # (gx1 * gxd^7)^((p - 5) / 8)\n  y11 = Fp.mul(y11, tv3);       //  17. y11 = y11 * tv3       # gx1*gxd^3*(gx1*gxd^7)^((p-5)/8)\n  let y12 = Fp.mul(y11, ELL2_C3); //  18. y12 = y11 * c3\n  tv2 = Fp.sqr(y11);            //  19. tv2 = y11^2\n  tv2 = Fp.mul(tv2, gxd);       //  20. tv2 = tv2 * gxd\n  let e1 = Fp.eql(tv2, gx1);    //  21.  e1 = tv2 == gx1\n  let y1 = Fp.cmov(y12, y11, e1); //  22.  y1 = CMOV(y12, y11, e1)  # If g(x1) is square, this is its sqrt\n  let x2n = Fp.mul(x1n, tv1);   //  23. x2n = x1n * tv1       # x2 = x2n / xd = 2 * u^2 * x1n / xd\n  let y21 = Fp.mul(y11, u);     //  24. y21 = y11 * u\n  y21 = Fp.mul(y21, ELL2_C2);   //  25. y21 = y21 * c2\n  let y22 = Fp.mul(y21, ELL2_C3); //  26. y22 = y21 * c3\n  let gx2 = Fp.mul(gx1, tv1);   //  27. gx2 = gx1 * tv1       # g(x2) = gx2 / gxd = 2 * u^2 * g(x1)\n  tv2 = Fp.sqr(y21);            //  28. tv2 = y21^2\n  tv2 = Fp.mul(tv2, gxd);       //  29. tv2 = tv2 * gxd\n  let e2 = Fp.eql(tv2, gx2);    //  30.  e2 = tv2 == gx2\n  let y2 = Fp.cmov(y22, y21, e2); //  31.  y2 = CMOV(y22, y21, e2)  # If g(x2) is square, this is its sqrt\n  tv2 = Fp.sqr(y1);             //  32. tv2 = y1^2\n  tv2 = Fp.mul(tv2, gxd);       //  33. tv2 = tv2 * gxd\n  let e3 = Fp.eql(tv2, gx1);    //  34.  e3 = tv2 == gx1\n  let xn = Fp.cmov(x2n, x1n, e3); //  35.  xn = CMOV(x2n, x1n, e3)  # If e3, x = x1, else x = x2\n  let y = Fp.cmov(y2, y1, e3);  //  36.   y = CMOV(y2, y1, e3)    # If e3, y = y1, else y = y2\n  let e4 = Fp.isOdd!(y);         //  37.  e4 = sgn0(y) == 1        # Fix sign of y\n  y = Fp.cmov(y, Fp.neg(y), e3 !== e4); //  38.   y = CMOV(y, -y, e3 XOR e4)\n  return { xMn: xn, xMd: xd, yMn: y, yMd: _1n }; //  39. return (xn, xd, y, 1)\n}\n\nconst ELL2_C1_EDWARDS = /* @__PURE__ */ (() => FpSqrtEven(Fp, Fp.neg(BigInt(486664))))(); // sgn0(c1) MUST equal 0\nfunction map_to_curve_elligator2_edwards25519(u: bigint) {\n  const { xMn, xMd, yMn, yMd } = map_to_curve_elligator2_curve25519(u); //  1.  (xMn, xMd, yMn, yMd) =\n  // map_to_curve_elligator2_curve25519(u)\n  let xn = Fp.mul(xMn, yMd); //  2.  xn = xMn * yMd\n  xn = Fp.mul(xn, ELL2_C1_EDWARDS); //  3.  xn = xn * c1\n  let xd = Fp.mul(xMd, yMn); //  4.  xd = xMd * yMn    # xn / xd = c1 * xM / yM\n  let yn = Fp.sub(xMn, xMd); //  5.  yn = xMn - xMd\n  let yd = Fp.add(xMn, xMd); //  6.  yd = xMn + xMd    # (n / d - 1) / (n / d + 1) = (n - d) / (n + d)\n  let tv1 = Fp.mul(xd, yd); //  7. tv1 = xd * yd\n  let e = Fp.eql(tv1, Fp.ZERO); //  8.   e = tv1 == 0\n  xn = Fp.cmov(xn, Fp.ZERO, e); //  9.  xn = CMOV(xn, 0, e)\n  xd = Fp.cmov(xd, Fp.ONE, e); //  10. xd = CMOV(xd, 1, e)\n  yn = Fp.cmov(yn, Fp.ONE, e); //  11. yn = CMOV(yn, 1, e)\n  yd = Fp.cmov(yd, Fp.ONE, e); //  12. yd = CMOV(yd, 1, e)\n  const [xd_inv, yd_inv] = FpInvertBatch(Fp, [xd, yd], true); // batch division\n  return { x: Fp.mul(xn, xd_inv), y: Fp.mul(yn, yd_inv) }; //  13. return (xn, xd, yn, yd)\n}\n\n/** Hashing to ed25519 points / field. RFC 9380 methods. */\nexport const ed25519_hasher: H2CHasher<bigint> = /* @__PURE__ */ (() =>\n  createHasher(\n    ed25519.Point,\n    (scalars: bigint[]) => map_to_curve_elligator2_edwards25519(scalars[0]),\n    {\n      DST: 'edwards25519_XMD:SHA-512_ELL2_RO_',\n      encodeDST: 'edwards25519_XMD:SHA-512_ELL2_NU_',\n      p: ed25519_CURVE_p,\n      m: 1,\n      k: 128,\n      expand: 'xmd',\n      hash: sha512,\n    }\n  ))();\n\n// √(-1) aka √(a) aka 2^((p-1)/4)\nconst SQRT_M1 = ED25519_SQRT_M1;\n// √(ad - 1)\nconst SQRT_AD_MINUS_ONE = /* @__PURE__ */ BigInt(\n  '25063068953384623474111414158702152701244531502492656460079210482610430750235'\n);\n// 1 / √(a-d)\nconst INVSQRT_A_MINUS_D = /* @__PURE__ */ BigInt(\n  '54469307008909316920995813868745141605393597292927456921205312896311721017578'\n);\n// 1-d²\nconst ONE_MINUS_D_SQ = /* @__PURE__ */ BigInt(\n  '1159843021668779879193775521855586647937357759715417654439879720876111806838'\n);\n// (d-1)²\nconst D_MINUS_ONE_SQ = /* @__PURE__ */ BigInt(\n  '40440834346308536858101042469323190826248399146238708352240133220865137265952'\n);\n// Calculates 1/√(number)\nconst invertSqrt = (number: bigint) => uvRatio(_1n, number);\n\nconst MAX_255B = /* @__PURE__ */ BigInt(\n  '0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'\n);\nconst bytes255ToNumberLE = (bytes: Uint8Array) =>\n  ed25519.Point.Fp.create(bytesToNumberLE(bytes) & MAX_255B);\n\ntype ExtendedPoint = EdwardsPoint;\n\n/**\n * Computes Elligator map for Ristretto255.\n * Described in [RFC9380](https://www.rfc-editor.org/rfc/rfc9380#appendix-B) and on\n * the [website](https://ristretto.group/formulas/elligator.html).\n */\nfunction calcElligatorRistrettoMap(r0: bigint): ExtendedPoint {\n  const { d } = ed25519_CURVE;\n  const P = ed25519_CURVE_p;\n  const mod = (n: bigint) => Fp.create(n);\n  const r = mod(SQRT_M1 * r0 * r0); // 1\n  const Ns = mod((r + _1n) * ONE_MINUS_D_SQ); // 2\n  let c = BigInt(-1); // 3\n  const D = mod((c - d * r) * mod(r + d)); // 4\n  let { isValid: Ns_D_is_sq, value: s } = uvRatio(Ns, D); // 5\n  let s_ = mod(s * r0); // 6\n  if (!isNegativeLE(s_, P)) s_ = mod(-s_);\n  if (!Ns_D_is_sq) s = s_; // 7\n  if (!Ns_D_is_sq) c = r; // 8\n  const Nt = mod(c * (r - _1n) * D_MINUS_ONE_SQ - D); // 9\n  const s2 = s * s;\n  const W0 = mod((s + s) * D); // 10\n  const W1 = mod(Nt * SQRT_AD_MINUS_ONE); // 11\n  const W2 = mod(_1n - s2); // 12\n  const W3 = mod(_1n + s2); // 13\n  return new ed25519.Point(mod(W0 * W3), mod(W2 * W1), mod(W1 * W3), mod(W0 * W2));\n}\n\nfunction ristretto255_map(bytes: Uint8Array): _RistrettoPoint {\n  abytes(bytes, 64);\n  const r1 = bytes255ToNumberLE(bytes.subarray(0, 32));\n  const R1 = calcElligatorRistrettoMap(r1);\n  const r2 = bytes255ToNumberLE(bytes.subarray(32, 64));\n  const R2 = calcElligatorRistrettoMap(r2);\n  return new _RistrettoPoint(R1.add(R2));\n}\n\n/**\n * Wrapper over Edwards Point for ristretto255.\n *\n * Each ed25519/ExtendedPoint has 8 different equivalent points. This can be\n * a source of bugs for protocols like ring signatures. Ristretto was created to solve this.\n * Ristretto point operates in X:Y:Z:T extended coordinates like ExtendedPoint,\n * but it should work in its own namespace: do not combine those two.\n * See [RFC9496](https://www.rfc-editor.org/rfc/rfc9496).\n */\nclass _RistrettoPoint extends PrimeEdwardsPoint<_RistrettoPoint> {\n  // Do NOT change syntax: the following gymnastics is done,\n  // because typescript strips comments, which makes bundlers disable tree-shaking.\n  // prettier-ignore\n  static BASE: _RistrettoPoint =\n    /* @__PURE__ */ (() => new _RistrettoPoint(ed25519.Point.BASE))();\n  // prettier-ignore\n  static ZERO: _RistrettoPoint =\n    /* @__PURE__ */ (() => new _RistrettoPoint(ed25519.Point.ZERO))();\n  // prettier-ignore\n  static Fp: IField<bigint> =\n    /* @__PURE__ */ (() => Fp)();\n  // prettier-ignore\n  static Fn: IField<bigint> =\n    /* @__PURE__ */ (() => Fn)();\n\n  constructor(ep: ExtendedPoint) {\n    super(ep);\n  }\n\n  static fromAffine(ap: AffinePoint<bigint>): _RistrettoPoint {\n    return new _RistrettoPoint(ed25519.Point.fromAffine(ap));\n  }\n\n  protected assertSame(other: _RistrettoPoint): void {\n    if (!(other instanceof _RistrettoPoint)) throw new Error('RistrettoPoint expected');\n  }\n\n  protected init(ep: EdwardsPoint): _RistrettoPoint {\n    return new _RistrettoPoint(ep);\n  }\n\n  /** @deprecated use `import { ristretto255_hasher } from '@noble/curves/ed25519.js';` */\n  static hashToCurve(hex: Hex): _RistrettoPoint {\n    return ristretto255_map(ensureBytes('ristrettoHash', hex, 64));\n  }\n\n  static fromBytes(bytes: Uint8Array): _RistrettoPoint {\n    abytes(bytes, 32);\n    const { a, d } = ed25519_CURVE;\n    const P = ed25519_CURVE_p;\n    const mod = (n: bigint) => Fp.create(n);\n    const s = bytes255ToNumberLE(bytes);\n    // 1. Check that s_bytes is the canonical encoding of a field element, or else abort.\n    // 3. Check that s is non-negative, or else abort\n    if (!equalBytes(Fp.toBytes(s), bytes) || isNegativeLE(s, P))\n      throw new Error('invalid ristretto255 encoding 1');\n    const s2 = mod(s * s);\n    const u1 = mod(_1n + a * s2); // 4 (a is -1)\n    const u2 = mod(_1n - a * s2); // 5\n    const u1_2 = mod(u1 * u1);\n    const u2_2 = mod(u2 * u2);\n    const v = mod(a * d * u1_2 - u2_2); // 6\n    const { isValid, value: I } = invertSqrt(mod(v * u2_2)); // 7\n    const Dx = mod(I * u2); // 8\n    const Dy = mod(I * Dx * v); // 9\n    let x = mod((s + s) * Dx); // 10\n    if (isNegativeLE(x, P)) x = mod(-x); // 10\n    const y = mod(u1 * Dy); // 11\n    const t = mod(x * y); // 12\n    if (!isValid || isNegativeLE(t, P) || y === _0n)\n      throw new Error('invalid ristretto255 encoding 2');\n    return new _RistrettoPoint(new ed25519.Point(x, y, _1n, t));\n  }\n\n  /**\n   * Converts ristretto-encoded string to ristretto point.\n   * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-decode).\n   * @param hex Ristretto-encoded 32 bytes. Not every 32-byte string is valid ristretto encoding\n   */\n  static fromHex(hex: Hex): _RistrettoPoint {\n    return _RistrettoPoint.fromBytes(ensureBytes('ristrettoHex', hex, 32));\n  }\n\n  static msm(points: _RistrettoPoint[], scalars: bigint[]): _RistrettoPoint {\n    return pippenger(_RistrettoPoint, ed25519.Point.Fn, points, scalars);\n  }\n\n  /**\n   * Encodes ristretto point to Uint8Array.\n   * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-encode).\n   */\n  toBytes(): Uint8Array {\n    let { X, Y, Z, T } = this.ep;\n    const P = ed25519_CURVE_p;\n    const mod = (n: bigint) => Fp.create(n);\n    const u1 = mod(mod(Z + Y) * mod(Z - Y)); // 1\n    const u2 = mod(X * Y); // 2\n    // Square root always exists\n    const u2sq = mod(u2 * u2);\n    const { value: invsqrt } = invertSqrt(mod(u1 * u2sq)); // 3\n    const D1 = mod(invsqrt * u1); // 4\n    const D2 = mod(invsqrt * u2); // 5\n    const zInv = mod(D1 * D2 * T); // 6\n    let D: bigint; // 7\n    if (isNegativeLE(T * zInv, P)) {\n      let _x = mod(Y * SQRT_M1);\n      let _y = mod(X * SQRT_M1);\n      X = _x;\n      Y = _y;\n      D = mod(D1 * INVSQRT_A_MINUS_D);\n    } else {\n      D = D2; // 8\n    }\n    if (isNegativeLE(X * zInv, P)) Y = mod(-Y); // 9\n    let s = mod((Z - Y) * D); // 10 (check footer's note, no sqrt(-a))\n    if (isNegativeLE(s, P)) s = mod(-s);\n    return Fp.toBytes(s); // 11\n  }\n\n  /**\n   * Compares two Ristretto points.\n   * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-equals).\n   */\n  equals(other: _RistrettoPoint): boolean {\n    this.assertSame(other);\n    const { X: X1, Y: Y1 } = this.ep;\n    const { X: X2, Y: Y2 } = other.ep;\n    const mod = (n: bigint) => Fp.create(n);\n    // (x1 * y2 == y1 * x2) | (y1 * y2 == x1 * x2)\n    const one = mod(X1 * Y2) === mod(Y1 * X2);\n    const two = mod(Y1 * Y2) === mod(X1 * X2);\n    return one || two;\n  }\n\n  is0(): boolean {\n    return this.equals(_RistrettoPoint.ZERO);\n  }\n}\n\nexport const ristretto255: {\n  Point: typeof _RistrettoPoint;\n} = { Point: _RistrettoPoint };\n\n/** Hashing to ristretto255 points / field. RFC 9380 methods. */\nexport const ristretto255_hasher: H2CHasherBase<bigint> = {\n  hashToCurve(msg: Uint8Array, options?: htfBasicOpts): _RistrettoPoint {\n    const DST = options?.DST || 'ristretto255_XMD:SHA-512_R255MAP_RO_';\n    const xmd = expand_message_xmd(msg, DST, 64, sha512);\n    return ristretto255_map(xmd);\n  },\n  hashToScalar(msg: Uint8Array, options: htfBasicOpts = { DST: _DST_scalar }) {\n    const xmd = expand_message_xmd(msg, options.DST, 64, sha512);\n    return Fn.create(bytesToNumberLE(xmd));\n  },\n};\n\n// export const ristretto255_oprf: OPRF = createORPF({\n//   name: 'ristretto255-SHA512',\n//   Point: RistrettoPoint,\n//   hash: sha512,\n//   hashToGroup: ristretto255_hasher.hashToCurve,\n//   hashToScalar: ristretto255_hasher.hashToScalar,\n// });\n\n/**\n * Weird / bogus points, useful for debugging.\n * All 8 ed25519 points of 8-torsion subgroup can be generated from the point\n * T = `26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05`.\n * ⟨T⟩ = { O, T, 2T, 3T, 4T, 5T, 6T, 7T }\n */\nexport const ED25519_TORSION_SUBGROUP: string[] = [\n  '0100000000000000000000000000000000000000000000000000000000000000',\n  'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a',\n  '0000000000000000000000000000000000000000000000000000000000000080',\n  '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05',\n  'ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f',\n  '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85',\n  '0000000000000000000000000000000000000000000000000000000000000000',\n  'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa',\n];\n\n/** @deprecated use `ed25519.utils.toMontgomery` */\nexport function edwardsToMontgomeryPub(edwardsPub: Hex): Uint8Array {\n  return ed25519.utils.toMontgomery(ensureBytes('pub', edwardsPub));\n}\n/** @deprecated use `ed25519.utils.toMontgomery` */\nexport const edwardsToMontgomery: typeof edwardsToMontgomeryPub = edwardsToMontgomeryPub;\n\n/** @deprecated use `ed25519.utils.toMontgomerySecret` */\nexport function edwardsToMontgomeryPriv(edwardsPriv: Uint8Array): Uint8Array {\n  return ed25519.utils.toMontgomerySecret(ensureBytes('pub', edwardsPriv));\n}\n\n/** @deprecated use `ristretto255.Point` */\nexport const RistrettoPoint: typeof _RistrettoPoint = _RistrettoPoint;\n/** @deprecated use `import { ed25519_hasher } from '@noble/curves/ed25519.js';` */\nexport const hashToCurve: H2CMethod<bigint> = /* @__PURE__ */ (() => ed25519_hasher.hashToCurve)();\n/** @deprecated use `import { ed25519_hasher } from '@noble/curves/ed25519.js';` */\nexport const encodeToCurve: H2CMethod<bigint> = /* @__PURE__ */ (() =>\n  ed25519_hasher.encodeToCurve)();\ntype RistHasher = (msg: Uint8Array, options: htfBasicOpts) => _RistrettoPoint;\n/** @deprecated use `import { ristretto255_hasher } from '@noble/curves/ed25519.js';` */\nexport const hashToRistretto255: RistHasher = /* @__PURE__ */ (() =>\n  ristretto255_hasher.hashToCurve as RistHasher)();\n/** @deprecated use `import { ristretto255_hasher } from '@noble/curves/ed25519.js';` */\nexport const hash_to_ristretto255: RistHasher = /* @__PURE__ */ (() =>\n  ristretto255_hasher.hashToCurve as RistHasher)();\n","/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n\nexport interface Coder<F, T> {\n  encode(from: F): T;\n  decode(to: T): F;\n}\n\nexport interface BytesCoder extends Coder<Uint8Array, string> {\n  encode: (data: Uint8Array) => string;\n  decode: (str: string) => Uint8Array;\n}\n\nfunction isBytes(a: unknown): a is Uint8Array {\n  return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n/** Asserts something is Uint8Array. */\nfunction abytes(b: Uint8Array | undefined, ...lengths: number[]): void {\n  if (!isBytes(b)) throw new Error('Uint8Array expected');\n  if (lengths.length > 0 && !lengths.includes(b.length))\n    throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);\n}\n\nfunction isArrayOf(isString: boolean, arr: any[]) {\n  if (!Array.isArray(arr)) return false;\n  if (arr.length === 0) return true;\n  if (isString) {\n    return arr.every((item) => typeof item === 'string');\n  } else {\n    return arr.every((item) => Number.isSafeInteger(item));\n  }\n}\n\n// no abytes: seems to have 10% slowdown. Why?!\n\nfunction afn(input: Function): input is Function {\n  if (typeof input !== 'function') throw new Error('function expected');\n  return true;\n}\n\nfunction astr(label: string, input: unknown): input is string {\n  if (typeof input !== 'string') throw new Error(`${label}: string expected`);\n  return true;\n}\n\nfunction anumber(n: number): void {\n  if (!Number.isSafeInteger(n)) throw new Error(`invalid integer: ${n}`);\n}\n\nfunction aArr(input: any[]) {\n  if (!Array.isArray(input)) throw new Error('array expected');\n}\nfunction astrArr(label: string, input: string[]) {\n  if (!isArrayOf(true, input)) throw new Error(`${label}: array of strings expected`);\n}\nfunction anumArr(label: string, input: number[]) {\n  if (!isArrayOf(false, input)) throw new Error(`${label}: array of numbers expected`);\n}\n\n// TODO: some recusive type inference so it would check correct order of input/output inside rest?\n// like <string, number>, <number, bytes>, <bytes, float>\ntype Chain = [Coder<any, any>, ...Coder<any, any>[]];\n// Extract info from Coder type\ntype Input<F> = F extends Coder<infer T, any> ? T : never;\ntype Output<F> = F extends Coder<any, infer T> ? T : never;\n// Generic function for arrays\ntype First<T> = T extends [infer U, ...any[]] ? U : never;\ntype Last<T> = T extends [...any[], infer U] ? U : never;\ntype Tail<T> = T extends [any, ...infer U] ? U : never;\n\ntype AsChain<C extends Chain, Rest = Tail<C>> = {\n  // C[K] = Coder<Input<C[K]>, Input<Rest[k]>>\n  [K in keyof C]: Coder<Input<C[K]>, Input<K extends keyof Rest ? Rest[K] : any>>;\n};\n\n/**\n * @__NO_SIDE_EFFECTS__\n */\nfunction chain<T extends Chain & AsChain<T>>(...args: T): Coder<Input<First<T>>, Output<Last<T>>> {\n  const id = (a: any) => a;\n  // Wrap call in closure so JIT can inline calls\n  const wrap = (a: any, b: any) => (c: any) => a(b(c));\n  // Construct chain of args[-1].encode(args[-2].encode([...]))\n  const encode = args.map((x) => x.encode).reduceRight(wrap, id);\n  // Construct chain of args[0].decode(args[1].decode(...))\n  const decode = args.map((x) => x.decode).reduce(wrap, id);\n  return { encode, decode };\n}\n\n/**\n * Encodes integer radix representation to array of strings using alphabet and back.\n * Could also be array of strings.\n * @__NO_SIDE_EFFECTS__\n */\nfunction alphabet(letters: string | string[]): Coder<number[], string[]> {\n  // mapping 1 to \"b\"\n  const lettersA = typeof letters === 'string' ? letters.split('') : letters;\n  const len = lettersA.length;\n  astrArr('alphabet', lettersA);\n\n  // mapping \"b\" to 1\n  const indexes = new Map(lettersA.map((l, i) => [l, i]));\n  return {\n    encode: (digits: number[]) => {\n      aArr(digits);\n      return digits.map((i) => {\n        if (!Number.isSafeInteger(i) || i < 0 || i >= len)\n          throw new Error(\n            `alphabet.encode: digit index outside alphabet \"${i}\". Allowed: ${letters}`\n          );\n        return lettersA[i]!;\n      });\n    },\n    decode: (input: string[]): number[] => {\n      aArr(input);\n      return input.map((letter) => {\n        astr('alphabet.decode', letter);\n        const i = indexes.get(letter);\n        if (i === undefined) throw new Error(`Unknown letter: \"${letter}\". Allowed: ${letters}`);\n        return i;\n      });\n    },\n  };\n}\n\n/**\n * @__NO_SIDE_EFFECTS__\n */\nfunction join(separator = ''): Coder<string[], string> {\n  astr('join', separator);\n  return {\n    encode: (from) => {\n      astrArr('join.decode', from);\n      return from.join(separator);\n    },\n    decode: (to) => {\n      astr('join.decode', to);\n      return to.split(separator);\n    },\n  };\n}\n\n/**\n * Pad strings array so it has integer number of bits\n * @__NO_SIDE_EFFECTS__\n */\nfunction padding(bits: number, chr = '='): Coder<string[], string[]> {\n  anumber(bits);\n  astr('padding', chr);\n  return {\n    encode(data: string[]): string[] {\n      astrArr('padding.encode', data);\n      while ((data.length * bits) % 8) data.push(chr);\n      return data;\n    },\n    decode(input: string[]): string[] {\n      astrArr('padding.decode', input);\n      let end = input.length;\n      if ((end * bits) % 8)\n        throw new Error('padding: invalid, string should have whole number of bytes');\n      for (; end > 0 && input[end - 1] === chr; end--) {\n        const last = end - 1;\n        const byte = last * bits;\n        if (byte % 8 === 0) throw new Error('padding: invalid, string has too much padding');\n      }\n      return input.slice(0, end);\n    },\n  };\n}\n\n/**\n * @__NO_SIDE_EFFECTS__\n */\nfunction normalize<T>(fn: (val: T) => T): Coder<T, T> {\n  afn(fn);\n  return { encode: (from: T) => from, decode: (to: T) => fn(to) };\n}\n\n/**\n * Slow: O(n^2) time complexity\n */\nfunction convertRadix(data: number[], from: number, to: number): number[] {\n  // base 1 is impossible\n  if (from < 2) throw new Error(`convertRadix: invalid from=${from}, base cannot be less than 2`);\n  if (to < 2) throw new Error(`convertRadix: invalid to=${to}, base cannot be less than 2`);\n  aArr(data);\n  if (!data.length) return [];\n  let pos = 0;\n  const res = [];\n  const digits = Array.from(data, (d) => {\n    anumber(d);\n    if (d < 0 || d >= from) throw new Error(`invalid integer: ${d}`);\n    return d;\n  });\n  const dlen = digits.length;\n  while (true) {\n    let carry = 0;\n    let done = true;\n    for (let i = pos; i < dlen; i++) {\n      const digit = digits[i]!;\n      const fromCarry = from * carry;\n      const digitBase = fromCarry + digit;\n      if (\n        !Number.isSafeInteger(digitBase) ||\n        fromCarry / from !== carry ||\n        digitBase - digit !== fromCarry\n      ) {\n        throw new Error('convertRadix: carry overflow');\n      }\n      const div = digitBase / to;\n      carry = digitBase % to;\n      const rounded = Math.floor(div);\n      digits[i] = rounded;\n      if (!Number.isSafeInteger(rounded) || rounded * to + carry !== digitBase)\n        throw new Error('convertRadix: carry overflow');\n      if (!done) continue;\n      else if (!rounded) pos = i;\n      else done = false;\n    }\n    res.push(carry);\n    if (done) break;\n  }\n  for (let i = 0; i < data.length - 1 && data[i] === 0; i++) res.push(0);\n  return res.reverse();\n}\n\nconst gcd = (a: number, b: number): number => (b === 0 ? a : gcd(b, a % b));\nconst radix2carry = /* @__NO_SIDE_EFFECTS__ */ (from: number, to: number) =>\n  from + (to - gcd(from, to));\nconst powers: number[] = /* @__PURE__ */ (() => {\n  let res = [];\n  for (let i = 0; i < 40; i++) res.push(2 ** i);\n  return res;\n})();\n/**\n * Implemented with numbers, because BigInt is 5x slower\n */\nfunction convertRadix2(data: number[], from: number, to: number, padding: boolean): number[] {\n  aArr(data);\n  if (from <= 0 || from > 32) throw new Error(`convertRadix2: wrong from=${from}`);\n  if (to <= 0 || to > 32) throw new Error(`convertRadix2: wrong to=${to}`);\n  if (radix2carry(from, to) > 32) {\n    throw new Error(\n      `convertRadix2: carry overflow from=${from} to=${to} carryBits=${radix2carry(from, to)}`\n    );\n  }\n  let carry = 0;\n  let pos = 0; // bitwise position in current element\n  const max = powers[from]!;\n  const mask = powers[to]! - 1;\n  const res: number[] = [];\n  for (const n of data) {\n    anumber(n);\n    if (n >= max) throw new Error(`convertRadix2: invalid data word=${n} from=${from}`);\n    carry = (carry << from) | n;\n    if (pos + from > 32) throw new Error(`convertRadix2: carry overflow pos=${pos} from=${from}`);\n    pos += from;\n    for (; pos >= to; pos -= to) res.push(((carry >> (pos - to)) & mask) >>> 0);\n    const pow = powers[pos];\n    if (pow === undefined) throw new Error('invalid carry');\n    carry &= pow - 1; // clean carry, otherwise it will cause overflow\n  }\n  carry = (carry << (to - pos)) & mask;\n  if (!padding && pos >= from) throw new Error('Excess padding');\n  if (!padding && carry > 0) throw new Error(`Non-zero padding: ${carry}`);\n  if (padding && pos > 0) res.push(carry >>> 0);\n  return res;\n}\n\n/**\n * @__NO_SIDE_EFFECTS__\n */\nfunction radix(num: number): Coder<Uint8Array, number[]> {\n  anumber(num);\n  const _256 = 2 ** 8;\n  return {\n    encode: (bytes: Uint8Array) => {\n      if (!isBytes(bytes)) throw new Error('radix.encode input should be Uint8Array');\n      return convertRadix(Array.from(bytes), _256, num);\n    },\n    decode: (digits: number[]) => {\n      anumArr('radix.decode', digits);\n      return Uint8Array.from(convertRadix(digits, num, _256));\n    },\n  };\n}\n\n/**\n * If both bases are power of same number (like `2**8 <-> 2**64`),\n * there is a linear algorithm. For now we have implementation for power-of-two bases only.\n * @__NO_SIDE_EFFECTS__\n */\nfunction radix2(bits: number, revPadding = false): Coder<Uint8Array, number[]> {\n  anumber(bits);\n  if (bits <= 0 || bits > 32) throw new Error('radix2: bits should be in (0..32]');\n  if (radix2carry(8, bits) > 32 || radix2carry(bits, 8) > 32)\n    throw new Error('radix2: carry overflow');\n  return {\n    encode: (bytes: Uint8Array) => {\n      if (!isBytes(bytes)) throw new Error('radix2.encode input should be Uint8Array');\n      return convertRadix2(Array.from(bytes), 8, bits, !revPadding);\n    },\n    decode: (digits: number[]) => {\n      anumArr('radix2.decode', digits);\n      return Uint8Array.from(convertRadix2(digits, bits, 8, revPadding));\n    },\n  };\n}\n\ntype ArgumentTypes<F extends Function> = F extends (...args: infer A) => any ? A : never;\nfunction unsafeWrapper<T extends (...args: any) => any>(fn: T) {\n  afn(fn);\n  return function (...args: ArgumentTypes<T>): ReturnType<T> | void {\n    try {\n      return fn.apply(null, args);\n    } catch (e) {}\n  };\n}\n\nfunction checksum(\n  len: number,\n  fn: (data: Uint8Array) => Uint8Array\n): Coder<Uint8Array, Uint8Array> {\n  anumber(len);\n  afn(fn);\n  return {\n    encode(data: Uint8Array) {\n      if (!isBytes(data)) throw new Error('checksum.encode: input should be Uint8Array');\n      const sum = fn(data).slice(0, len);\n      const res = new Uint8Array(data.length + len);\n      res.set(data);\n      res.set(sum, data.length);\n      return res;\n    },\n    decode(data: Uint8Array) {\n      if (!isBytes(data)) throw new Error('checksum.decode: input should be Uint8Array');\n      const payload = data.slice(0, -len);\n      const oldChecksum = data.slice(-len);\n      const newChecksum = fn(payload).slice(0, len);\n      for (let i = 0; i < len; i++)\n        if (newChecksum[i] !== oldChecksum[i]) throw new Error('Invalid checksum');\n      return payload;\n    },\n  };\n}\n\n// prettier-ignore\nexport const utils: { alphabet: typeof alphabet; chain: typeof chain; checksum: typeof checksum; convertRadix: typeof convertRadix; convertRadix2: typeof convertRadix2; radix: typeof radix; radix2: typeof radix2; join: typeof join; padding: typeof padding; } = {\n  alphabet, chain, checksum, convertRadix, convertRadix2, radix, radix2, join, padding,\n};\n\n// RFC 4648 aka RFC 3548\n// ---------------------\n\n/**\n * base16 encoding from RFC 4648.\n * @example\n * ```js\n * base16.encode(Uint8Array.from([0x12, 0xab]));\n * // => '12AB'\n * ```\n */\nexport const base16: BytesCoder = chain(radix2(4), alphabet('0123456789ABCDEF'), join(''));\n\n/**\n * base32 encoding from RFC 4648. Has padding.\n * Use `base32nopad` for unpadded version.\n * Also check out `base32hex`, `base32hexnopad`, `base32crockford`.\n * @example\n * ```js\n * base32.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'CKVQ===='\n * base32.decode('CKVQ====');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32: BytesCoder = chain(\n  radix2(5),\n  alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'),\n  padding(5),\n  join('')\n);\n\n/**\n * base32 encoding from RFC 4648. No padding.\n * Use `base32` for padded version.\n * Also check out `base32hex`, `base32hexnopad`, `base32crockford`.\n * @example\n * ```js\n * base32nopad.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'CKVQ'\n * base32nopad.decode('CKVQ');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32nopad: BytesCoder = chain(\n  radix2(5),\n  alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'),\n  join('')\n);\n/**\n * base32 encoding from RFC 4648. Padded. Compared to ordinary `base32`, slightly different alphabet.\n * Use `base32hexnopad` for unpadded version.\n * @example\n * ```js\n * base32hex.encode(Uint8Array.from([0x12, 0xab]));\n * // => '2ALG===='\n * base32hex.decode('2ALG====');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32hex: BytesCoder = chain(\n  radix2(5),\n  alphabet('0123456789ABCDEFGHIJKLMNOPQRSTUV'),\n  padding(5),\n  join('')\n);\n\n/**\n * base32 encoding from RFC 4648. No padding. Compared to ordinary `base32`, slightly different alphabet.\n * Use `base32hex` for padded version.\n * @example\n * ```js\n * base32hexnopad.encode(Uint8Array.from([0x12, 0xab]));\n * // => '2ALG'\n * base32hexnopad.decode('2ALG');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32hexnopad: BytesCoder = chain(\n  radix2(5),\n  alphabet('0123456789ABCDEFGHIJKLMNOPQRSTUV'),\n  join('')\n);\n/**\n * base32 encoding from RFC 4648. Doug Crockford's version.\n * https://www.crockford.com/base32.html\n * @example\n * ```js\n * base32crockford.encode(Uint8Array.from([0x12, 0xab]));\n * // => '2ANG'\n * base32crockford.decode('2ANG');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32crockford: BytesCoder = chain(\n  radix2(5),\n  alphabet('0123456789ABCDEFGHJKMNPQRSTVWXYZ'),\n  join(''),\n  normalize((s: string) => s.toUpperCase().replace(/O/g, '0').replace(/[IL]/g, '1'))\n);\n\n// Built-in base64 conversion https://caniuse.com/mdn-javascript_builtins_uint8array_frombase64\n// prettier-ignore\nconst hasBase64Builtin: boolean = /* @__PURE__ */ (() =>\n  typeof (Uint8Array as any).from([]).toBase64 === 'function' &&\n  typeof (Uint8Array as any).fromBase64 === 'function')();\n\nconst decodeBase64Builtin = (s: string, isUrl: boolean) => {\n  astr('base64', s);\n  const re = isUrl ? /^[A-Za-z0-9=_-]+$/ : /^[A-Za-z0-9=+/]+$/;\n  const alphabet = isUrl ? 'base64url' : 'base64';\n  if (s.length > 0 && !re.test(s)) throw new Error('invalid base64');\n  return (Uint8Array as any).fromBase64(s, { alphabet, lastChunkHandling: 'strict' });\n};\n\n/**\n * base64 from RFC 4648. Padded.\n * Use `base64nopad` for unpadded version.\n * Also check out `base64url`, `base64urlnopad`.\n * Falls back to built-in function, when available.\n * @example\n * ```js\n * base64.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'Eqs='\n * base64.decode('Eqs=');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\n// prettier-ignore\nexport const base64: BytesCoder = hasBase64Builtin ? {\n  encode(b) { abytes(b); return (b as any).toBase64(); },\n  decode(s) { return decodeBase64Builtin(s, false); },\n} : chain(\n  radix2(6),\n  alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'),\n  padding(6),\n  join('')\n);\n/**\n * base64 from RFC 4648. No padding.\n * Use `base64` for padded version.\n * @example\n * ```js\n * base64nopad.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'Eqs'\n * base64nopad.decode('Eqs');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base64nopad: BytesCoder = chain(\n  radix2(6),\n  alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'),\n  join('')\n);\n\n/**\n * base64 from RFC 4648, using URL-safe alphabet. Padded.\n * Use `base64urlnopad` for unpadded version.\n * Falls back to built-in function, when available.\n * @example\n * ```js\n * base64url.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'Eqs='\n * base64url.decode('Eqs=');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\n// prettier-ignore\nexport const base64url: BytesCoder = hasBase64Builtin ? {\n  encode(b) { abytes(b); return (b as any).toBase64({ alphabet: 'base64url' }); },\n  decode(s) { return decodeBase64Builtin(s, true); },\n} : chain(\n  radix2(6),\n  alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'),\n  padding(6),\n  join('')\n);\n\n/**\n * base64 from RFC 4648, using URL-safe alphabet. No padding.\n * Use `base64url` for padded version.\n * @example\n * ```js\n * base64urlnopad.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'Eqs'\n * base64urlnopad.decode('Eqs');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base64urlnopad: BytesCoder = chain(\n  radix2(6),\n  alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'),\n  join('')\n);\n\n// base58 code\n// -----------\nconst genBase58 = /* @__NO_SIDE_EFFECTS__ */ (abc: string) =>\n  chain(radix(58), alphabet(abc), join(''));\n\n/**\n * base58: base64 without ambigous characters +, /, 0, O, I, l.\n * Quadratic (O(n^2)) - so, can't be used on large inputs.\n * @example\n * ```js\n * base58.decode('01abcdef');\n * // => '3UhJW'\n * ```\n */\nexport const base58: BytesCoder = genBase58(\n  '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n);\n/**\n * base58: flickr version. Check out `base58`.\n */\nexport const base58flickr: BytesCoder = genBase58(\n  '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'\n);\n/**\n * base58: XRP version. Check out `base58`.\n */\nexport const base58xrp: BytesCoder = genBase58(\n  'rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz'\n);\n\n// Data len (index) -> encoded block len\nconst XMR_BLOCK_LEN = [0, 2, 3, 5, 6, 7, 9, 10, 11];\n\n/**\n * base58: XMR version. Check out `base58`.\n * Done in 8-byte blocks (which equals 11 chars in decoding). Last (non-full) block padded with '1' to size in XMR_BLOCK_LEN.\n * Block encoding significantly reduces quadratic complexity of base58.\n */\nexport const base58xmr: BytesCoder = {\n  encode(data: Uint8Array) {\n    let res = '';\n    for (let i = 0; i < data.length; i += 8) {\n      const block = data.subarray(i, i + 8);\n      res += base58.encode(block).padStart(XMR_BLOCK_LEN[block.length]!, '1');\n    }\n    return res;\n  },\n  decode(str: string) {\n    let res: number[] = [];\n    for (let i = 0; i < str.length; i += 11) {\n      const slice = str.slice(i, i + 11);\n      const blockLen = XMR_BLOCK_LEN.indexOf(slice.length);\n      const block = base58.decode(slice);\n      for (let j = 0; j < block.length - blockLen; j++) {\n        if (block[j] !== 0) throw new Error('base58xmr: wrong padding');\n      }\n      res = res.concat(Array.from(block.slice(block.length - blockLen)));\n    }\n    return Uint8Array.from(res);\n  },\n};\n\n/**\n * Method, which creates base58check encoder.\n * Requires function, calculating sha256.\n */\nexport const createBase58check = (sha256: (data: Uint8Array) => Uint8Array): BytesCoder =>\n  chain(\n    checksum(4, (data) => sha256(sha256(data))),\n    base58\n  );\n\n/**\n * Use `createBase58check` instead.\n * @deprecated\n */\nexport const base58check: (sha256: (data: Uint8Array) => Uint8Array) => BytesCoder =\n  createBase58check;\n\n// Bech32 code\n// -----------\nexport interface Bech32Decoded<Prefix extends string = string> {\n  prefix: Prefix;\n  words: number[];\n}\nexport interface Bech32DecodedWithArray<Prefix extends string = string> {\n  prefix: Prefix;\n  words: number[];\n  bytes: Uint8Array;\n}\n\nconst BECH_ALPHABET: Coder<number[], string> = chain(\n  alphabet('qpzry9x8gf2tvdw0s3jn54khce6mua7l'),\n  join('')\n);\n\nconst POLYMOD_GENERATORS = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3];\nfunction bech32Polymod(pre: number): number {\n  const b = pre >> 25;\n  let chk = (pre & 0x1ffffff) << 5;\n  for (let i = 0; i < POLYMOD_GENERATORS.length; i++) {\n    if (((b >> i) & 1) === 1) chk ^= POLYMOD_GENERATORS[i]!;\n  }\n  return chk;\n}\n\nfunction bechChecksum(prefix: string, words: number[], encodingConst = 1): string {\n  const len = prefix.length;\n  let chk = 1;\n  for (let i = 0; i < len; i++) {\n    const c = prefix.charCodeAt(i);\n    if (c < 33 || c > 126) throw new Error(`Invalid prefix (${prefix})`);\n    chk = bech32Polymod(chk) ^ (c >> 5);\n  }\n  chk = bech32Polymod(chk);\n  for (let i = 0; i < len; i++) chk = bech32Polymod(chk) ^ (prefix.charCodeAt(i) & 0x1f);\n  for (let v of words) chk = bech32Polymod(chk) ^ v;\n  for (let i = 0; i < 6; i++) chk = bech32Polymod(chk);\n  chk ^= encodingConst;\n  return BECH_ALPHABET.encode(convertRadix2([chk % powers[30]!], 30, 5, false));\n}\n\nexport interface Bech32 {\n  encode<Prefix extends string>(\n    prefix: Prefix,\n    words: number[] | Uint8Array,\n    limit?: number | false\n  ): `${Lowercase<Prefix>}1${string}`;\n  decode<Prefix extends string>(\n    str: `${Prefix}1${string}`,\n    limit?: number | false\n  ): Bech32Decoded<Prefix>;\n  encodeFromBytes(prefix: string, bytes: Uint8Array): string;\n  decodeToBytes(str: string): Bech32DecodedWithArray;\n  decodeUnsafe(str: string, limit?: number | false): void | Bech32Decoded<string>;\n  fromWords(to: number[]): Uint8Array;\n  fromWordsUnsafe(to: number[]): void | Uint8Array;\n  toWords(from: Uint8Array): number[];\n}\n/**\n * @__NO_SIDE_EFFECTS__\n */\nfunction genBech32(encoding: 'bech32' | 'bech32m'): Bech32 {\n  const ENCODING_CONST = encoding === 'bech32' ? 1 : 0x2bc830a3;\n  const _words = radix2(5);\n  const fromWords = _words.decode;\n  const toWords = _words.encode;\n  const fromWordsUnsafe = unsafeWrapper(fromWords);\n\n  function encode<Prefix extends string>(\n    prefix: Prefix,\n    words: number[] | Uint8Array,\n    limit: number | false = 90\n  ): `${Lowercase<Prefix>}1${string}` {\n    astr('bech32.encode prefix', prefix);\n    if (isBytes(words)) words = Array.from(words);\n    anumArr('bech32.encode', words);\n    const plen = prefix.length;\n    if (plen === 0) throw new TypeError(`Invalid prefix length ${plen}`);\n    const actualLength = plen + 7 + words.length;\n    if (limit !== false && actualLength > limit)\n      throw new TypeError(`Length ${actualLength} exceeds limit ${limit}`);\n    const lowered = prefix.toLowerCase();\n    const sum = bechChecksum(lowered, words, ENCODING_CONST);\n    return `${lowered}1${BECH_ALPHABET.encode(words)}${sum}` as `${Lowercase<Prefix>}1${string}`;\n  }\n\n  function decode<Prefix extends string>(\n    str: `${Prefix}1${string}`,\n    limit?: number | false\n  ): Bech32Decoded<Prefix>;\n  function decode(str: string, limit?: number | false): Bech32Decoded;\n  function decode(str: string, limit: number | false = 90): Bech32Decoded {\n    astr('bech32.decode input', str);\n    const slen = str.length;\n    if (slen < 8 || (limit !== false && slen > limit))\n      throw new TypeError(`invalid string length: ${slen} (${str}). Expected (8..${limit})`);\n    // don't allow mixed case\n    const lowered = str.toLowerCase();\n    if (str !== lowered && str !== str.toUpperCase())\n      throw new Error(`String must be lowercase or uppercase`);\n    const sepIndex = lowered.lastIndexOf('1');\n    if (sepIndex === 0 || sepIndex === -1)\n      throw new Error(`Letter \"1\" must be present between prefix and data only`);\n    const prefix = lowered.slice(0, sepIndex);\n    const data = lowered.slice(sepIndex + 1);\n    if (data.length < 6) throw new Error('Data must be at least 6 characters long');\n    const words = BECH_ALPHABET.decode(data).slice(0, -6);\n    const sum = bechChecksum(prefix, words, ENCODING_CONST);\n    if (!data.endsWith(sum)) throw new Error(`Invalid checksum in ${str}: expected \"${sum}\"`);\n    return { prefix, words };\n  }\n\n  const decodeUnsafe = unsafeWrapper(decode);\n\n  function decodeToBytes(str: string): Bech32DecodedWithArray {\n    const { prefix, words } = decode(str, false);\n    return { prefix, words, bytes: fromWords(words) };\n  }\n\n  function encodeFromBytes(prefix: string, bytes: Uint8Array) {\n    return encode(prefix, toWords(bytes));\n  }\n\n  return {\n    encode,\n    decode,\n    encodeFromBytes,\n    decodeToBytes,\n    decodeUnsafe,\n    fromWords,\n    fromWordsUnsafe,\n    toWords,\n  };\n}\n\n/**\n * bech32 from BIP 173. Operates on words.\n * For high-level, check out scure-btc-signer:\n * https://github.com/paulmillr/scure-btc-signer.\n */\nexport const bech32: Bech32 = genBech32('bech32');\n\n/**\n * bech32m from BIP 350. Operates on words.\n * It was to mitigate `bech32` weaknesses.\n * For high-level, check out scure-btc-signer:\n * https://github.com/paulmillr/scure-btc-signer.\n */\nexport const bech32m: Bech32 = genBech32('bech32m');\n\ndeclare const TextEncoder: any;\ndeclare const TextDecoder: any;\n\n/**\n * UTF-8-to-byte decoder. Uses built-in TextDecoder / TextEncoder.\n * @example\n * ```js\n * const b = utf8.decode(\"hey\"); // => new Uint8Array([ 104, 101, 121 ])\n * const str = utf8.encode(b); // \"hey\"\n * ```\n */\nexport const utf8: BytesCoder = {\n  encode: (data) => new TextDecoder().decode(data),\n  decode: (str) => new TextEncoder().encode(str),\n};\n\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\n// prettier-ignore\nconst hasHexBuiltin: boolean = /* @__PURE__ */ (() =>\n  typeof (Uint8Array as any).from([]).toHex === 'function' &&\n  typeof (Uint8Array as any).fromHex === 'function')();\n// prettier-ignore\nconst hexBuiltin: BytesCoder = {\n  encode(data) { abytes(data); return (data as any).toHex(); },\n  decode(s) { astr('hex', s); return (Uint8Array as any).fromHex(s); },\n};\n/**\n * hex string decoder. Uses built-in function, when available.\n * @example\n * ```js\n * const b = hex.decode(\"0102ff\"); // => new Uint8Array([ 1, 2, 255 ])\n * const str = hex.encode(b); // \"0102ff\"\n * ```\n */\nexport const hex: BytesCoder = hasHexBuiltin\n  ? hexBuiltin\n  : chain(\n      radix2(4),\n      alphabet('0123456789abcdef'),\n      join(''),\n      normalize((s: string) => {\n        if (typeof s !== 'string' || s.length % 2 !== 0)\n          throw new TypeError(\n            `hex.decode: expected string, got ${typeof s} with length ${s.length}`\n          );\n        return s.toLowerCase();\n      })\n    );\n\nexport type SomeCoders = {\n  utf8: BytesCoder;\n  hex: BytesCoder;\n  base16: BytesCoder;\n  base32: BytesCoder;\n  base64: BytesCoder;\n  base64url: BytesCoder;\n  base58: BytesCoder;\n  base58xmr: BytesCoder;\n};\n// prettier-ignore\nconst CODERS: SomeCoders = {\n  utf8, hex, base16, base32, base64, base64url, base58, base58xmr\n};\ntype CoderType = keyof SomeCoders;\nconst coderTypeError =\n  'Invalid encoding type. Available types: utf8, hex, base16, base32, base64, base64url, base58, base58xmr';\n\n/** @deprecated */\nexport const bytesToString = (type: CoderType, bytes: Uint8Array): string => {\n  if (typeof type !== 'string' || !CODERS.hasOwnProperty(type)) throw new TypeError(coderTypeError);\n  if (!isBytes(bytes)) throw new TypeError('bytesToString() expects Uint8Array');\n  return CODERS[type].encode(bytes);\n};\n\n/** @deprecated */\nexport const str: (type: CoderType, bytes: Uint8Array) => string = bytesToString; // as in python, but for bytes only\n\n/** @deprecated */\nexport const stringToBytes = (type: CoderType, str: string): Uint8Array => {\n  if (!CODERS.hasOwnProperty(type)) throw new TypeError(coderTypeError);\n  if (typeof str !== 'string') throw new TypeError('stringToBytes() expects string');\n  return CODERS[type].decode(str);\n};\n/** @deprecated */\nexport const bytes: (type: CoderType, str: string) => Uint8Array = stringToBytes;\n","import { ed25519 } from '@noble/curves/ed25519';\nimport { base58 } from '@scure/base';\nimport { bytesToHex, isAddress, sha256 } from 'viem';\nimport { solanaAddress } from '../../chains/non-evm.js';\nconst textEncoder = new TextEncoder();\nconst PROGRAM_DERIVED_ADDRESS_MARKER = textEncoder.encode('ProgramDerivedAddress');\nconst SWIG_SEED = textEncoder.encode('swig');\nconst SWIG_WALLET_SEED = textEncoder.encode('swig-wallet-address');\nconst MAX_SEEDS = 16;\nconst MAX_SEED_LENGTH = 32;\n/** Program used by classic Swig accounts on Solana. */\nconst SWIG_PROGRAM_ADDRESS = solanaAddress('swigypWHEksbC64pWKwah1WTeh9JXwx8H1rJHLdbQMB');\nclass OnCurveAddressError extends Error {\n}\nfunction concatBytes(values) {\n    const result = new Uint8Array(values.reduce((length, value) => length + value.length, 0));\n    let offset = 0;\n    for (const value of values) {\n        result.set(value, offset);\n        offset += value.length;\n    }\n    return result;\n}\nfunction decodeAddress(value) {\n    const bytes = base58.decode(value);\n    if (bytes.length !== 32) {\n        throw new TypeError('Invalid Solana address: expected 32 bytes');\n    }\n    return bytes;\n}\nfunction isOnCurve(bytes) {\n    try {\n        ed25519.ExtendedPoint.fromHex(bytes);\n        return true;\n    }\n    catch {\n        return false;\n    }\n}\nfunction createProgramAddress(seeds, programAddress) {\n    if (seeds.length > MAX_SEEDS) {\n        throw new TypeError(`Too many PDA seeds: expected at most ${MAX_SEEDS}`);\n    }\n    for (const seed of seeds) {\n        if (seed.length > MAX_SEED_LENGTH) {\n            throw new TypeError(`Invalid PDA seed: expected at most ${MAX_SEED_LENGTH} bytes`);\n        }\n    }\n    const bytes = sha256(concatBytes([\n        ...seeds,\n        decodeAddress(programAddress),\n        PROGRAM_DERIVED_ADDRESS_MARKER,\n    ]), 'bytes');\n    if (isOnCurve(bytes)) {\n        throw new OnCurveAddressError('Invalid PDA seeds: address must fall off the curve');\n    }\n    return solanaAddress(base58.encode(bytes));\n}\nfunction findProgramAddress(seeds, programAddress) {\n    if (seeds.length >= MAX_SEEDS) {\n        throw new TypeError(`Too many PDA seeds: expected at most ${MAX_SEEDS - 1} before the bump`);\n    }\n    for (let bump = 255; bump >= 0; bump--) {\n        try {\n            return {\n                address: createProgramAddress([...seeds, Uint8Array.of(bump)], programAddress),\n                bump,\n            };\n        }\n        catch (error) {\n            if (!(error instanceof OnCurveAddressError))\n                throw error;\n        }\n    }\n    /* v8 ignore next -- exhausting every SHA-256 bump is not constructible */\n    throw new Error('Unable to find a viable program address bump');\n}\nfunction asSwigNamespace(value) {\n    if (!/^[a-z0-9-]{1,32}$/.test(value)) {\n        throw new TypeError(`Invalid Swig namespace \"${value}\": expected 1-32 chars of [a-z0-9-]`);\n    }\n    return value;\n}\n/**\n * The Swig namespace each environment's orchestrator derives EVM-paired Swigs\n * under (its `SOLANA_SWIG_NAMESPACE`). A mismatch derives a different Swig than\n * the backend expects, so these must track the deployed configuration.\n */\nconst MANAGED_SWIG_NAMESPACES = {\n    development: 'dev-v1',\n    production: 'prod-v1',\n};\nfunction isManagedSwigNamespace(value) {\n    return Object.values(MANAGED_SWIG_NAMESPACES).includes(value);\n}\nfunction swigId(namespace, evmAccount) {\n    if (!isAddress(evmAccount, { strict: false })) {\n        throw new TypeError(`Invalid EVM account address: ${evmAccount}`);\n    }\n    return sha256(textEncoder.encode(`rhinestone:swig:v1:${namespace}:${evmAccount.toLowerCase()}`), 'bytes');\n}\n/** The asset-holding wallet PDA of a Swig state account. */\nfunction locateSwigWallet(swig) {\n    return findProgramAddress([SWIG_WALLET_SEED, decodeAddress(swig)], SWIG_PROGRAM_ADDRESS);\n}\n/** The Swig state account and wallet a 32-byte Swig id derives. */\nfunction locateSwigById(id) {\n    if (id.length !== 32) {\n        throw new TypeError('Invalid Swig id: expected 32 bytes');\n    }\n    const swig = findProgramAddress([SWIG_SEED, id], SWIG_PROGRAM_ADDRESS);\n    const wallet = locateSwigWallet(swig.address);\n    return {\n        id,\n        swig: swig.address,\n        swigBump: swig.bump,\n        wallet: wallet.address,\n        walletBump: wallet.bump,\n    };\n}\nfunction locateSwig(namespace, evmAccount) {\n    const normalizedAccount = evmAccount.toLowerCase();\n    return {\n        namespace,\n        evmAccount: normalizedAccount,\n        ...locateSwigById(swigId(namespace, normalizedAccount)),\n    };\n}\n/**\n * Mints a fresh, random Swig id and the addresses it derives, for a Solana\n * account that is not tied to a managed EVM account.\n *\n * Persist `id` together with `swig`: configure the account with\n * `solana: { swig, owner }`, and pass the id to\n * `account.deploy('solana', solanaChain, { swigId: id })`\n * to create it. The id cannot be recovered from the addresses, so a lost id\n * leaves the Swig uncreatable; mint a new one instead.\n *\n * @returns The 32-byte Swig `id` as hex, the Swig state account `swig`, and\n * the asset-holding `wallet` that receives funds.\n * @example\n * ```ts\n * import { createSolanaSwigId } from '@rhinestone/sdk/solana'\n *\n * const { id, swig, wallet } = createSolanaSwigId()\n * // Save `id` and `swig`; fund `wallet` only after the Swig is created.\n * ```\n */\nfunction createSolanaSwigId() {\n    const id = crypto.getRandomValues(new Uint8Array(32));\n    const location = locateSwigById(id);\n    return { id: bytesToHex(id), swig: location.swig, wallet: location.wallet };\n}\nexport { MANAGED_SWIG_NAMESPACES, SWIG_PROGRAM_ADDRESS, asSwigNamespace, createProgramAddress, createSolanaSwigId, findProgramAddress, isManagedSwigNamespace, locateSwig, locateSwigById, locateSwigWallet, };\n","// Public destination chain descriptors for destinations that aren't a plain\n// viem `Chain`: the non-EVM chains (Solana, Tron, Stellar) plus HyperCore (an\n// EVM-settled\n// virtual L1). Mirrors the minimal shape of viem's `Chain` (name,\n// nativeCurrency) so callers can pass them anywhere a destination chain is\n// expected — `targetChain: solanaMainnet` reads the same as `targetChain:\n// optimism`.\n//\n// The wire format is the CAIP-2 string. Internally the SDK and the\n// orchestrator also use a synthetic numeric chain id derived from the\n// CAIP-2 mapping, but it is non-standard and intentionally not exposed\n// on this type.\nconst BASE58_ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';\n/** Validate and brand a canonical Solana address. */\nfunction solanaAddress(value) {\n    if (!value)\n        throw new TypeError('Invalid Solana address: expected 32 bytes');\n    let number = 0n;\n    for (const character of value) {\n        const digit = BASE58_ALPHABET.indexOf(character);\n        if (digit < 0) {\n            throw new TypeError('Invalid Solana address: expected canonical base58');\n        }\n        number = number * 58n + BigInt(digit);\n    }\n    let decodedLength = 0;\n    for (let remaining = number; remaining > 0n; remaining >>= 8n)\n        decodedLength++;\n    const leadingZeroes = value.length - value.replace(/^1+/, '').length;\n    if (decodedLength + leadingZeroes !== 32) {\n        throw new TypeError('Invalid Solana address: expected 32 bytes');\n    }\n    return value;\n}\nconst solanaMainnet = {\n    name: 'Solana',\n    caip2: 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp',\n    kind: 'svm',\n    nativeCurrency: { name: 'Solana', symbol: 'SOL', decimals: 9 },\n};\nconst solanaDevnet = {\n    name: 'Solana Devnet',\n    caip2: 'solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1',\n    kind: 'svm',\n    nativeCurrency: { name: 'Solana', symbol: 'SOL', decimals: 9 },\n    testnet: true,\n};\nconst tronMainnet = {\n    name: 'Tron',\n    caip2: 'tron:mainnet',\n    kind: 'tvm',\n    nativeCurrency: { name: 'Tron', symbol: 'TRX', decimals: 6 },\n};\n// Stellar addresses classic assets through Soroban contracts, so a token\n// request carries the asset's Stellar Asset Contract (a `C…` strkey) while the\n// recipient is an account (`G…`) — two different shapes in the same namespace.\nconst stellarMainnet = {\n    name: 'Stellar',\n    caip2: 'stellar:pubnet',\n    kind: 'stellar',\n    nativeCurrency: { name: 'Lumen', symbol: 'XLM', decimals: 7 },\n};\n// A HyperCore deposit credits one of two accounts that are not\n// interchangeable: the recipient's spot wallet, or the default perp dex's\n// margin account. `CoreDepositWallet.depositFor` selects between them, and the\n// wrong choice is invisible — the intent completes, the fill succeeds, and only\n// the recipient's Core state shows where the funds went. So the venue is the\n// destination you address, not an optional field that four separate\n// field-by-field rebuilds could each silently drop (RHI-5510).\nconst hyperCoreSpot = {\n    name: 'HyperCore Spot',\n    caip2: 'hypercore:spot',\n    kind: 'hypercore',\n    nativeCurrency: { name: 'Hyperliquid', symbol: 'HYPE', decimals: 18 },\n};\nconst hyperCorePerp = {\n    name: 'HyperCore Perp',\n    caip2: 'hypercore:perp',\n    kind: 'hypercore',\n    nativeCurrency: { name: 'Hyperliquid', symbol: 'HYPE', decimals: 18 },\n};\nexport { hyperCorePerp, hyperCoreSpot, solanaAddress, solanaDevnet, solanaMainnet, stellarMainnet, tronMainnet, };\n","export function captureLegacySdkConfig(input, authProvider) {\n    return {\n        authProvider,\n        endpointUrl: input.endpointUrl,\n        provider: input.provider,\n        bundler: input.bundler,\n        paymaster: input.paymaster,\n        useDevContracts: input.useDevContracts,\n        headers: input.headers,\n        hyperliquid: input.hyperliquid,\n    };\n}\nexport function createLegacyAccountConfig(input, sdk) {\n    return {\n        ...input,\n        _authProvider: sdk.authProvider,\n        endpointUrl: sdk.endpointUrl,\n        provider: sdk.provider,\n        bundler: sdk.bundler,\n        paymaster: sdk.paymaster,\n        useDevContracts: sdk.useDevContracts,\n        headers: sdk.headers,\n        hyperliquid: sdk.hyperliquid,\n    };\n}\n","export function ecdsaSignerId(account) {\n    const address = typeof account === 'string' ? account : account.address;\n    return `ecdsa:${address.toLowerCase()}`;\n}\nexport function webauthnSignerId(account) {\n    const publicKey = typeof account === 'string' ? account : account.publicKey;\n    return `webauthn:${publicKey.toLowerCase()}`;\n}\n","import { ecdsaSignerId, webauthnSignerId } from './signer-id.js';\nfunction moduleSelection(address, profile) {\n    return address === undefined\n        ? { source: 'default', profile }\n        : { source: 'explicit', address };\n}\nfunction defineAtomicValidator(input, id, publicId) {\n    const ownerId = (index) => `${id}/owner/${index}`;\n    switch (input.type) {\n        case 'ecdsa':\n            return {\n                kind: 'ecdsa',\n                id,\n                publicId,\n                module: moduleSelection(input.module, 'ownable'),\n                owners: input.accounts.map((account, index) => ({\n                    kind: 'ecdsa',\n                    id: ownerId(index),\n                    signerId: ecdsaSignerId(account),\n                    account,\n                })),\n                threshold: input.threshold ?? 1,\n            };\n        case 'quorum': {\n            const owners = input.owners.map((owner, index) => ({\n                kind: 'ecdsa',\n                id: ownerId(index),\n                signerId: ecdsaSignerId(owner.account),\n                account: owner.account,\n                weight: owner.weight,\n            }));\n            return {\n                kind: 'quorum',\n                id,\n                publicId,\n                module: { source: 'explicit', address: input.module },\n                owners,\n                threshold: owners.length,\n                thresholdWeight: input.thresholdWeight,\n            };\n        }\n        case 'ens':\n            return {\n                kind: 'ens',\n                id,\n                publicId,\n                module: moduleSelection(undefined, 'ens'),\n                owners: input.owners.map((owner, index) => ({\n                    kind: 'ens',\n                    id: ownerId(index),\n                    signerId: ecdsaSignerId(owner.account),\n                    account: owner.account,\n                    ...(owner.expiration ? { expiration: owner.expiration } : {}),\n                })),\n                threshold: input.threshold ?? 1,\n            };\n        case 'passkey':\n            return {\n                kind: 'passkey',\n                id,\n                publicId,\n                module: moduleSelection(input.module, 'webauthn'),\n                owners: input.accounts.map((account, index) => ({\n                    kind: 'webauthn',\n                    id: ownerId(index),\n                    signerId: webauthnSignerId(account),\n                    account,\n                })),\n                threshold: input.threshold ?? 1,\n            };\n    }\n}\nexport function defineValidator(input, id = 'owner-validator', publicId = 0) {\n    if (input.type !== 'multi-factor') {\n        return defineAtomicValidator(input, id, Number(publicId));\n    }\n    const definition = {\n        kind: 'multi-factor',\n        id,\n        publicId,\n        module: moduleSelection(input.module, 'multi-factor'),\n        validators: input.validators.map((validator, index) => defineAtomicValidator(validator, `${id}/factor/${index}`, index)),\n        threshold: input.threshold ?? 1,\n    };\n    return definition;\n}\n","import { concat, encodeAbiParameters, hexToBytes, toHex, } from 'viem';\nexport const OWNABLE_VALIDATOR_ADDRESS = '0x000000000013fdb5234e4e3162a810f54d9f7e98';\nexport const OWNABLE_V0_VALIDATOR_ADDRESS = '0x2483da3a338895199e5e538530213157e931bf06';\nexport const OWNABLE_BETA_VALIDATOR_ADDRESS = '0x0000000000e9e6e96bcaa3c113187cdb7e38aed9';\nexport const ECDSA_MOCK_SIGNATURE = '0x81d4b4981670cb18f99f0b4a66446df1bf5b204d24cfcb659bf38ba27a4359b5711649ec2423c5e1247245eba2964679b6a1dbb85c992ae40b9b00c6935b02ff1b';\nfunction moduleAddress(definition) {\n    return definition.module.source === 'explicit'\n        ? definition.module.address\n        : OWNABLE_VALIDATOR_ADDRESS;\n}\n/**\n * The configuration `OwnableValidator.validateSignatureWithData` expects: the\n * threshold followed by the sorted, uniquified owner list. Byte-identical to\n * the validator's install data, which is why the same encoder produces both.\n */\nexport function encodeOwnableStatelessData(input) {\n    return encodeAbiParameters([\n        { name: 'threshold', type: 'uint256' },\n        { name: 'owners', type: 'address[]' },\n    ], [\n        BigInt(input.threshold),\n        input.owners.map((owner) => owner.toLowerCase()).sort(),\n    ]);\n}\nexport function resolveOwnableAddresses(input) {\n    return {\n        kind: 'validator',\n        address: input.address ?? OWNABLE_VALIDATOR_ADDRESS,\n        initData: encodeOwnableStatelessData(input),\n        deInitData: '0x',\n        additionalContext: '0x',\n    };\n}\nfunction ownableDefinitionOwners(definition) {\n    return definition.owners\n        .map((owner) => {\n        if (owner.kind === 'webauthn') {\n            throw new Error('Ownable validator contains a WebAuthn owner');\n        }\n        return owner.account.address.toLowerCase();\n    })\n        .sort();\n}\nexport function resolveOwnableValidator(definition) {\n    return resolveOwnableAddresses({\n        owners: ownableDefinitionOwners(definition),\n        threshold: definition.threshold,\n        address: moduleAddress(definition),\n    });\n}\nexport function resolveOwnableStatelessData(definition) {\n    return encodeOwnableStatelessData({\n        owners: ownableDefinitionOwners(definition),\n        threshold: definition.threshold,\n    });\n}\nexport function encodeOwnableMockSignature(ownerCount) {\n    return concat(Array.from({ length: ownerCount }, () => ECDSA_MOCK_SIGNATURE));\n}\nexport function encodeEcdsaValidatorContribution(input) {\n    if (input.threshold < 1 || input.threshold > input.ownerOrder.length) {\n        throw new Error('Validator threshold is outside the configured owner set');\n    }\n    const configured = new Set(input.ownerOrder);\n    const contributions = new Map();\n    for (const contribution of input.contributions) {\n        if (!configured.has(contribution.ownerId)) {\n            throw new Error(`Unknown validator owner ${contribution.ownerId}`);\n        }\n        if (contributions.has(contribution.ownerId)) {\n            throw new Error(`Duplicate validator owner ${contribution.ownerId}`);\n        }\n        contributions.set(contribution.ownerId, contribution.encoding === 'validator-contribution'\n            ? contribution.signature\n            : encodeEcdsaRecoveryValue(contribution.signature, input.recoveryEncoding));\n    }\n    const ordered = input.ownerOrder.flatMap((ownerId) => {\n        const contribution = contributions.get(ownerId);\n        return contribution ? [contribution] : [];\n    });\n    if (ordered.length < input.threshold) {\n        throw new Error(`Insufficient validator contributions: required ${input.threshold}, received ${ordered.length}`);\n    }\n    return concat(ordered);\n}\nexport function encodeEcdsaRecoveryValue(signature, encoding) {\n    const bytes = hexToBytes(signature);\n    if (bytes.length !== 65) {\n        throw new Error('ECDSA signatures must contain 65 bytes');\n    }\n    const recovery = bytes[64];\n    const ethereumRecovery = recovery < 27 ? recovery + 27 : recovery;\n    const encodedRecovery = encoding === 'validator-offset-4' ? ethereumRecovery + 4 : ethereumRecovery;\n    if (encodedRecovery > 255) {\n        throw new Error('ECDSA recovery value does not fit in one byte');\n    }\n    return concat([signature.slice(0, -2), toHex(encodedRecovery)]);\n}\n","import { resolveOwnableAddresses } from './ownable.js';\nexport const SOCIAL_RECOVERY_VALIDATOR_ADDRESS = '0xa04d053b3c8021e8d5bf641816c42daa75d8b597';\n/**\n * Resolves the social recovery validator module.\n *\n * The module shares the ownable validator's `(threshold, address[])` init\n * encoding and its concatenated-ECDSA signature format, so it resolves through\n * the same encoder at a different address. `onInstall` requires the guardian\n * list to be sorted and unique, which `resolveOwnableAddresses` guarantees.\n */\nexport function resolveSocialRecoveryValidator(input) {\n    return resolveOwnableAddresses({\n        owners: input.guardians,\n        threshold: input.threshold ?? 1,\n        address: SOCIAL_RECOVERY_VALIDATOR_ADDRESS,\n    });\n}\n","const baseDefaults = {\n    orchestratorUrl: 'https://v1.orchestrator.rhinestone.dev',\n    environment: 'production',\n    provider: 'public',\n    account: { kind: 'nexus' },\n};\nexport const currentV2Defaults = Object.freeze({\n    ...baseDefaults,\n    id: 'current-v2',\n    account: {\n        ...baseDefaults.account,\n        safeAdapterProfile: 'safe-current-adapter',\n    },\n});\nexport const legacyV0Defaults = Object.freeze({\n    ...baseDefaults,\n    id: 'legacy-v0',\n    account: {\n        ...baseDefaults.account,\n        safeAdapterProfile: 'safe-legacy-v0-adapter',\n    },\n});\nexport const standaloneDefaults = {\n    'current-v2': currentV2Defaults,\n    'legacy-v0': legacyV0Defaults,\n};\n","import { defineValidator } from '../modules/validators/definition.js';\nimport { resolveSocialRecoveryValidator } from '../modules/validators/social-recovery.js';\nimport { currentV2Defaults, standaloneDefaults, } from './defaults.js';\nconst emptyHeaders = Object.freeze({});\nfunction selectValue(value, profile) {\n    return value === undefined\n        ? { source: 'default', profile }\n        : { source: 'explicit', value };\n}\nfunction selectAddress(address, profile) {\n    return address === undefined\n        ? { source: 'default', profile }\n        : { source: 'explicit', address };\n}\nfunction selectModuleData(value) {\n    return value === undefined\n        ? { source: 'omitted' }\n        : { source: 'explicit', value };\n}\nfunction configureModules(modules) {\n    return (modules ?? []).map((module) => ({\n        kind: module.type,\n        address: module.address,\n        initData: selectModuleData(module.initData),\n        deInitData: selectModuleData(module.deInitData),\n        additionalContext: selectModuleData(module.additionalContext),\n    }));\n}\nfunction configureRecovery(recovery) {\n    if (!recovery)\n        return [];\n    const module = resolveSocialRecoveryValidator({\n        guardians: recovery.guardians.map((guardian) => guardian.address),\n        ...(recovery.threshold === undefined\n            ? {}\n            : { threshold: recovery.threshold }),\n    });\n    return [\n        {\n            kind: module.kind,\n            address: module.address,\n            initData: { source: 'explicit', value: module.initData },\n            deInitData: { source: 'explicit', value: module.deInitData },\n            additionalContext: {\n                source: 'explicit',\n                value: module.additionalContext,\n            },\n        },\n    ];\n}\nfunction resolveAuth(input) {\n    let auth;\n    if ('auth' in input && input.auth) {\n        auth = input.auth;\n    }\n    else if ('apiKey' in input && input.apiKey) {\n        auth = { mode: 'apiKey', apiKey: input.apiKey };\n    }\n    if (!auth) {\n        throw new Error('RhinestoneSDK requires either `apiKey` or `auth` in config');\n    }\n    if (auth.mode === 'apiKey') {\n        return { kind: 'api-key', apiKey: auth.apiKey };\n    }\n    return {\n        kind: 'jwt',\n        accessToken: auth.accessToken,\n        ...(auth.getIntentExtensionToken\n            ? { getIntentExtensionToken: auth.getIntentExtensionToken }\n            : {}),\n    };\n}\nfunction resolveProvider(input) {\n    if (!input)\n        return { kind: 'public' };\n    return { kind: 'custom', urls: input.urls };\n}\nfunction resolveService(input) {\n    if (!input)\n        return undefined;\n    if (input.type === 'custom') {\n        return { kind: 'custom', urls: input.url };\n    }\n    return { kind: input.type, apiKey: input.apiKey };\n}\nfunction resolveAccountDefinition(input, defaults) {\n    const account = input ?? { type: defaults.account.kind };\n    switch (account.type) {\n        case 'safe':\n            return {\n                kind: 'safe',\n                version: selectValue(account.version, 'safe-current-version'),\n                adapter: selectValue(account.adapter, defaults.account.safeAdapterProfile),\n                nonce: selectValue(account.nonce, 'safe-zero-nonce'),\n            };\n        case 'nexus':\n            return {\n                kind: 'nexus',\n                version: selectValue(account.version, 'nexus-current-version'),\n                salt: selectValue(account.salt, 'nexus-empty-calldata-salt'),\n            };\n        case 'kernel':\n            return {\n                kind: 'kernel',\n                version: selectValue(account.version, 'kernel-current-version'),\n                salt: selectValue(account.salt, 'kernel-zero-salt'),\n            };\n        case 'startale':\n            return {\n                kind: 'startale',\n                salt: selectValue(account.salt, 'startale-zero-salt'),\n            };\n        case 'hca':\n            return {\n                kind: 'hca',\n                factory: selectValue(account.factory, 'hca-canonical-factory'),\n            };\n        case 'eoa':\n            return { kind: 'eoa' };\n    }\n}\nfunction resolveSessions(input, environment) {\n    return {\n        configured: input !== undefined,\n        enabled: input?.enabled ?? false,\n        module: selectAddress(input?.module, 'smart-session-emissary'),\n        compatibilityFallback: selectAddress(input?.compatibilityFallback, 'safe-session-fallback'),\n        environment,\n    };\n}\nfunction resolveAccountWithDefaults(input, defaults, environment) {\n    return {\n        profile: defaults.id,\n        account: resolveAccountDefinition(input.account, defaults),\n        ...(input.owners ? { owners: defineValidator(input.owners) } : {}),\n        ...(input.eoa ? { eoa: input.eoa } : {}),\n        modules: [\n            ...configureRecovery(input.recovery),\n            ...configureModules(input.modules),\n        ],\n        ...(input.initData ? { initData: input.initData } : {}),\n        sessions: resolveSessions(input.sessions, environment),\n    };\n}\nexport function resolveSdkConfig(input, defaults = currentV2Defaults) {\n    const bundler = resolveService(input.bundler);\n    const paymaster = resolveService(input.paymaster);\n    return {\n        profile: defaults.id,\n        defaults: {\n            orchestratorUrl: defaults.orchestratorUrl,\n            environment: defaults.environment,\n            provider: defaults.provider,\n            account: { ...defaults.account },\n        },\n        environment: input.useDevContracts === true ? 'development' : defaults.environment,\n        auth: resolveAuth(input),\n        orchestratorUrl: input.endpointUrl ?? defaults.orchestratorUrl,\n        provider: resolveProvider(input.provider),\n        ...(bundler ? { bundler } : {}),\n        ...(paymaster ? { paymaster } : {}),\n        headers: input.headers ?? emptyHeaders,\n        ...(input.hyperliquid ? { hyperliquid: input.hyperliquid } : {}),\n    };\n}\nexport function resolveAccountConfig(sdk, input) {\n    return resolveAccountWithDefaults(input, { id: sdk.profile, ...sdk.defaults }, sdk.environment);\n}\nexport function resolveConfig(sdkInput, accountInput, defaults = currentV2Defaults) {\n    const sdk = resolveSdkConfig(sdkInput, defaults);\n    return { sdk, account: resolveAccountConfig(sdk, accountInput) };\n}\nexport function resolveStandaloneAccountConfig(input, profile) {\n    return resolveAccountWithDefaults(input, standaloneDefaults[profile], 'production');\n}\nfunction materializeSdkInvocationConfig(sdk, compatibility) {\n    const bundler = resolveService(compatibility.bundler);\n    const paymaster = resolveService(compatibility.paymaster);\n    return {\n        profile: sdk.profile,\n        defaults: sdk.defaults,\n        auth: sdk.auth,\n        environment: compatibility.useDevContracts === true\n            ? 'development'\n            : sdk.defaults.environment,\n        orchestratorUrl: compatibility.endpointUrl ?? sdk.defaults.orchestratorUrl,\n        provider: resolveProvider(compatibility.provider),\n        ...(bundler ? { bundler } : {}),\n        ...(paymaster ? { paymaster } : {}),\n        headers: compatibility.headers ?? emptyHeaders,\n        ...(compatibility.hyperliquid\n            ? { hyperliquid: compatibility.hyperliquid }\n            : {}),\n    };\n}\nexport function materializeAccountInvocationContext(sdk, compatibilityConfig, method) {\n    const invocationSdk = materializeSdkInvocationConfig(sdk, compatibilityConfig);\n    return {\n        method,\n        sdk: invocationSdk,\n        account: resolveAccountConfig(invocationSdk, compatibilityConfig),\n        compatibilityConfig,\n    };\n}\n","class AccountError extends Error {\n    _message;\n    _context;\n    _errorType;\n    _traceId;\n    constructor(params) {\n        super();\n        this._message = params?.message || 'AccountError';\n        this._context = params?.context || {};\n        this._errorType = params?.errorType || 'Unknown';\n        this._traceId = params?.traceId || '';\n    }\n    get message() {\n        return this._message;\n    }\n    get context() {\n        return this._context;\n    }\n    get errorType() {\n        return this._errorType;\n    }\n    get traceId() {\n        return this._traceId;\n    }\n}\nclass Eip7702AccountMustHaveEoaError extends AccountError {\n    constructor(params) {\n        super({\n            message: 'EIP-7702 accounts must have an EOA account',\n            ...params,\n        });\n    }\n}\nclass EoaAccountMustHaveAccountError extends AccountError {\n    constructor(params) {\n        super({\n            message: 'EOA accounts must have a signer `account` provided',\n            ...params,\n        });\n    }\n}\nclass FactoryArgsNotAvailableError extends AccountError {\n    constructor(params) {\n        super({\n            message: 'Factory args not available',\n            ...params,\n        });\n    }\n}\nclass DefaultValidatorAlreadyInitializedError extends AccountError {\n    constructor(params) {\n        super({\n            message: 'ECDSA is already enabled on this account. Use `addOwner` / `removeOwner` / `changeThreshold` to manage owners instead of `enable`.',\n            ...params,\n        });\n    }\n}\nclass SigningNotSupportedForAccountError extends AccountError {\n    constructor(params) {\n        super({\n            message: 'Signing not supported for the account',\n            ...params,\n        });\n    }\n}\nclass Eip7702NotSupportedForAccountError extends AccountError {\n    constructor(account, params) {\n        const accountName = getAccountName(account);\n        super({\n            message: `EIP-7702 is not supported for ${accountName} accounts`,\n            ...params,\n        });\n    }\n}\nclass AccountConfigurationNotSupportedError extends AccountError {\n    constructor(message, account, params) {\n        super({\n            message: `Account configuration for ${getAccountName(account)} account is not supported: ${message}`,\n            ...params,\n        });\n    }\n}\nclass WalletClientNoConnectedAccountError extends AccountError {\n    constructor(params) {\n        super({\n            message: 'WalletClient is missing a default account. Ensure the wallet is connected and the client has an account.',\n            ...params,\n        });\n    }\n}\nclass ModuleInstallationNotSupportedError extends AccountError {\n    constructor(account, params) {\n        const accountName = getAccountName(account);\n        super({\n            message: `Module installation is not supported for ${accountName} accounts`,\n            ...params,\n        });\n    }\n}\nclass EoaSigningNotSupportedError extends AccountError {\n    constructor(method, params) {\n        super({\n            message: `EOA account provider does not support ${method} signing`,\n            ...params,\n        });\n    }\n}\nclass EoaSigningMethodNotConfiguredError extends AccountError {\n    constructor(method, params) {\n        super({\n            message: `EOA account provider must have ${method} method configured`,\n            ...params,\n        });\n    }\n}\nclass OwnersFieldRequiredError extends AccountError {\n    constructor(params) {\n        super({\n            message: 'Owners field is required for smart accounts',\n            ...params,\n        });\n    }\n}\nclass PasskeyConfigurationNotInstallableError extends AccountError {\n    constructor(reason, params) {\n        super({\n            message: `Passkey owner set cannot be installed on a new account: ${reason}`,\n            ...params,\n        });\n    }\n}\nclass Eip712DomainNotAvailableError extends AccountError {\n    constructor(message) {\n        super({\n            message,\n        });\n    }\n}\nfunction isAccountError(error) {\n    return error instanceof AccountError;\n}\nfunction getAccountName(account) {\n    switch (account) {\n        case 'safe':\n            return 'Safe';\n        case 'kernel':\n            return 'Kernel';\n        case 'nexus':\n            return 'Nexus';\n        case 'startale':\n            return 'Startale';\n        case 'hca':\n            return 'HCA';\n        case 'eoa':\n            return 'EOA';\n    }\n}\nexport { isAccountError, AccountError, Eip712DomainNotAvailableError, Eip7702AccountMustHaveEoaError, EoaAccountMustHaveAccountError, FactoryArgsNotAvailableError, DefaultValidatorAlreadyInitializedError, SigningNotSupportedForAccountError, Eip7702NotSupportedForAccountError, AccountConfigurationNotSupportedError, WalletClientNoConnectedAccountError, ModuleInstallationNotSupportedError, EoaSigningNotSupportedError, EoaSigningMethodNotConfiguredError, OwnersFieldRequiredError, PasskeyConfigurationNotInstallableError, };\n","import { OwnersFieldRequiredError } from '../accounts/error.js';\nexport function assertAccountOwnersConfigured(config) {\n    if (config.account.kind !== 'eoa' && !config.owners) {\n        throw new OwnersFieldRequiredError();\n    }\n}\n","class AccountCapabilityError extends Error {\n    context;\n    constructor(message, context = {}) {\n        super(message);\n        this.name = 'AccountCapabilityError';\n        this.context = context;\n    }\n}\n/** Thrown when a composite account configuration is malformed. */\nclass InvalidAccountConfigError extends AccountCapabilityError {\n    constructor(message) {\n        super(`Invalid account configuration: ${message}`);\n        this.name = 'InvalidAccountConfigError';\n    }\n}\n/**\n * Thrown when managed Solana capability is requested outside a supported\n * environment and endpoint pair.\n */\nclass ManagedSolanaAccountNotSupportedError extends AccountCapabilityError {\n    constructor(message) {\n        super(message ??\n            \"Managed Solana accounts are available only on production with the default endpoint `https://v1.orchestrator.rhinestone.dev`, or with `useDevContracts: true` and `endpointUrl: 'https://dev.v1.orchestrator.rhinestone.dev'`. Use an address-only Solana receiver elsewhere.\", { vm: 'solana' });\n        this.name = 'ManagedSolanaAccountNotSupportedError';\n    }\n}\n/** Thrown when an address is requested for a VM absent from the account. */\nclass AccountVmNotConfiguredError extends AccountCapabilityError {\n    constructor(vm) {\n        super(`The ${vm} VM is not configured on this account.`, { vm });\n        this.name = 'AccountVmNotConfiguredError';\n    }\n}\n/** Thrown when a transaction requests an unsupported account capability. */\nclass UnsupportedAccountCapabilityError extends AccountCapabilityError {\n    constructor(message, context) {\n        super(message, context);\n        this.name = 'UnsupportedAccountCapabilityError';\n    }\n}\nfunction isAccountCapabilityError(error) {\n    return error instanceof AccountCapabilityError;\n}\nexport { AccountCapabilityError, AccountVmNotConfiguredError, InvalidAccountConfigError, ManagedSolanaAccountNotSupportedError, UnsupportedAccountCapabilityError, isAccountCapabilityError, };\n","import { base64urlnopad } from '@scure/base';\nimport { bytesToHex, hexToBytes, isAddress, isAddressEqual, isHex, recoverMessageAddress, } from 'viem';\nimport { isManagedSwigNamespace, } from '../../accounts/solana/address.js';\nimport { formatCaip2 } from '../../chains/caip2.js';\nimport { solanaAddress, solanaDevnet, solanaMainnet, } from '../../chains/non-evm.js';\nimport { isSponsoredIntentInput, projectCompatibleIntentInput, } from '../../clients/orchestrator/normalized.js';\nimport { InvalidSolanaTransactionArtifactError, SolanaQuoteExpiredError, } from '../../errors/execution.js';\nimport { normalizeRecovery } from '../../signing/signers/ecdsa.js';\nimport { toNormalizedAccount, toWireEvmAccount, } from './account.js';\nimport { projectPreparedBinding } from './compatibility.js';\nimport { normalizeIntentQuote } from './normalize.js';\nimport { toExecution } from './request.js';\nimport { normalizeSolanaAddressLookupTables, normalizeSolanaInstructions, } from './solana-instructions.js';\nconst SOLANA_MAINNET_ID = 792703809;\nconst SOLANA_DEVNET_ID = 792703810;\nconst SOLANA_MAINNET_CAIP2 = 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp';\nconst SOLANA_DEVNET_CAIP2 = 'solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1';\nexport const NATIVE_SOL_SENTINEL = '11111111111111111111111111111111';\nexport function solanaChainId(chain) {\n    const expected = chain.caip2 === SOLANA_MAINNET_CAIP2\n        ? solanaMainnet\n        : chain.caip2 === SOLANA_DEVNET_CAIP2\n            ? solanaDevnet\n            : undefined;\n    if (!expected ||\n        chain.kind !== expected.kind ||\n        chain.name !== expected.name ||\n        chain.testnet !== expected.testnet ||\n        chain.nativeCurrency.name !== expected.nativeCurrency.name ||\n        chain.nativeCurrency.symbol !== expected.nativeCurrency.symbol ||\n        chain.nativeCurrency.decimals !== expected.nativeCurrency.decimals) {\n        throw new InvalidSolanaTransactionArtifactError('the chain must be the canonical Solana mainnet or devnet descriptor');\n    }\n    return chain.caip2 === SOLANA_MAINNET_CAIP2\n        ? SOLANA_MAINNET_ID\n        : SOLANA_DEVNET_ID;\n}\nfunction validateFee(name, fee) {\n    if (!fee)\n        return;\n    if (typeof fee !== 'object' ||\n        typeof fee.feeBps !== 'number' ||\n        !Number.isInteger(fee.feeBps) ||\n        fee.feeBps < 0 ||\n        fee.feeBps > 10_000) {\n        throw new InvalidSolanaTransactionArtifactError(`${name}.feeBps must be an integer from 0 to 10000`);\n    }\n}\nfunction toSponsorship(settings) {\n    return settings ? { ...settings } : undefined;\n}\n/** The delivery, when the paired EVM account runs calls on its arrival. */\nfunction executingDelivery(input) {\n    const { action } = input;\n    return action.kind === 'transfer' &&\n        action.delivery.kind === 'cross-chain' &&\n        action.delivery.execution\n        ? action.delivery\n        : undefined;\n}\nexport function buildSolanaIntentRequest(input) {\n    const chainId = solanaChainId(input.chain);\n    const caip2 = formatCaip2(chainId);\n    if (!isManagedSwigNamespace(input.namespace)) {\n        throw new InvalidSolanaTransactionArtifactError('the managed account namespace must be dev-v1 or prod-v1');\n    }\n    validateFee('appFees', input.appFees);\n    validateFee('protocolFees', input.protocolFees);\n    const executing = executingDelivery(input);\n    const execution = executing?.execution;\n    if (execution) {\n        if (!input.accountType) {\n            throw new InvalidSolanaTransactionArtifactError('destination calls need a paired EVM account to run them');\n        }\n        const executor = execution.account.address.toLowerCase();\n        if (executor !== input.accountAddress.toLowerCase() ||\n            executor !== executing.recipient.toLowerCase()) {\n            throw new InvalidSolanaTransactionArtifactError('destination calls run on the paired EVM account, which must also receive the delivery');\n        }\n        if (execution.calls.length === 0) {\n            throw new InvalidSolanaTransactionArtifactError('a destination execution needs at least one call');\n        }\n    }\n    const normalizedOptions = {\n        // The SVM-only account has no signature mode; the paired EVM entry does.\n        ...(execution ? { signatureMode: 1 } : {}),\n        ...(input.appFees ? { appFees: input.appFees } : {}),\n        ...(input.protocolFees ? { protocolFees: input.protocolFees } : {}),\n        ...(input.sponsorSettings\n            ? { sponsorSettings: input.sponsorSettings }\n            : {}),\n    };\n    const sponsorship = toSponsorship(input.sponsorSettings);\n    const options = {\n        ...(input.appFees ? { appFees: input.appFees } : {}),\n        ...(input.protocolFees ? { protocolFees: input.protocolFees } : {}),\n        ...(sponsorship ? { sponsorship } : {}),\n    };\n    // No `initData`: a spend never creates the Swig. Creation is a separate,\n    // tokenless deployment request.\n    const svm = {\n        type: 'swig',\n        address: input.walletAddress,\n        authorization: input.authority,\n    };\n    // Plain Solana operations always name the selected Swig directly. Only an\n    // actual destination execution uses the backend's paired EVM+SVM contract.\n    const swig = execution ? svm : { ...svm, swigAccount: input.swigAddress };\n    const account = execution\n        ? {\n            evm: toWireEvmAccount(execution.account, { signatureMode: 1 }),\n            svm: swig,\n        }\n        : { svm: swig };\n    // Projected from the same entries the request sends, so the approval input\n    // names the paying Swig and its key exactly as the orchestrator receives it.\n    const normalizedAccount = execution\n        ? { ...toNormalizedAccount(execution.account), svm: swig }\n        : { address: input.walletAddress, svm: swig };\n    if (input.action.kind === 'instructions') {\n        if (input.appFees || input.protocolFees) {\n            throw new InvalidSolanaTransactionArtifactError('a Solana instruction execution carries no value leg to charge fees on');\n        }\n        const lookupTables = normalizeSolanaAddressLookupTables(input.action.addressLookupTables);\n        const instructions = normalizeSolanaInstructions(input.action.instructions);\n        return {\n            request: {\n                account,\n                destination: {\n                    vm: 'svm',\n                    chainId: caip2,\n                    // Tokenless: the instructions move whatever they move, and the payee\n                    // is encoded inside them, so this names neither token nor recipient\n                    // and acquires no funding mint.\n                    tokenRequests: [],\n                    execution: {\n                        instructions,\n                        ...(lookupTables ? { addressLookupTables: lookupTables } : {}),\n                    },\n                },\n                source: {\n                    selection: { chains: { only: [caip2] }, tokens: 'all' },\n                },\n                ...(Object.keys(options).length > 0 ? { options } : {}),\n            },\n            normalized: {\n                destinationExecutions: [],\n                account: normalizedAccount,\n                options: normalizedOptions,\n                destinationChainId: chainId,\n                tokenRequests: [],\n                destinationInstructions: instructions,\n                ...(lookupTables ? { addressLookupTableAddresses: lookupTables } : {}),\n                accountAccessList: { chainIds: [chainId] },\n            },\n        };\n    }\n    const mint = solanaAddress(input.action.mint);\n    if (mint === NATIVE_SOL_SENTINEL) {\n        throw new InvalidSolanaTransactionArtifactError('native SOL transfers are not supported; provide an SPL mint');\n    }\n    if (input.action.amount !== undefined &&\n        (typeof input.action.amount !== 'bigint' || input.action.amount <= 0n)) {\n        throw new InvalidSolanaTransactionArtifactError('the token amount must be a positive bigint when provided');\n    }\n    const sourceLimit = input.action.sourceLimit;\n    if (sourceLimit !== undefined &&\n        (typeof sourceLimit !== 'bigint' || sourceLimit <= 0n)) {\n        throw new InvalidSolanaTransactionArtifactError('the source amount cap must be a positive bigint when provided');\n    }\n    const amount = input.action.amount === undefined\n        ? {}\n        : { amount: input.action.amount };\n    const delivery = input.action.delivery;\n    if (delivery.kind === 'same-chain' &&\n        sourceLimit !== undefined &&\n        input.action.amount !== undefined &&\n        input.action.amount > sourceLimit) {\n        throw new InvalidSolanaTransactionArtifactError('the token amount exceeds the source amount cap');\n    }\n    // Pinned to the cluster and the one mint: naming the cluster without the\n    // mint would re-expand the source scope to every registry token on it and\n    // defeat the explicit source asset. A cap only adds a limit on that pair; it\n    // never widens the selection.\n    const source = {\n        selection: {\n            chains: { only: [caip2] },\n            tokens: { only: [mint] },\n            perChain: { [caip2]: { tokens: { only: [mint] } } },\n        },\n        ...(sourceLimit === undefined\n            ? {}\n            : {\n                limits: [\n                    { chainId: caip2, tokenAddress: mint, maxAmount: sourceLimit },\n                ],\n            }),\n    };\n    // A capped pair is named by its cap alone, as an EVM capped source asset is.\n    const cappedAccessList = sourceLimit === undefined\n        ? undefined\n        : { chainTokenAmounts: { [chainId]: { [mint]: sourceLimit } } };\n    if (delivery.kind === 'cross-chain') {\n        if (!Number.isSafeInteger(delivery.chainId) ||\n            delivery.chainId < 0 ||\n            !formatCaip2(delivery.chainId).startsWith('eip155:')) {\n            throw new InvalidSolanaTransactionArtifactError('the delivery chain must be an EVM chain');\n        }\n        if (!isAddress(delivery.token) || !isAddress(delivery.recipient)) {\n            throw new InvalidSolanaTransactionArtifactError('the delivery token and recipient must be EVM addresses');\n        }\n        const executions = execution?.calls.map(toExecution);\n        // The calls run on the paired account, which receives the delivery when no\n        // recipient is named. Naming it anyway would plan it as a second account,\n        // one the account entry's setup and delegations never reach.\n        const recipient = execution\n            ? {}\n            : { recipient: { address: delivery.recipient } };\n        return {\n            request: {\n                account,\n                destination: {\n                    vm: 'evm',\n                    chainId: formatCaip2(delivery.chainId),\n                    ...recipient,\n                    tokenRequests: [{ tokenAddress: delivery.token, ...amount }],\n                    ...(executions\n                        ? {\n                            execution: {\n                                calls: executions,\n                                ...(execution?.gasLimit === undefined\n                                    ? {}\n                                    : { gasLimit: execution.gasLimit }),\n                            },\n                        }\n                        : {}),\n                },\n                source,\n                ...(Object.keys(options).length > 0 ? { options } : {}),\n            },\n            normalized: {\n                destinationExecutions: executions ?? [],\n                ...(execution?.gasLimit === undefined\n                    ? {}\n                    : { destinationGasUnits: execution.gasLimit }),\n                account: normalizedAccount,\n                options: normalizedOptions,\n                destinationChainId: delivery.chainId,\n                tokenRequests: [{ tokenAddress: delivery.token, ...amount }],\n                // The EVM payee in the spelling the released EVM input uses.\n                ...(execution\n                    ? {}\n                    : {\n                        recipient: {\n                            address: delivery.recipient,\n                            accountType: 'EOA',\n                            setupOps: [],\n                        },\n                    }),\n                accountAccessList: cappedAccessList ?? {\n                    chainTokens: { [chainId]: [mint] },\n                },\n            },\n        };\n    }\n    const recipient = solanaAddress(delivery.recipient);\n    if (recipient === input.walletAddress) {\n        throw new InvalidSolanaTransactionArtifactError('the recipient must differ from the managed Solana wallet');\n    }\n    return {\n        request: {\n            account,\n            destination: {\n                vm: 'svm',\n                chainId: caip2,\n                recipient: { address: recipient },\n                tokenRequests: [{ tokenAddress: mint, ...amount }],\n            },\n            source,\n            ...(Object.keys(options).length > 0 ? { options } : {}),\n        },\n        normalized: {\n            destinationExecutions: [],\n            account: normalizedAccount,\n            options: normalizedOptions,\n            destinationChainId: chainId,\n            tokenRequests: [{ tokenAddress: mint, ...amount }],\n            recipient: { address: recipient },\n            accountAccessList: cappedAccessList ?? {\n                chainTokens: { [chainId]: [mint] },\n            },\n        },\n    };\n}\nfunction deliveryKind(input) {\n    return input.action.kind === 'instructions'\n        ? 'same-chain'\n        : input.action.delivery.kind;\n}\nfunction spendPayload(quote, input, delivery) {\n    const request = quote.signingRequests[0];\n    // Not a `=== 'RELAY'` whitelist: the same corridor is planned on other\n    // settlement layers, and any of them authorizes the spend identically.\n    const layerMismatch = delivery === 'same-chain'\n        ? quote.settlementLayer !== 'SAME_CHAIN'\n        : quote.settlementLayer === 'SAME_CHAIN';\n    const refuse = (reason) => {\n        throw new InvalidSolanaTransactionArtifactError(reason, {\n            intentId: quote.intentId,\n        });\n    };\n    if (!quote.intentId) {\n        refuse('the quote must carry an intent id');\n    }\n    if (layerMismatch) {\n        refuse(delivery === 'same-chain'\n            ? 'the quote must be a SAME_CHAIN route'\n            : 'the quote must be a cross-chain route');\n    }\n    const executing = executingDelivery(input);\n    const destinationRequests = quote.signingRequests.slice(1);\n    if (!request || (!executing && destinationRequests.length > 0)) {\n        refuse('the quote must carry exactly one signing request');\n    }\n    const expected = input.authority;\n    let signed;\n    if (expected.kind === 'secp256r1') {\n        if (request.payload.kind !== 'webauthn') {\n            refuse('the quote must ask for a WebAuthn spend authorization');\n        }\n        const { challenge } = request.payload;\n        if (!/^0x[0-9a-fA-F]{64}$/u.test(challenge)) {\n            refuse('the WebAuthn challenge must be 32 bytes of hex');\n        }\n        signed = { kind: 'webauthn', challenge: challenge };\n    }\n    else {\n        if (request.payload.kind !== 'personalSign' ||\n            request.payload.message.encoding !== 'utf8') {\n            refuse('the quote must ask for a UTF-8 personal-sign spend authorization');\n        }\n        const payload = request.payload;\n        if (!/^[0-9a-fA-F]{64}$/u.test(payload.message.value)) {\n            refuse('the personal-sign message must be a 64-character opaque payload');\n        }\n        signed = { kind: 'personalSign', message: payload.message.value };\n    }\n    // The Swig wallet holds the assets; the state account is a different address\n    // and signing for it would authorize nothing.\n    if (request.account.vm !== 'svm' ||\n        request.account.wallet !== input.walletAddress ||\n        request.account.swigAccount !== input.swigAddress) {\n        refuse('the signing request must name the configured Swig wallet and state account');\n    }\n    const authority = request.authority;\n    const role = authority.kind === 'swigRole' ? authority.authority : authority;\n    const named = expected.kind === 'secp256r1'\n        ? role.kind === 'secp256r1' &&\n            role.publicKey.toLowerCase() === expected.publicKey.toLowerCase()\n        : role.kind === 'secp256k1' &&\n            role.address.toLowerCase() === expected.address.toLowerCase();\n    if (!named) {\n        refuse('the signing request must name the configured Solana authority');\n    }\n    const scope = request.scope;\n    if (scope.vm !== 'svm' || scope.action !== 'spend') {\n        refuse('the signing request must authorize a Solana spend');\n    }\n    const slot = request.validity.find((entry) => entry.kind === 'svmSlot');\n    if (!slot || !/^\\d+$/u.test(slot.expiresAtSlot)) {\n        refuse('the signing request must disclose a decimal Solana slot window');\n    }\n    if (executing) {\n        if (!destinationRequests.some(({ purpose, payload }) => purpose === 'originAuthorization' && payload.kind === 'eip712')) {\n            refuse(\"the quote must ask for the destination calls' EIP-712 authorization\");\n        }\n        for (const { account, payload } of destinationRequests) {\n            const chainId = payload.kind === 'eip712'\n                ? Number(payload.typedData.domain?.chainId)\n                : payload.kind === 'eip7702'\n                    ? payload.authorization.chainId\n                    : undefined;\n            if (account.vm !== 'evm' ||\n                account.address.toLowerCase() !== input.accountAddress.toLowerCase() ||\n                chainId !== executing.chainId) {\n                refuse('each destination signing request must name the paired EVM account on the delivery chain');\n            }\n        }\n    }\n    return {\n        request: request,\n        expiresAtSlot: slot.expiresAtSlot,\n        ...signed,\n    };\n}\nfunction validateQuote(quote, input) {\n    spendPayload(quote, input, deliveryKind(input));\n    const chainId = formatCaip2(solanaChainId(input.chain));\n    if (input.action.kind === 'instructions') {\n        // The serving route decides how many cost legs an instruction execution\n        // has, so only their chain is asserted: anything off the requested cluster\n        // is not this intent.\n        const offChain = [...quote.cost.input, ...quote.cost.output].some((leg) => leg.chainId !== chainId);\n        if (offChain) {\n            throw new InvalidSolanaTransactionArtifactError('every quote cost must reference the requested Solana chain', { intentId: quote.intentId });\n        }\n        return;\n    }\n    if (quote.cost.input.length !== 1 || quote.cost.output.length !== 1) {\n        throw new InvalidSolanaTransactionArtifactError('quote costs must include exactly one input and one output entry', { intentId: quote.intentId });\n    }\n    const source = quote.cost.input[0];\n    if (source.chainId !== chainId || source.tokenAddress !== input.action.mint) {\n        throw new InvalidSolanaTransactionArtifactError('the quote input cost must reference the requested Solana chain and mint', { intentId: quote.intentId });\n    }\n    // Only as strong as the quote's accounting: a route that bills source fees\n    // outside `cost.input` is bounded by the orchestrator's own limit check.\n    const cap = input.action.sourceLimit;\n    if (cap !== undefined &&\n        (typeof source.amount !== 'bigint' || source.amount > cap)) {\n        throw new InvalidSolanaTransactionArtifactError('the quote input cost exceeds the source amount cap', { intentId: quote.intentId });\n    }\n    const output = quote.cost.output[0];\n    const delivery = input.action.delivery;\n    if (delivery.kind === 'same-chain') {\n        if (output.chainId !== chainId ||\n            output.tokenAddress !== input.action.mint) {\n            throw new InvalidSolanaTransactionArtifactError('the quote output cost must reference the requested Solana chain and mint', { intentId: quote.intentId });\n        }\n        return;\n    }\n    // The orchestrator lowercases EVM addresses; base58 mints stay exact.\n    if (output.chainId !== formatCaip2(delivery.chainId) ||\n        typeof output.tokenAddress !== 'string' ||\n        output.tokenAddress.toLowerCase() !== delivery.token.toLowerCase()) {\n        throw new InvalidSolanaTransactionArtifactError('the quote output cost must reference the requested delivery chain and token', { intentId: quote.intentId });\n    }\n}\nexport async function prepareSolanaIntent(context, input) {\n    const { request, normalized } = buildSolanaIntentRequest(input);\n    const response = await context.quoteClient.createQuote(request, {\n        intentInput: projectCompatibleIntentInput(normalized),\n        sponsored: isSponsoredIntentInput(normalized),\n    });\n    if (response.routes.length === 0) {\n        throw new InvalidSolanaTransactionArtifactError('the orchestrator returned no quote');\n    }\n    const quotes = response.routes.map(normalizeIntentQuote);\n    for (const quote of quotes)\n        validateQuote(quote, input);\n    return {\n        traceId: response.traceId,\n        input,\n        request,\n        normalized,\n        quote: quotes[0],\n        quotes,\n    };\n}\nfunction canonical(value) {\n    if (typeof value === 'bigint')\n        return { $bigint: value.toString() };\n    if (Array.isArray(value))\n        return value.map(canonical);\n    if (value && typeof value === 'object') {\n        return Object.fromEntries(Object.entries(value)\n            .sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))\n            .map(([key, item]) => [key, canonical(item)]));\n    }\n    return value;\n}\nfunction stable(value) {\n    return JSON.stringify(canonical(value));\n}\nexport function reconstructSolanaIntent(input) {\n    const { request, normalized } = buildSolanaIntentRequest(input.transfer);\n    if (stable(projectPreparedBinding(request).request) !==\n        stable(projectPreparedBinding(input.request).request)) {\n        throw new InvalidSolanaTransactionArtifactError('the persisted request does not match the captured transaction', { intentId: input.quote.intentId });\n    }\n    if (stable(projectCompatibleIntentInput(normalized)) !==\n        stable(input.intentInput)) {\n        throw new InvalidSolanaTransactionArtifactError('the canonical intent input does not match the captured transaction', { intentId: input.quote.intentId });\n    }\n    const quotes = input.quotes.map(normalizeIntentQuote);\n    const quote = quotes.find(({ intentId }) => intentId === input.quote.intentId);\n    if (!quote || stable(quote) !== stable(normalizeIntentQuote(input.quote))) {\n        throw new InvalidSolanaTransactionArtifactError('the selected quote is missing or differs from the prepared quote set', { intentId: input.quote.intentId });\n    }\n    for (const candidate of quotes)\n        validateQuote(candidate, input.transfer);\n    return {\n        traceId: input.traceId,\n        input: input.transfer,\n        request,\n        normalized,\n        quote,\n        quotes,\n    };\n}\nexport function assertSolanaNotExpired(now, quote) {\n    if (!Number.isFinite(quote.expiresAt) || now >= quote.expiresAt * 1000) {\n        throw new SolanaQuoteExpiredError(quote.intentId);\n    }\n}\n/**\n * Checks that a paired account's proofs answer the quote's EVM requests slot by\n * slot. A `SingleChainOps` authorization is one hex signature, never a\n * session's pair.\n */\nfunction assertEvmProofs(quote, proofs) {\n    const requests = quote.signingRequests.slice(1);\n    const answered = proofs.length === requests.length &&\n        requests.every(({ payload }, index) => {\n            const proof = proofs[index];\n            return payload.kind === 'eip712'\n                ? proof.kind === 'eip712' &&\n                    typeof proof.signature === 'string' &&\n                    isHex(proof.signature)\n                : payload.kind === 'eip7702' && proof.kind === 'eip7702';\n        });\n    if (!answered) {\n        throw new InvalidSolanaTransactionArtifactError('the destination proofs must answer each EVM signing request in order', { intentId: quote.intentId });\n    }\n}\nexport async function signSolanaIntent(input) {\n    assertSolanaNotExpired(input.now(), input.prepared.quote);\n    const payload = spendPayload(input.prepared.quote, input.prepared.input, deliveryKind(input.prepared.input));\n    const refuse = (reason) => {\n        throw new InvalidSolanaTransactionArtifactError(reason, {\n            intentId: input.prepared.quote.intentId,\n        });\n    };\n    const authority = input.prepared.input.authority;\n    // Checked before any EVM request is signed, so a wrong owner prompts nobody.\n    if (authority.kind === 'secp256r1' && input.owner.type !== 'webAuthn') {\n        refuse('the configured authority is a passkey; provide the viem WebAuthn account that owns it');\n    }\n    if (authority.kind === 'secp256k1' &&\n        (input.owner.type === 'webAuthn' || !input.owner.signMessage)) {\n        refuse('the configured authority cannot sign messages; provide a viem account with signMessage for headless signing');\n    }\n    const executing = executingDelivery(input.prepared.input);\n    let evmProofs = [];\n    if (executing) {\n        if (!input.signEvmRequests) {\n            refuse('the destination calls need the paired EVM account to sign them');\n        }\n        // Before the spend, whose payload stays valid for only a short slot window\n        // from the quote.\n        evmProofs = await input.signEvmRequests(input.prepared.quote.signingRequests.slice(1), executing.chainId);\n        assertEvmProofs(input.prepared.quote, evmProofs);\n    }\n    let spend;\n    if (authority.kind === 'secp256r1') {\n        const owner = input.owner;\n        const { challenge } = payload;\n        const { signature, webauthn } = await owner.sign({ hash: challenge });\n        const assertion = {\n            credentialId: owner.id,\n            authenticatorData: webauthn.authenticatorData,\n            // Passed through untouched: the orchestrator hashes these exact bytes.\n            clientDataJSON: webauthn.clientDataJSON,\n            signature,\n        };\n        validateSolanaWebAuthnAssertion({ challenge }, assertion);\n        spend = { kind: 'webauthn', assertion };\n    }\n    else {\n        const { message } = payload;\n        const signature = normalizeRecovery(await input.owner.signMessage({ message }));\n        await validateSolanaSignature(authority.address, { message }, signature);\n        spend = { kind: 'personalSign', signature };\n    }\n    return { prepared: input.prepared, proofs: [spend, ...evmProofs] };\n}\nexport async function validateSolanaSignature(authority, payload, signature) {\n    let signatureLength;\n    try {\n        signatureLength = hexToBytes(signature).length;\n    }\n    catch {\n        signatureLength = -1;\n    }\n    if (signatureLength !== 65) {\n        throw new InvalidSolanaTransactionArtifactError('the origin signature must be a recoverable 65-byte ECDSA signature');\n    }\n    let recovered;\n    try {\n        recovered = await recoverMessageAddress({\n            message: payload.message,\n            signature,\n        });\n    }\n    catch {\n        throw new InvalidSolanaTransactionArtifactError('the origin signature is not recoverable');\n    }\n    if (!isAddressEqual(recovered, authority)) {\n        throw new InvalidSolanaTransactionArtifactError('the origin signature does not recover to the configured Solana authority');\n    }\n}\n/**\n * Checks a passkey assertion's shape before it is submitted: the client data is\n * a `webauthn.get` over this challenge, and the signature is 64-byte r‖s.\n *\n * The P-256 signature itself is deliberately not verified here. The\n * orchestrator verifies it and normalises low-S before it records anything, so\n * a bad one is refused with nothing spent, and verifying locally would cost the\n * root bundle a P-256 implementation.\n */\nexport function validateSolanaWebAuthnAssertion(payload, assertion) {\n    const refuse = (reason) => {\n        throw new InvalidSolanaTransactionArtifactError(reason);\n    };\n    if (!/^0x[0-9a-fA-F]{128}$/u.test(assertion.signature)) {\n        refuse('the passkey signature must be a 64-byte r‖s P-256 signature');\n    }\n    let clientData;\n    try {\n        clientData = JSON.parse(assertion.clientDataJSON);\n    }\n    catch {\n        refuse('the passkey client data must be JSON');\n    }\n    if (clientData?.type !== 'webauthn.get') {\n        refuse('the passkey client data must be a webauthn.get assertion');\n    }\n    if (clientData.challenge !==\n        base64urlnopad.encode(hexToBytes(payload.challenge))) {\n        refuse('the passkey assertion does not sign the requested challenge');\n    }\n}\n/**\n * SEC1-compresses a P-256 public key: the 64-byte x‖y a viem WebAuthn\n * credential carries, or a 65-byte `0x04`-prefixed key. A 33-byte compressed\n * key is returned unchanged. Only the shape is checked, not that the point lies\n * on the curve.\n */\nexport function compressP256PublicKey(publicKey) {\n    const bytes = hexToBytes(publicKey);\n    if (bytes.length === 33 && (bytes[0] === 2 || bytes[0] === 3)) {\n        return publicKey;\n    }\n    const point = bytes.length === 64\n        ? bytes\n        : bytes.length === 65 && bytes[0] === 4\n            ? bytes.subarray(1)\n            : undefined;\n    if (!point) {\n        throw new InvalidSolanaTransactionArtifactError('the passkey public key must be a 64-byte x‖y, 65-byte uncompressed or 33-byte compressed P-256 key');\n    }\n    const prefix = point[63] % 2 === 0 ? 0x02 : 0x03;\n    return bytesToHex(new Uint8Array([prefix, ...point.subarray(0, 32)]));\n}\nexport async function submitSolanaIntent(context, signed) {\n    assertSolanaNotExpired(context.now(), signed.prepared.quote);\n    const action = signed.prepared.input.action;\n    const payload = spendPayload(signed.prepared.quote, signed.prepared.input, deliveryKind(signed.prepared.input));\n    const authority = signed.prepared.input.authority;\n    const [proof, ...evmProofs] = signed.proofs;\n    if (authority.kind === 'secp256r1' && proof.kind === 'webauthn') {\n        validateSolanaWebAuthnAssertion(payload, proof.assertion);\n    }\n    else if (authority.kind === 'secp256k1' && proof.kind === 'personalSign') {\n        await validateSolanaSignature(authority.address, payload, proof.signature);\n    }\n    else {\n        throw new InvalidSolanaTransactionArtifactError('the spend proof does not match the configured Solana authority', { intentId: signed.prepared.quote.intentId });\n    }\n    assertEvmProofs(signed.prepared.quote, evmProofs);\n    const response = await context.submissionClient.submitIntent({\n        intentId: signed.prepared.quote.intentId,\n        proofs: [proof, ...evmProofs],\n    });\n    return {\n        type: 'intent',\n        traceId: response.traceId,\n        intentId: response.intentId,\n        sourceChains: [solanaChainId(signed.prepared.input.chain)],\n        targetChain: action.kind === 'transfer' && action.delivery.kind === 'cross-chain'\n            ? action.delivery.chainId\n            : solanaChainId(signed.prepared.input.chain),\n    };\n}\n","// CAIP-2 wire format. EVM chains map programmatically (`eip155:<id>`); the\n// handful of non-EVM / virtual chains carry an explicit id ↔ caip2 mapping.\n//\n// v2: this small table is bundled here rather than read from\n// `@rhinestone/shared-configs`. EVM is the common case and needs no table, so a\n// new EVM chain needs no SDK change; a new non-EVM chain is rare and adds one\n// entry below. Every HyperCore id is EVM-*settled*, so `isNonEvmChainId` is\n// `false` for all of them even though their wire ids are the non-`eip155`\n// `hypercore:` namespace.\n//\n// This table is TRANSLATION, not policy: it answers \"what number is this wire\n// id\", and adding an entry does not make that chain a legal destination. Which\n// HyperCore ids you may TARGET is `HyperCoreCaip2ChainId` and the exported\n// descriptors — only the two venues. `hypercore:mainnet` is here because it is a\n// real chain (the Core L1, where deposits originate) that can appear in a\n// response we have to parse; it is not an addressable target (RHI-5510).\n//\n// Spec: https://chainagnostic.org/CAIPs/caip-2\nconst NON_EVM_CHAINS = [\n    { id: 1337, caip2: 'hypercore:mainnet', nonEvm: false },\n    { id: 1337001, caip2: 'hypercore:spot', nonEvm: false },\n    { id: 1337002, caip2: 'hypercore:perp', nonEvm: false },\n    { id: 728126428, caip2: 'tron:mainnet', nonEvm: true },\n    {\n        id: 792703809,\n        caip2: 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp',\n        nonEvm: true,\n    },\n    {\n        id: 792703810,\n        caip2: 'solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1',\n        nonEvm: true,\n    },\n    { id: 1500148, caip2: 'stellar:pubnet', nonEvm: true },\n];\nconst HYPERCORE_WIRE_IDS = new Set(NON_EVM_CHAINS.filter((chain) => chain.caip2.startsWith('hypercore:')).map((chain) => chain.id));\n/**\n * True when a chain id's wire form is in the `hypercore:` namespace.\n *\n * This is the one combination the `caip2.startsWith('eip155:')` test gets wrong:\n * HyperCore is EVM-*addressed* (hex recipients, EIP-712 signing) while its wire\n * id is not `eip155:`, so every place that decides \"is this reference EVM\" must\n * ask this too. Two places did it as `chainId === 1337`, which silently became\n * wrong the moment HyperCore gained a second id — derived from the table here so\n * a third venue cannot reintroduce it.\n *\n * NOT the same as `isHyperCoreChainId` in `@rhinestone/shared-configs`, which\n * answers \"is this a delivery VENUE\" and is deliberately false for the Core L1.\n * This one is about address shape, so it is true for all three.\n */\nexport function isHyperCoreWireId(chainId) {\n    return HYPERCORE_WIRE_IDS.has(chainId);\n}\nconst evmPattern = /^eip155:(0|[1-9]\\d*)$/;\nexport function formatCaip2(chainId) {\n    if (!Number.isSafeInteger(chainId) || chainId < 0) {\n        throw new Error(`Invalid chain id: ${chainId}`);\n    }\n    const nonEvm = NON_EVM_CHAINS.find((chain) => chain.id === chainId);\n    return nonEvm ? nonEvm.caip2 : `eip155:${chainId}`;\n}\nexport function chainIdFromCaip2(value) {\n    if (evmPattern.test(value)) {\n        return Number(value.slice('eip155:'.length));\n    }\n    return NON_EVM_CHAINS.find((chain) => chain.caip2 === value)?.id;\n}\nexport function parseCaip2(value) {\n    if (evmPattern.test(value)) {\n        const id = Number(value.slice('eip155:'.length));\n        return { kind: 'evm', id, caip2: `eip155:${id}` };\n    }\n    const id = chainIdFromCaip2(value);\n    if (id === undefined) {\n        throw new Error(`Invalid CAIP-2 chain id: ${value}`);\n    }\n    if (!isNonEvmChainId(id)) {\n        return { kind: 'evm', id, caip2: value };\n    }\n    const separator = value.indexOf(':');\n    return {\n        kind: 'non-evm',\n        namespace: value.slice(0, separator),\n        reference: value.slice(separator + 1),\n        caip2: value,\n    };\n}\nexport function toEvmChainReference(chainId) {\n    const caip2 = formatCaip2(chainId);\n    if (!caip2.startsWith('eip155:') && !isHyperCoreWireId(chainId)) {\n        throw new Error(`Chain ${chainId} is not EVM-compatible`);\n    }\n    return {\n        kind: 'evm',\n        id: chainId,\n        caip2: caip2,\n    };\n}\n/**\n * The execution environment of a chain, which is NOT `ChainReference.kind`:\n * HyperCore is EVM-*settled* and so reads as `kind: 'evm'`, while its own\n * destination shape and evidence are `hypercore`.\n */\nexport function chainVm(chain) {\n    const namespace = chain.caip2.slice(0, chain.caip2.indexOf(':'));\n    switch (namespace) {\n        case 'hypercore':\n            return 'hypercore';\n        case 'solana':\n            return 'svm';\n        case 'tron':\n            return 'tvm';\n        case 'stellar':\n            return 'stellar';\n        case 'eip155':\n            return 'evm';\n        default:\n            throw new Error(`Unsupported chain namespace: ${chain.caip2}`);\n    }\n}\nexport function chainIdFromReference(chain) {\n    if (chain.kind === 'evm')\n        return chain.id;\n    const id = chainIdFromCaip2(chain.caip2);\n    if (id === undefined) {\n        throw new Error(`Invalid CAIP-2 chain id: ${chain.caip2}`);\n    }\n    return id;\n}\nexport function isCaip2(value) {\n    return evmPattern.test(value) || chainIdFromCaip2(value) !== undefined;\n}\nexport function isEvmCaip2(value) {\n    return evmPattern.test(value);\n}\n// True when a numeric chain id is genuinely non-EVM (Solana / Tron / Stellar). Every\n// HyperCore id is EVM-settled, so this is `false` for all of them even though\n// their wire ids are in the non-`eip155` `hypercore:` namespace.\nexport function isNonEvmChainId(chainId) {\n    return NON_EVM_CHAINS.some((chain) => chain.id === chainId && chain.nonEvm);\n}\n","export function serializeBigInts(value) {\n    if (typeof value === 'bigint')\n        return value.toString();\n    if (Array.isArray(value)) {\n        return value.map(serializeBigInts);\n    }\n    if (value && typeof value === 'object') {\n        return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, serializeBigInts(item)]));\n    }\n    return value;\n}\n","import { serializeBigInts } from './serialization.js';\n// The normalized input is structurally the public `IntentInput` with `readonly`\n// modifiers, so the serialized value is a `SerializedIntentInput` — the cast\n// only re-attaches the type `serializeBigInts` erases.\nexport function projectCompatibleIntentInput(input) {\n    return serializeBigInts(input);\n}\n/** Whether the normalized input asks for any sponsorship. */\nexport function isSponsoredIntentInput(input) {\n    return Boolean(input.options.sponsorSettings);\n}\n","class ExecutionError extends Error {\n    _message;\n    _context;\n    _errorType;\n    _traceId;\n    constructor(params) {\n        super();\n        this._message = params?.message || 'ExecutionError';\n        this._context = params?.context || {};\n        this._errorType = params?.errorType || 'Unknown';\n        this._traceId = params?.traceId || '';\n    }\n    get message() {\n        return this._message;\n    }\n    get context() {\n        return this._context;\n    }\n    get errorType() {\n        return this._errorType;\n    }\n    get traceId() {\n        return this._traceId;\n    }\n}\nclass SignerNotSupportedError extends ExecutionError {\n    constructor(params) {\n        super({\n            message: 'Sending a transaction is not supported for this type of signers. Use user operations instead.',\n            ...params,\n        });\n    }\n}\nclass OrderPathRequiredForIntentsError extends ExecutionError {\n    constructor(params) {\n        super({\n            message: 'Order path is required when using intents',\n            ...params,\n        });\n    }\n}\nclass IntentFailedError extends ExecutionError {\n    constructor(params) {\n        super({\n            message: 'Intent failed',\n            ...params,\n        });\n    }\n}\nclass QuoteNotInPreparedTransactionError extends ExecutionError {\n    constructor(params) {\n        super({\n            message: 'Selected quote does not belong to the prepared transaction. Re-prepare and try again.',\n            ...params,\n        });\n    }\n}\n/** Thrown when a Solana quote's approximate signing deadline has passed. */\nclass SolanaQuoteExpiredError extends ExecutionError {\n    constructor(intentId) {\n        super({\n            message: `Solana intent ${intentId} has expired. Re-prepare the transaction and sign the new quote; do not retry an uncertain prior submission without checking its status.`,\n            context: { intentId },\n            errorType: 'SolanaQuoteExpired',\n        });\n    }\n}\n/** Thrown when persisted Solana lifecycle data is incomplete or inconsistent. */\nclass InvalidSolanaTransactionArtifactError extends ExecutionError {\n    constructor(message, context) {\n        super({\n            message: `Invalid Solana transaction artifact: ${message}`,\n            context,\n            errorType: 'InvalidSolanaTransactionArtifact',\n        });\n    }\n}\nclass InvalidSourceCallsError extends ExecutionError {\n    constructor(params) {\n        super({\n            message: params?.chainId !== undefined\n                ? `sourceCalls includes chainId ${params.chainId} which is not in sourceChains (or the target chain for same-chain transactions)`\n                : 'sourceCalls includes a chainId not in sourceChains (or the target chain for same-chain transactions)',\n            ...params,\n        });\n    }\n}\nclass Eip7702InitSignatureRequiredError extends ExecutionError {\n    constructor(params) {\n        super({\n            message: 'EIP-7702 initialization signature is required for 7702 accounts. This signature is needed during transaction preparation, even if your account is already deployed on all chains. Use `getEip7702InitSignature()` to generate it.',\n            ...params,\n        });\n    }\n}\nclass UnknownOwnerError extends ExecutionError {\n    constructor(params) {\n        super({\n            message: 'The provided owner is not part of the account owner set. Pass an account that matches one of the configured `owners` (for multi-factor owner sets, also pass the matching `validatorId`).',\n            ...params,\n        });\n    }\n}\nclass MismatchedOwnerSignaturesError extends ExecutionError {\n    constructor(params) {\n        super({\n            message: params?.message ??\n                'Owner signatures are inconsistent and cannot be assembled. All owners must sign the same prepared transaction and quote using `signTransaction` with the `owner` option.',\n            ...params,\n        });\n    }\n}\nclass InsufficientOwnerSignaturesError extends ExecutionError {\n    constructor(params) {\n        super({\n            message: params?.required !== undefined\n                ? params?.validatorId !== undefined\n                    ? `Not enough owner signatures to meet the threshold of validator ${params.validatorId}: ${params.provided ?? 0} of ${params.required} required. Collect the missing owner signatures before calling \\`assembleTransaction\\`.`\n                    : `Not enough owner signatures to meet the account threshold: ${params.provided ?? 0} of ${params.required} required. Collect the missing owner signatures before calling \\`assembleTransaction\\`.`\n                : 'Not enough owner signatures to meet the account threshold. Collect the missing owner signatures before calling `assembleTransaction`.',\n            context: {\n                required: params?.required,\n                provided: params?.provided,\n                validatorId: params?.validatorId,\n                ...params?.context,\n            },\n            errorType: params?.errorType,\n            traceId: params?.traceId,\n        });\n    }\n}\nclass InvalidOwnerSigningOptionsError extends ExecutionError {\n    constructor(params) {\n        super({\n            message: 'Invalid per-owner signing options. Pass `validatorId` only for multi-factor accounts, where it must identify the factor containing `owner`.',\n            ...params,\n        });\n    }\n}\nclass IndependentSigningNotSupportedError extends ExecutionError {\n    constructor(params) {\n        super({\n            message: 'Independent owner signing is only supported for smart accounts using ECDSA, passkey, or multi-factor owners. EOA accounts, smart sessions, and K1/ERC-7739 validators must use the standard `signTransaction` flow.',\n            ...params,\n        });\n    }\n}\nclass InvalidPreparedTransactionError extends ExecutionError {\n    constructor(params) {\n        super({\n            message: 'This prepared transaction was created for an earlier orchestrator wire version and cannot be signed or submitted. Reconcile the original submission, then prepare the transaction again.',\n            ...params,\n        });\n    }\n}\nclass UnsupportedSigningRequestError extends ExecutionError {\n    constructor(params) {\n        super({\n            message: params.reason ??\n                `The quote asks for a \\`${params.payloadKind}\\` signature at request ${params.index}, which this SDK version cannot produce. Upgrade the SDK, or change the intent so the route does not require it.`,\n            context: {\n                requestIndex: params.index,\n                payloadKind: params.payloadKind,\n                ...params.context,\n            },\n            ...(params.errorType ? { errorType: params.errorType } : {}),\n            ...(params.traceId ? { traceId: params.traceId } : {}),\n        });\n    }\n}\nclass IncompleteIntentProofsError extends ExecutionError {\n    constructor(params) {\n        super({\n            message: `Intent ${params.intentId} is missing proofs for signing request${params.missing.length === 1 ? '' : 's'} ${params.missing.join(', ')}. Every request in \\`quote.signingRequests\\` needs its own proof before the transaction can be submitted.`,\n            context: {\n                intentId: params.intentId,\n                missing: [...params.missing],\n                ...params.context,\n            },\n            ...(params.errorType ? { errorType: params.errorType } : {}),\n            ...(params.traceId ? { traceId: params.traceId } : {}),\n        });\n    }\n}\nclass MismatchedIntentProofError extends ExecutionError {\n    constructor(params) {\n        super({\n            message: params?.message ??\n                'A supplied proof does not belong to this prepared transaction. Contributions are bound to the intent, the exact ordered request set, and the request index they answer.',\n            ...params,\n        });\n    }\n}\n/**\n * Intent-scoped sponsorship cannot bind this request: the approval input the\n * integrator would sign is not exactly what the orchestrator can recompute\n * from the quote request. Thrown before `getIntentExtensionToken` runs and\n * before anything is quoted.\n */\nclass UnsupportedSponsorshipApprovalError extends ExecutionError {\n    constructor(params) {\n        super({\n            message: `Intent-scoped sponsorship cannot bind this request${params.field ? ` (${params.field})` : ''}: its approval input does not exactly describe the quote request. Remove the unsupported option, or use project-wide sponsorship for this transaction.`,\n            context: {\n                reason: params.reason,\n                ...(params.field ? { field: params.field } : {}),\n            },\n            errorType: 'UnsupportedSponsorshipApproval',\n        });\n    }\n}\nfunction isExecutionError(error) {\n    return error instanceof ExecutionError;\n}\nfunction isSolanaQuoteExpiredError(error) {\n    return error instanceof SolanaQuoteExpiredError;\n}\nfunction isInvalidSolanaTransactionArtifactError(error) {\n    return error instanceof InvalidSolanaTransactionArtifactError;\n}\nexport { isExecutionError, isInvalidSolanaTransactionArtifactError, isSolanaQuoteExpiredError, ExecutionError, Eip7702InitSignatureRequiredError, IncompleteIntentProofsError, IndependentSigningNotSupportedError, InsufficientOwnerSignaturesError, IntentFailedError, InvalidOwnerSigningOptionsError, InvalidPreparedTransactionError, InvalidSolanaTransactionArtifactError, InvalidSourceCallsError, MismatchedIntentProofError, MismatchedOwnerSignaturesError, OrderPathRequiredForIntentsError, QuoteNotInPreparedTransactionError, SignerNotSupportedError, SolanaQuoteExpiredError, UnknownOwnerError, UnsupportedSigningRequestError, UnsupportedSponsorshipApprovalError, };\n","import { concat, hexToBytes, toHex } from 'viem';\nimport { selectSignerChain } from './wallet-chain.js';\nexport async function invokeEcdsaSigner(input) {\n    const account = input.signer.account;\n    const chain = invocationChain(input.invocation);\n    await selectSignerChain({\n        account,\n        ...(chain ? { chain } : {}),\n        ...(input.resolveChain ? { resolveChain: input.resolveChain } : {}),\n    });\n    switch (input.invocation.kind) {\n        case 'ecdsa-sign-message': {\n            if (!account.signMessage)\n                throw new Error('Account does not support signMessage');\n            const signature = await account.signMessage({\n                message: input.invocation.message,\n            });\n            return {\n                kind: 'ecdsa-signature',\n                signature: normalizeRecovery(signature),\n            };\n        }\n        case 'ecdsa-sign-hash': {\n            if (!account.sign)\n                throw new Error('Account does not support sign');\n            return {\n                kind: 'ecdsa-signature',\n                signature: normalizeRecovery(await account.sign({ hash: input.invocation.hash })),\n            };\n        }\n        case 'ecdsa-sign-typed-data': {\n            if (!account.signTypedData)\n                throw new Error('Account does not support signTypedData');\n            const signature = await account.signTypedData(input.invocation.typedData);\n            return {\n                kind: 'ecdsa-signature',\n                signature: normalizeRecovery(signature),\n            };\n        }\n        case 'sign-authorization': {\n            if (!account.signAuthorization) {\n                throw new Error('Account does not support signAuthorization');\n            }\n            return {\n                kind: 'signed-authorization',\n                authorization: await account.signAuthorization(input.invocation.authorization),\n            };\n        }\n    }\n}\nfunction invocationChain(invocation) {\n    return 'chain' in invocation ? invocation.chain : undefined;\n}\nexport function normalizeRecovery(signature) {\n    const bytes = hexToBytes(signature);\n    if (bytes.length !== 65)\n        return signature;\n    const recovery = bytes[64];\n    if (recovery >= 27)\n        return signature;\n    return concat([signature.slice(0, -2), toHex(recovery + 27)]);\n}\n","import { createWalletClient, custom } from 'viem';\nexport async function selectSignerChain(input) {\n    if (!input.chain || !input.resolveChain)\n        return;\n    const transport = input.account.client?.transport;\n    if (!transport)\n        return;\n    const chain = input.resolveChain(input.chain);\n    const walletClient = createWalletClient({\n        account: input.account,\n        chain,\n        transport: custom(transport),\n    });\n    await walletClient.switchChain({ id: chain.id });\n}\n","import { Eip7702InitSignatureRequiredError } from '../../errors/execution.js';\n/** Wraps a resolved account so it can be used as an intent recipient. */\nexport function asIntentRecipient(account) {\n    const { kind, ...rest } = account;\n    return { kind: 'account', accountKind: kind, ...rest };\n}\nexport function projectIntentAccount(input) {\n    const { runtime } = input;\n    const adoption = runtime.construction.eoa\n        ? runtime.adapter.getEip7702AdoptionPlan?.(runtime.construction)\n        : undefined;\n    const setupOps = input.setupOverride\n        ? [...input.setupOverride]\n        : adoption\n            ? [eip7702SetupOp(runtime, input.eip7702InitSignature)]\n            : deploymentSetupOps(runtime);\n    return {\n        // An adopted 7702 account is an ERC-7579 account WITH delegations, not a\n        // stripped EOA: it still routes through its setup op and its signature is\n        // still validated by the account.\n        kind: runtime.construction.account.kind === 'eoa' ? 'eoa' : 'erc7579',\n        address: runtime.identity.address,\n        setupOps,\n        ...(adoption ? { delegationContract: adoption.contract } : {}),\n    };\n}\n/** The Caucasus `account.evm` entry. */\nexport function toWireEvmAccount(projection, extras) {\n    const delegations = projection.delegationContract\n        ? { default: { contract: projection.delegationContract } }\n        : undefined;\n    if (projection.kind === 'eoa') {\n        // A true EOA permits neither setup operations nor simulation stubs.\n        return {\n            type: 'eoa',\n            address: projection.address,\n            ...(extras?.signatureMode === undefined\n                ? {}\n                : { signatureMode: extras.signatureMode }),\n            ...(delegations ? { delegations } : {}),\n        };\n    }\n    return {\n        type: 'erc7579',\n        address: projection.address,\n        ...(projection.setupOps.length > 0\n            ? { initData: { setupOps: projection.setupOps } }\n            : {}),\n        ...(extras?.signatureMode === undefined\n            ? {}\n            : { signatureMode: extras.signatureMode }),\n        ...(delegations ? { delegations } : {}),\n        ...(extras?.mockSignaturesByChain\n            ? { simulation: { mockSignaturesByChain: extras.mockSignaturesByChain } }\n            : {}),\n    };\n}\nexport function toWireRecipient(recipient) {\n    if (recipient.kind === 'bare') {\n        return { address: recipient.address };\n    }\n    const { accountKind: kind, address, setupOps, delegationContract } = recipient;\n    const delegations = delegationContract\n        ? { default: { contract: delegationContract } }\n        : undefined;\n    if (kind === 'eoa') {\n        return { type: 'eoa', address, ...(delegations ? { delegations } : {}) };\n    }\n    return {\n        type: 'erc7579',\n        address,\n        ...(setupOps.length > 0 ? { initData: { setupOps } } : {}),\n        ...(delegations ? { delegations } : {}),\n    };\n}\n/** The account as the normalized sponsorship input has always spelled it. */\nexport function toNormalizedAccount(projection, extras) {\n    return {\n        address: projection.address,\n        accountType: projection.kind === 'eoa' ? 'EOA' : 'ERC7579',\n        setupOps: projection.setupOps,\n        // The key is always present (undefined for non-7702 accounts, a chain-zero\n        // map for 7702). That is the shape existing sponsorship digests were\n        // computed over, so it survives the wire migration unchanged.\n        delegations: projection.delegationContract\n            ? { 0: { contract: projection.delegationContract } }\n            : undefined,\n        ...(extras?.mockSignatures\n            ? { mockSignatures: extras.mockSignatures }\n            : {}),\n    };\n}\nexport function toNormalizedRecipient(recipient, destination) {\n    if (recipient.kind === 'bare') {\n        // The released input spells an EVM-addressed payee as a setup-free EOA.\n        // The wire now sends it bare, but existing policies and digests were built\n        // against this spelling, so the approval input keeps it.\n        return destination.evmAddressed\n            ? { address: recipient.address, accountType: 'EOA', setupOps: [] }\n            : { address: recipient.address };\n    }\n    return toNormalizedAccount({\n        kind: recipient.accountKind,\n        address: recipient.address,\n        setupOps: recipient.setupOps,\n        ...(recipient.delegationContract\n            ? { delegationContract: recipient.delegationContract }\n            : {}),\n    });\n}\nfunction deploymentSetupOps(runtime) {\n    const deployment = runtime.adapter.getDeploymentPlan(runtime.construction);\n    return !deployment.factory || !deployment.factoryData\n        ? []\n        : [{ to: deployment.factory, data: deployment.factoryData }];\n}\n// A 7702 account is routed by its `initializeAccount` setup op, which requires\n// the EIP-7702 init signature at preparation time — even when the account is\n// already deployed. Without it the orchestrator sees a bare smart account and\n// finds no viable route.\nfunction eip7702SetupOp(runtime, eip7702InitSignature) {\n    if (!eip7702InitSignature ||\n        eip7702InitSignature === '0x' ||\n        !runtime.adapter.getEip7702InitCall) {\n        throw new Eip7702InitSignatureRequiredError();\n    }\n    return {\n        to: runtime.identity.address,\n        data: runtime.adapter.getEip7702InitCall(runtime.construction, eip7702InitSignature),\n    };\n}\nexport function projectIntentRecipient(recipient) {\n    // A bare address is a payee and nothing more. The old projection attached an\n    // `EOA` account type with empty setup ops on EVM destinations, which read on\n    // the wire as \"this recipient can execute\" — it cannot.\n    return recipient ? { kind: 'bare', address: recipient } : undefined;\n}\n","import { InvalidPreparedTransactionError } from '../../errors/execution.js';\n/**\n * Serializes a quote's signing payloads for the public prepared data.\n *\n * Typed-data messages are normalized to bigints for hashing; the persisted form\n * has to survive `JSON.stringify`, so they go back to decimal strings here and\n * `normalizeIntentQuote` restores them on the way in. Cost and requirement\n * amounts stay bigint — that is their published type.\n */\nexport function projectCompatibleQuote(quote) {\n    return {\n        ...quote,\n        signingRequests: serializeBigInts(quote.signingRequests),\n    };\n}\n/** The wire generation a persisted request was built for. */\nexport const PREPARED_REQUEST_VERSION = 'caucasus-1';\nexport function projectPreparedBinding(request) {\n    return {\n        version: PREPARED_REQUEST_VERSION,\n        request: serializeBigInts(request),\n    };\n}\n/**\n * Refuses a prepared payload from an earlier wire generation.\n *\n * Called before anything reads the artifact's quotes, so an older shape fails\n * with this typed error rather than tripping over a missing field.\n */\nexport function assertPreparedBinding(binding) {\n    if (!binding || binding.version !== PREPARED_REQUEST_VERSION) {\n        throw new InvalidPreparedTransactionError({\n            context: { version: binding?.version ?? null },\n        });\n    }\n}\nexport function restorePreparedBinding(binding) {\n    assertPreparedBinding(binding);\n    return binding.request;\n}\nfunction serializeBigInts(value) {\n    if (typeof value === 'bigint')\n        return value.toString();\n    if (Array.isArray(value))\n        return value.map(serializeBigInts);\n    if (value && typeof value === 'object') {\n        return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, serializeBigInts(item)]));\n    }\n    return value;\n}\n","import { chainIdFromCaip2 } from '../../chains/caip2.js';\nclass OrchestratorError extends Error {\n    code;\n    traceId;\n    statusCode;\n    constructor(params) {\n        super(params.message);\n        this.code = params.code ?? 'UNKNOWN';\n        this.traceId = params.traceId ?? '';\n        this.statusCode = params.statusCode;\n    }\n}\nclass ValidationError extends OrchestratorError {\n    issues;\n    constructor(params) {\n        super({ ...params, code: 'VALIDATION_ERROR' });\n        this.issues = params.issues ?? [];\n    }\n}\n/**\n * The EVM-derived Solana account has not been created on the requested cluster.\n * Create and authority-verify `swigAddress` before preparing another transfer.\n *\n * `chainId` is the SDK's numeric id for the cluster, and is absent when the\n * response carries no usable chain id.\n */\nclass SolanaAccountNotCreatedError extends ValidationError {\n    swigAddress;\n    chainId;\n    constructor(params) {\n        super(params);\n        this.swigAddress = params.swigAddress;\n        this.chainId = params.chainId;\n    }\n}\nclass InsufficientLiquidityError extends OrchestratorError {\n    availableIntents;\n    unfillable;\n    constructor(params) {\n        super({ ...params, code: 'INSUFFICIENT_LIQUIDITY' });\n        this.availableIntents = params.availableIntents;\n        this.unfillable = params.unfillable;\n    }\n}\nclass NotFoundError extends OrchestratorError {\n    constructor(params) {\n        super({ ...params, code: 'NOT_FOUND' });\n    }\n}\nclass UnauthorizedError extends OrchestratorError {\n    constructor(params) {\n        super({ ...params, code: 'UNAUTHORIZED' });\n    }\n}\nclass ForbiddenError extends OrchestratorError {\n    constructor(params) {\n        super({ ...params, code: params.code ?? 'FORBIDDEN' });\n    }\n}\n/**\n * Thrown when an API key's scope denies the request.\n *\n * Subclass of `ForbiddenError` carrying the failed `scope` and the\n * `required` / `actual` levels — distinct from a generic 403 so integrators\n * can prompt the user to widen the key's scope rather than rotate it.\n */\nclass KeyScopeDeniedError extends ForbiddenError {\n    scope;\n    required;\n    actual;\n    constructor(params) {\n        super({ ...params, code: 'KEY_SCOPE_DENIED' });\n        this.scope = params.scope;\n        this.required = params.required;\n        this.actual = params.actual;\n    }\n}\nclass ConflictError extends OrchestratorError {\n    details;\n    constructor(params) {\n        super({ ...params, code: 'CONFLICT' });\n        this.details = params.details ?? [];\n    }\n}\nclass UnprocessableContentError extends OrchestratorError {\n    details;\n    constructor(params) {\n        super({ ...params, code: 'UNPROCESSABLE_CONTENT' });\n        this.details = params.details ?? [];\n    }\n}\n/**\n * The Swig a Solana account creation targets already exists on the requested\n * cluster. Internal: `deploy('solana', …)` resolves `true` on it.\n *\n * Extends {@link UnprocessableContentError} and keeps its `code`. `chainId` is\n * the SDK's numeric id for the cluster, and is absent when the response carries\n * no usable chain id.\n */\nclass SolanaAccountAlreadyCreatedError extends UnprocessableContentError {\n    swigAddress;\n    chainId;\n    constructor(params) {\n        super(params);\n        this.swigAddress = params.swigAddress;\n        this.chainId = params.chainId;\n    }\n}\n/** Per-client sponsorship cap a quote can breach. Mirrors the orchestrator's\n * `SponsorLimits` keys: per-intent gas, per-intent bridge fee, or the\n * per-intent aggregate. */\nconst SPONSOR_LIMIT_KEYS = [\n    'gasPerIntentUSD',\n    'bridgeFeePerIntentUSD',\n    'perIntentUSD',\n];\n/**\n * A configured per-client sponsorship cap was exceeded by a quote.\n *\n * A `422 UNPROCESSABLE_CONTENT` specialization: the integrator's sponsor\n * policy sets a per-intent USD ceiling (gas, bridge-fee, or aggregate) and\n * this quote's sponsored coverage would exceed it. Distinct from\n * {@link InsufficientSponsorBalanceError} (a funds shortfall) — a cap breach\n * is deterministic and does NOT clear by topping up the sponsorship balance;\n * the cap itself must be raised or the intent made cheaper.\n *\n * Extends {@link UnprocessableContentError} and keeps `code` as\n * `'UNPROCESSABLE_CONTENT'` (the wire does not yet carry a dedicated code), so\n * existing handling of that error still catches it. `sponsorAddress` is\n * populated only for the pre-fold check; the post-fold multi-candidate\n * rejection omits it, so treat every field as best-effort.\n */\nclass SponsorLimitExceededError extends UnprocessableContentError {\n    limitKey;\n    capUsd;\n    coverageUsd;\n    sponsorAddress;\n    constructor(params) {\n        super(params);\n        this.limitKey = params.limitKey;\n        this.capUsd = params.capUsd;\n        this.coverageUsd = params.coverageUsd;\n        this.sponsorAddress = params.sponsorAddress;\n    }\n}\n/**\n * The sponsor's prefunded balance cannot cover the sponsored categories for a\n * quote.\n *\n * A `422 UNPROCESSABLE_CONTENT` specialization. Coverage is all-or-nothing:\n * `failedCategories` lists the enabled categories (`gas`, `bridgeFee`,\n * `swapFee`) that could not be covered. Unlike\n * {@link SponsorLimitExceededError} (a configured policy cap), this clears once\n * the sponsorship balance is topped up.\n *\n * Extends {@link UnprocessableContentError} and keeps `code` as\n * `'UNPROCESSABLE_CONTENT'`, so existing handling of that error still catches\n * it.\n */\nclass InsufficientSponsorBalanceError extends UnprocessableContentError {\n    failedCategories;\n    sponsorAddress;\n    remainingBalanceUsd;\n    totalSponsoredUsd;\n    constructor(params) {\n        super(params);\n        this.failedCategories = params.failedCategories ?? [];\n        this.sponsorAddress = params.sponsorAddress;\n        this.remainingBalanceUsd = params.remainingBalanceUsd;\n        this.totalSponsoredUsd = params.totalSponsoredUsd;\n    }\n}\nclass RateLimitedError extends OrchestratorError {\n    retryAfter;\n    constructor(params) {\n        super({ ...params, code: 'TOO_MANY_REQUESTS' });\n        this.retryAfter = params.retryAfter;\n    }\n}\nclass SettlementQuoteError extends OrchestratorError {\n    constructor(params) {\n        super({ ...params, code: 'SETTLEMENT_QUOTE_ERROR' });\n    }\n}\nclass SettlementExecutionError extends OrchestratorError {\n    constructor(params) {\n        super({ ...params, code: 'SETTLEMENT_EXECUTION_ERROR' });\n    }\n}\nclass SimulationFailedError extends OrchestratorError {\n    nonce;\n    category;\n    errorSelector;\n    errorName;\n    errorArgs;\n    retryable;\n    retryHint;\n    simulations;\n    constructor(params) {\n        super({ ...params, code: 'SIMULATION_FAILED' });\n        this.nonce = params.nonce;\n        this.category = params.category;\n        this.errorSelector = params.errorSelector;\n        this.errorName = params.errorName;\n        this.errorArgs = params.errorArgs;\n        this.retryable = params.retryable ?? false;\n        this.retryHint = params.retryHint;\n        this.simulations = params.simulations ?? [];\n    }\n}\nclass ExternalServiceTimeoutError extends OrchestratorError {\n    constructor(params) {\n        super({ ...params, code: 'EXTERNAL_SERVICE_TIMEOUT' });\n    }\n}\nclass RelayerMarketUnavailableError extends OrchestratorError {\n    constructor(params) {\n        super({ ...params, code: 'RELAYER_MARKET_UNAVAILABLE' });\n    }\n}\nclass InternalServerError extends OrchestratorError {\n    constructor(params) {\n        super({ ...params, code: 'INTERNAL_ERROR' });\n    }\n}\nfunction parseTokenAmounts(record) {\n    return Object.fromEntries(Object.entries(record).map(([addr, amount]) => [addr, BigInt(amount)]));\n}\nfunction isRecord(value) {\n    return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\nfunction stringValue(value) {\n    return typeof value === 'string' ? value : undefined;\n}\nfunction booleanValue(value) {\n    return typeof value === 'boolean' ? value : undefined;\n}\nfunction numberValue(value) {\n    return typeof value === 'number' && Number.isFinite(value) ? value : undefined;\n}\nfunction recordValue(value) {\n    return isRecord(value) ? value : undefined;\n}\nfunction parseErrorDetails(details) {\n    if (!Array.isArray(details)) {\n        return [];\n    }\n    return details.flatMap((detail) => {\n        if (!isRecord(detail) || typeof detail.message !== 'string') {\n            return [];\n        }\n        const context = recordValue(detail.context);\n        return [\n            {\n                message: detail.message,\n                ...(context ? { context } : {}),\n            },\n        ];\n    });\n}\nconst SIMULATION_ACTIONS = ['claim', 'fill'];\nconst SIMULATION_RETRY_HINTS = ['RE_PREPARE', 'RETRY_LATER'];\nconst SIMULATION_ERROR_CATEGORIES = [\n    'QUOTE_EXPIRED',\n    'ORDER_EXPIRED',\n    'PERMIT_EXPIRED',\n    'PERMIT2_NONCE_CONSUMED',\n    'EXECUTOR_NONCE_CONSUMED',\n    'INVALID_SIGNATURE',\n    'INVALID_PERMIT2_SIGNATURE',\n    'INVALID_CONTRACT_SIGNATURE',\n    'INVALID_SIGNER',\n    'INSUFFICIENT_BALANCE',\n    'INSUFFICIENT_ALLOWANCE',\n    'ACCOUNT_CREATION_FAILED',\n    'ACCOUNT_UNAUTHORIZED',\n    'ADAPTER_CALL_FAILED',\n    'EXECUTION_FAILED',\n    'CLAIM_FAILED',\n    'ROUTER_PAUSED',\n    'ADAPTER_NOT_FOUND',\n    'PANIC',\n    'REQUIRE_FAILED',\n    'UNCLASSIFIED_REVERT',\n    'EMPTY_REVERT',\n];\nfunction oneOf(value, allowed) {\n    return typeof value === 'string' && allowed.includes(value)\n        ? value\n        : undefined;\n}\nfunction stringArrayValue(value) {\n    return Array.isArray(value)\n        ? value.filter((item) => typeof item === 'string')\n        : undefined;\n}\nfunction parseSimulationCall(value) {\n    if (!isRecord(value)) {\n        return undefined;\n    }\n    return {\n        chainId: stringValue(value.chainId),\n        to: stringValue(value.to),\n        data: stringValue(value.data),\n        value: stringValue(value.value),\n    };\n}\nfunction parseSimulationDetails(value) {\n    if (!isRecord(value)) {\n        return undefined;\n    }\n    return {\n        stateOverride: value.stateOverride,\n        blockNumber: stringValue(value.blockNumber),\n        relayer: stringValue(value.relayer),\n        simulationUrls: stringArrayValue(value.simulationUrls),\n    };\n}\nfunction isSimulationFailureSimulation(value) {\n    return isRecord(value) && value.success === false;\n}\nfunction parseSimulationFailureSimulation(value) {\n    if (!isSimulationFailureSimulation(value)) {\n        return undefined;\n    }\n    return {\n        success: false,\n        action: oneOf(value.action, SIMULATION_ACTIONS),\n        chainId: stringValue(value.chainId),\n        call: parseSimulationCall(value.call),\n        errorSelector: stringValue(value.errorSelector),\n        errorName: stringValue(value.errorName),\n        errorArgs: recordValue(value.errorArgs),\n        errorCategory: oneOf(value.errorCategory, SIMULATION_ERROR_CATEGORIES),\n        details: parseSimulationDetails(value.details),\n    };\n}\nfunction parseSimulationFailureDetails(details) {\n    if (!isRecord(details)) {\n        return {};\n    }\n    return {\n        nonce: stringValue(details.nonce),\n        category: oneOf(details.category, SIMULATION_ERROR_CATEGORIES),\n        errorSelector: stringValue(details.errorSelector),\n        errorName: stringValue(details.errorName),\n        errorArgs: recordValue(details.errorArgs),\n        retryable: booleanValue(details.retryable),\n        retryHint: oneOf(details.retryHint, SIMULATION_RETRY_HINTS),\n        simulations: Array.isArray(details.simulations)\n            ? details.simulations\n                .map(parseSimulationFailureSimulation)\n                .filter((simulation) => simulation !== undefined)\n            : undefined,\n    };\n}\n/**\n * Detect a sponsor-specific failure inside a generic `UNPROCESSABLE_CONTENT`\n * envelope. The orchestrator collapses both sponsor errors onto that wire code\n * and carries the distinguishing code plus structured fields in the first\n * detail's `context`. This reads that (untyped) context defensively and mints\n * the typed error; anything unrecognized returns `undefined` so the caller\n * falls back to a plain {@link UnprocessableContentError}.\n *\n * Interim: keyed on `details[0].context.code`, which is not part of the formal\n * wire schema. If the orchestrator stops emitting it, detection degrades to the\n * generic error (non-breaking). Superseded once a dedicated wire code ships.\n */\nfunction parseSponsorError(base, details) {\n    const context = details[0]?.context;\n    if (!context) {\n        return undefined;\n    }\n    switch (stringValue(context.code)) {\n        case 'SPONSOR_LIMIT_EXCEEDED':\n            return new SponsorLimitExceededError({\n                ...base,\n                details,\n                limitKey: oneOf(context.limitKey, SPONSOR_LIMIT_KEYS),\n                capUsd: numberValue(context.capUSD),\n                coverageUsd: numberValue(context.coverageUSD),\n                sponsorAddress: stringValue(context.sponsorAddress),\n            });\n        case 'INSUFFICIENT_SPONSOR_BALANCE':\n            return new InsufficientSponsorBalanceError({\n                ...base,\n                details,\n                failedCategories: stringArrayValue(context.failedCategories),\n                sponsorAddress: stringValue(context.sponsorAddress),\n                remainingBalanceUsd: numberValue(context.remainingBalanceUSD),\n                totalSponsoredUsd: numberValue(context.totalSponsoredUSD),\n            });\n        default:\n            return undefined;\n    }\n}\n/**\n * Normalize `context.chainId` to the SDK's numeric chain ids. The error\n * boundary lowers it to CAIP-2 (`solana:EtWTRAB…`); older orchestrators send a\n * number. Anything else — including a chain this SDK version has no id for —\n * yields `undefined`, which drops the chain hint without losing the error\n * identity; the raw value stays readable on `issues[].context`.\n */\nfunction parseContextChainId(value) {\n    if (typeof value === 'string') {\n        return chainIdFromCaip2(value);\n    }\n    if (typeof value === 'number' && Number.isSafeInteger(value) && value >= 0) {\n        return value;\n    }\n    return undefined;\n}\nfunction parseSolanaAccountNotCreatedError(base, issues) {\n    const context = issues.find((issue) => issue.context?.code === 'SOLANA_ACCOUNT_NOT_CREATED')?.context;\n    if (!context ||\n        typeof context.swigAddress !== 'string' ||\n        context.swigAddress.length === 0) {\n        return undefined;\n    }\n    const chainId = parseContextChainId(context.chainId);\n    return new SolanaAccountNotCreatedError({\n        ...base,\n        issues,\n        swigAddress: context.swigAddress,\n        ...(chainId === undefined ? {} : { chainId }),\n    });\n}\n// `ACCOUNT_ALREADY_DEPLOYED` is shared with EVM setup-only intents; only a\n// refusal naming a Swig is the Solana one.\nfunction parseSolanaAccountAlreadyCreatedError(base, details) {\n    const context = details.find((detail) => detail.context?.code === 'ACCOUNT_ALREADY_DEPLOYED' &&\n        typeof detail.context.swig === 'string' &&\n        detail.context.swig.length > 0)?.context;\n    if (!context) {\n        return undefined;\n    }\n    const chainId = parseContextChainId(context.destinationChainId);\n    return new SolanaAccountAlreadyCreatedError({\n        ...base,\n        details,\n        swigAddress: context.swig,\n        ...(chainId === undefined ? {} : { chainId }),\n    });\n}\nfunction parseErrorEnvelope(envelope, statusCode, retryAfter) {\n    const base = {\n        message: envelope.message,\n        traceId: envelope.traceId,\n        statusCode,\n    };\n    switch (envelope.code) {\n        case 'VALIDATION_ERROR': {\n            const issues = parseErrorDetails(envelope.details);\n            return (parseSolanaAccountNotCreatedError(base, issues) ??\n                new ValidationError({ ...base, issues }));\n        }\n        case 'INSUFFICIENT_LIQUIDITY': {\n            const details = (envelope.details ?? {});\n            return new InsufficientLiquidityError({\n                ...base,\n                availableIntents: (details.availableIntents ?? []).map(parseTokenAmounts),\n                unfillable: parseTokenAmounts(details.unfillable ?? {}),\n            });\n        }\n        case 'NOT_FOUND':\n            return new NotFoundError(base);\n        case 'UNAUTHORIZED':\n            return new UnauthorizedError(base);\n        case 'FORBIDDEN':\n            return new ForbiddenError(base);\n        case 'KEY_SCOPE_DENIED': {\n            const detail = Array.isArray(envelope.details)\n                ? envelope.details[0]\n                : undefined;\n            const context = (detail?.context ?? {});\n            return new KeyScopeDeniedError({\n                ...base,\n                scope: context.scope ?? '',\n                required: context.required ?? '',\n                actual: context.actual ?? '',\n            });\n        }\n        case 'CONFLICT':\n            return new ConflictError({\n                ...base,\n                details: parseErrorDetails(envelope.details),\n            });\n        case 'UNPROCESSABLE_CONTENT': {\n            const details = parseErrorDetails(envelope.details);\n            return (parseSponsorError(base, details) ??\n                parseSolanaAccountAlreadyCreatedError(base, details) ??\n                new UnprocessableContentError({ ...base, details }));\n        }\n        case 'TOO_MANY_REQUESTS':\n            return new RateLimitedError({ ...base, retryAfter });\n        case 'SETTLEMENT_QUOTE_ERROR':\n            return new SettlementQuoteError(base);\n        case 'SETTLEMENT_EXECUTION_ERROR':\n            return new SettlementExecutionError(base);\n        case 'SIMULATION_FAILED':\n            return new SimulationFailedError({\n                ...base,\n                ...parseSimulationFailureDetails(envelope.details),\n            });\n        case 'EXTERNAL_SERVICE_TIMEOUT':\n            return new ExternalServiceTimeoutError(base);\n        case 'RELAYER_MARKET_UNAVAILABLE':\n            return new RelayerMarketUnavailableError(base);\n        case 'INTERNAL_ERROR':\n            return new InternalServerError(base);\n        default:\n            return new OrchestratorError({ ...base, code: 'UNKNOWN' });\n    }\n}\nfunction isOrchestratorError(error) {\n    return error instanceof OrchestratorError;\n}\nfunction isRateLimited(error) {\n    return error instanceof RateLimitedError;\n}\nfunction isValidationError(error) {\n    return error instanceof ValidationError;\n}\nfunction isSolanaAccountNotCreated(error) {\n    return error instanceof SolanaAccountNotCreatedError;\n}\nfunction isSolanaAccountAlreadyCreated(error) {\n    return error instanceof SolanaAccountAlreadyCreatedError;\n}\nfunction isAuthError(error) {\n    return error instanceof UnauthorizedError || error instanceof ForbiddenError;\n}\nfunction isSimulationFailed(error) {\n    return error instanceof SimulationFailedError;\n}\nfunction isSponsorLimitExceeded(error) {\n    return error instanceof SponsorLimitExceededError;\n}\nfunction isInsufficientSponsorBalance(error) {\n    return error instanceof InsufficientSponsorBalanceError;\n}\n/** Either sponsor failure: a configured cap breach or a balance shortfall. */\nfunction isSponsorError(error) {\n    return isSponsorLimitExceeded(error) || isInsufficientSponsorBalance(error);\n}\nfunction isRetryable(error) {\n    return (error instanceof InternalServerError ||\n        error instanceof ExternalServiceTimeoutError ||\n        error instanceof RelayerMarketUnavailableError ||\n        (error instanceof SimulationFailedError && error.retryable));\n}\n// Transport-level error codes that escape `fetch` as raw errors rather than\n// typed HTTP envelopes. Spans Node/undici and common system codes.\nconst CONNECTION_ERROR_CODES = new Set([\n    'ECONNRESET',\n    'ECONNREFUSED',\n    'ECONNABORTED',\n    'ETIMEDOUT',\n    'EPIPE',\n    'ENOTFOUND',\n    'EAI_AGAIN',\n    'EHOSTUNREACH',\n    'ENETUNREACH',\n    'UND_ERR_SOCKET',\n    'UND_ERR_CONNECT_TIMEOUT',\n    'UND_ERR_HEADERS_TIMEOUT',\n    'UND_ERR_BODY_TIMEOUT',\n]);\nconst CONNECTION_ERROR_MESSAGES = [\n    'socket connection was closed', // Bun\n    'fetch failed', // undici/Node (the coded cause is matched separately)\n    'failed to fetch', // Chrome/Edge\n    'networkerror when attempting to fetch', // Firefox\n    'network request failed',\n    'connection closed',\n    'connection reset',\n];\n/**\n * Detects transport-level failures (connection reset, socket closed, DNS, TLS)\n * that `fetch` rejects with instead of returning an HTTP response. Unlike HTTP\n * errors — which the client converts into typed {@link OrchestratorError}s —\n * these carry no status and bubble up untyped, so {@link isRetryable} misses\n * them. They are safe to retry for idempotent reads (e.g. intent-status\n * polling). We match by `code` and message across the cause chain — never by\n * error type: `fetch` rejects network failures as `TypeError`, but `TypeError`\n * is also thrown for logic bugs, bad URLs, and response-decoding errors that\n * must NOT be retried (`waitForExecution` has no SDK-side deadline). Runtimes\n * differ (Bun throws a plain `Error` with a socket message; undici/Node a\n * `TypeError` with a coded `cause`), hence both signals. Caller-initiated\n * aborts are excluded so deadlines/cancellation still propagate.\n */\nfunction isConnectionError(error) {\n    // HTTP-status errors are already typed and classified elsewhere.\n    if (isOrchestratorError(error)) {\n        return false;\n    }\n    // Caller cancellation / deadline must propagate, not retry.\n    if (error instanceof Error && error.name === 'AbortError') {\n        return false;\n    }\n    // Walk the `cause` chain; `seen` guards against cyclic causes looping forever.\n    const seen = new Set();\n    let current = error;\n    while (current != null && !seen.has(current)) {\n        seen.add(current);\n        const code = current.code;\n        if (typeof code === 'string' && CONNECTION_ERROR_CODES.has(code)) {\n            return true;\n        }\n        const message = current instanceof Error ? current.message.toLowerCase() : '';\n        if (CONNECTION_ERROR_MESSAGES.some((m) => message.includes(m))) {\n            return true;\n        }\n        current = current.cause;\n    }\n    return false;\n}\nexport { parseErrorEnvelope, isOrchestratorError, isRetryable, isConnectionError, isAuthError, isValidationError, isSolanaAccountNotCreated, isSolanaAccountAlreadyCreated, isRateLimited, isSimulationFailed, isSponsorLimitExceeded, isInsufficientSponsorBalance, isSponsorError, OrchestratorError, ValidationError, SolanaAccountNotCreatedError, SolanaAccountAlreadyCreatedError, InsufficientLiquidityError, SponsorLimitExceededError, InsufficientSponsorBalanceError, NotFoundError, UnauthorizedError, ForbiddenError, KeyScopeDeniedError, ConflictError, UnprocessableContentError, RateLimitedError, SettlementQuoteError, SettlementExecutionError, SimulationFailedError, ExternalServiceTimeoutError, RelayerMarketUnavailableError, InternalServerError, };\n","import { ValidationError } from '../../clients/orchestrator/errors.js';\nexport function normalizeIntentTypedData(typedData) {\n    const types = typedData.types;\n    return {\n        ...typedData,\n        message: normalizeTypedDataMessage(types, typedData.primaryType, typedData.message),\n    };\n}\n// Normalizes the numeric values a JSON payload carries as strings into the\n// bigints viem hashes with. The typed-data digest is unchanged by this.\nfunction normalizeSigningRequest(request) {\n    return request.payload.kind === 'eip712'\n        ? {\n            ...request,\n            payload: {\n                ...request.payload,\n                typedData: normalizeIntentTypedData(request.payload.typedData),\n            },\n        }\n        : request;\n}\n/**\n * Normalizes an execution route. An account-creation route is refused: it\n * carries no execution cost or signing requests, and reading it as one would\n * present a deployment as a spend.\n */\nexport function normalizeIntentQuote(quote) {\n    if (quote.purpose !== 'execution') {\n        throw new ValidationError({\n            message: `The orchestrator returned a ${String(quote.purpose)} route (${quote.intentId}) where an execution route was expected.`,\n        });\n    }\n    return {\n        ...quote,\n        signingRequests: quote.signingRequests.map(normalizeSigningRequest),\n    };\n}\nfunction normalizeTypedDataMessage(types, primaryType, message) {\n    const fields = types[primaryType];\n    if (!fields)\n        return message;\n    return Object.fromEntries(Object.entries(message).map(([name, value]) => {\n        const type = fields.find((field) => field.name === name)?.type;\n        return [name, type ? normalizeTypedDataValue(types, type, value) : value];\n    }));\n}\nfunction normalizeTypedDataValue(types, type, value) {\n    if (value === null || value === undefined)\n        return value;\n    const array = type.match(/^(.+)\\[\\d*\\]$/u);\n    if (array) {\n        return Array.isArray(value)\n            ? value.map((item) => normalizeTypedDataValue(types, array[1], item))\n            : value;\n    }\n    if (/^u?int\\d*$/u.test(type)) {\n        return typeof value === 'string' || typeof value === 'number'\n            ? BigInt(value)\n            : value;\n    }\n    return types[type]\n        ? normalizeTypedDataMessage(types, type, value)\n        : value;\n}\n","import { isAddress } from 'viem';\n// Token inputs are per-chain ERC-20 addresses (v2 no longer bundles a token\n// registry — chain/token data is fetched from the orchestrator at runtime).\n// Non-EVM chains pass their token identifiers through unchanged; EVM inputs\n// must be hex addresses.\nexport function normalizeTokenAddress(token, chainId, nonEvm) {\n    if (isAddress(token))\n        return token;\n    if (nonEvm)\n        return token;\n    throw new Error(`Expected a token address on EVM chain ${chainId}, got: ${token}`);\n}\n// Rejects non-address token identifiers (e.g. symbols) so they can't slip\n// through the `sourceAssets` token-list inputs the way they can't through\n// tokenRequests / per-chain `ExactInputConfig`.\nexport function validateTokenAddresses(tokens) {\n    for (const token of tokens) {\n        if (!isAddress(token, { strict: false })) {\n            throw new Error(`Invalid token address: ${token}`);\n        }\n    }\n}\n","import { formatCaip2 } from '../../chains/caip2.js';\nexport function buildIntentSource(input) {\n    const selection = buildSelection(input.policy);\n    const limits = buildLimits(input.policy);\n    const auxiliaryFunds = input.auxiliaryFunds\n        ? mapByCaip2(input.auxiliaryFunds)\n        : undefined;\n    const executions = Object.entries(input.executions ?? {}).map(([chainId, calls]) => ({\n        vm: 'evm',\n        chainId: formatCaip2(Number(chainId)),\n        calls,\n    }));\n    const source = {\n        ...(selection ? { selection } : {}),\n        ...(limits.length > 0 ? { limits } : {}),\n        ...(auxiliaryFunds ? { auxiliaryFunds } : {}),\n        ...(executions.length > 0 ? { executions } : {}),\n    };\n    return Object.keys(source).length > 0 ? source : undefined;\n}\nfunction buildSelection(policy) {\n    if (!policy)\n        return undefined;\n    const perChainTokens = mergePerChainTokens(policy);\n    const namedChains = perChainTokens && [...perChainTokens.keys()];\n    // A per-chain map is the whole chain allowlist, not a narrowing of a wider\n    // one: an unlisted chain is not eligible, exactly as `chainTokens` meant.\n    const chains = namedChains !== undefined\n        ? { only: namedChains.map(formatCaip2) }\n        : policy.chainIds\n            ? { only: policy.chainIds.map(formatCaip2) }\n            : undefined;\n    const globalTokens = policy.tokens ? [...policy.tokens] : undefined;\n    // With a per-chain map, the token dimension IS restricted — to the union of\n    // everything named — and `perChain` then narrows each chain to its own list.\n    // Sending `'all'` here and relying on `perChain` alone would leave any chain\n    // the map does not cover open to every token.\n    const tokens = namedChains\n        ? { only: [...new Set([...perChainTokens.values()].flat())] }\n        : globalTokens\n            ? { only: globalTokens }\n            : undefined;\n    if (!chains && !tokens)\n        return undefined;\n    return {\n        chains: chains ?? 'all',\n        tokens: (tokens ?? 'all'),\n        ...(perChainTokens\n            ? {\n                perChain: Object.fromEntries([...perChainTokens].map(([chainId, list]) => [\n                    formatCaip2(chainId),\n                    { tokens: { only: list } },\n                ])),\n            }\n            : {}),\n    };\n}\n/**\n * The tokens each named chain may be sourced in, unioning the unbounded\n * (`chainTokens`) and capped (`chainTokenAmounts`) entries. Returns `undefined`\n * when the policy names no per-chain restriction at all — which is not the same\n * as naming an empty one, and that distinction is what makes an explicit but\n * empty asset selection fail closed instead of widening to everything.\n */\nfunction mergePerChainTokens(policy) {\n    if (!policy.chainTokens && !policy.chainTokenAmounts)\n        return undefined;\n    const merged = new Map();\n    const add = (chainId, token) => {\n        const list = merged.get(chainId) ?? [];\n        if (!list.some((entry) => sameToken(entry, token)))\n            list.push(token);\n        merged.set(chainId, list);\n    };\n    for (const [chainId, tokens] of Object.entries(policy.chainTokens ?? {})) {\n        merged.set(Number(chainId), merged.get(Number(chainId)) ?? []);\n        for (const token of tokens)\n            add(Number(chainId), token);\n    }\n    for (const [chainId, amounts] of Object.entries(policy.chainTokenAmounts ?? {})) {\n        merged.set(Number(chainId), merged.get(Number(chainId)) ?? []);\n        for (const token of Object.keys(amounts))\n            add(Number(chainId), token);\n    }\n    return merged;\n}\nfunction buildLimits(policy) {\n    const limits = [];\n    for (const [chainId, amounts] of Object.entries(policy?.chainTokenAmounts ?? {})) {\n        for (const [tokenAddress, maxAmount] of Object.entries(amounts)) {\n            limits.push({\n                chainId: formatCaip2(Number(chainId)),\n                tokenAddress,\n                maxAmount,\n            });\n        }\n    }\n    return limits;\n}\nfunction sameToken(left, right) {\n    return left === right || left.toLowerCase() === right.toLowerCase();\n}\nfunction mapByCaip2(input) {\n    return Object.fromEntries(Object.entries(input).map(([chainId, value]) => [\n        formatCaip2(Number(chainId)),\n        value,\n    ]));\n}\n","import { chainIdFromReference, chainVm, formatCaip2 } from '../../chains/caip2.js';\nimport { normalizeTokenAddress } from '../../chains/tokens.js';\nimport { toNormalizedAccount, toNormalizedRecipient, toWireEvmAccount, toWireRecipient, } from './account.js';\nimport { buildIntentSource } from './source.js';\nexport function buildIntentRequest(input) {\n    const { transaction } = input;\n    const destinationChainId = chainIdFromReference(transaction.destination);\n    const vm = chainVm(transaction.destination);\n    const nonEvm = transaction.destination.kind === 'non-evm';\n    const executions = input.calls.map(toExecution);\n    const sourceExecutions = Object.fromEntries(Object.entries(input.sourceCalls).map(([chainId, calls]) => [\n        Number(chainId),\n        calls.map(toExecution),\n    ]));\n    const auxiliaryFunds = mergeAuxiliaryFunds(transaction.options?.auxiliaryFunds, input.providedFunds);\n    const tokenRequests = transaction.tokenRequests.map((request) => ({\n        tokenAddress: normalizeTokenAddress(request.token, destinationChainId, nonEvm),\n        ...(request.amount === undefined ? {} : { amount: request.amount }),\n    }));\n    const signatureMode = transaction.signatureMode ?? 1;\n    const sponsorship = toSponsorship(transaction.options?.sponsorSettings);\n    const options = {\n        ...(transaction.options?.appFees\n            ? { appFees: transaction.options.appFees }\n            : {}),\n        ...(transaction.options?.protocolFees\n            ? { protocolFees: transaction.options.protocolFees }\n            : {}),\n        ...(transaction.options?.customDeadline === undefined\n            ? {}\n            : { customDeadline: transaction.options.customDeadline }),\n        ...(sponsorship ? { sponsorship } : {}),\n        ...(transaction.options?.settlementLayers\n            ? { settlementLayers: transaction.options.settlementLayers }\n            : {}),\n        ...(transaction.options?.quoters\n            ? { quoters: transaction.options.quoters }\n            : {}),\n    };\n    return {\n        request: {\n            account: {\n                evm: toWireEvmAccount(input.account, {\n                    signatureMode,\n                    ...(input.mockSignatures\n                        ? {\n                            mockSignaturesByChain: mapMockSignatures(input.mockSignatures),\n                        }\n                        : {}),\n                }),\n            },\n            destination: buildDestination({\n                vm,\n                chainId: formatCaip2(destinationChainId),\n                transaction,\n                tokenRequests,\n                executions,\n            }),\n            ...(() => {\n                const source = buildIntentSource({\n                    ...(transaction.accountAccessList\n                        ? { policy: transaction.accountAccessList }\n                        : {}),\n                    ...(auxiliaryFunds ? { auxiliaryFunds } : {}),\n                    ...(Object.keys(sourceExecutions).length > 0\n                        ? { executions: sourceExecutions }\n                        : {}),\n                });\n                return source ? { source } : {};\n            })(),\n            ...(Object.keys(options).length > 0 ? { options } : {}),\n        },\n        normalized: {\n            account: toNormalizedAccount(input.account, {\n                ...(input.mockSignatures\n                    ? { mockSignatures: input.mockSignatures }\n                    : {}),\n            }),\n            destinationChainId,\n            destinationExecutions: executions,\n            tokenRequests,\n            ...(transaction.recipient\n                ? {\n                    recipient: toNormalizedRecipient(transaction.recipient, {\n                        evmAddressed: vm === 'evm' || vm === 'hypercore',\n                    }),\n                }\n                : {}),\n            ...(transaction.gasLimit === undefined\n                ? {}\n                : { destinationGasUnits: transaction.gasLimit }),\n            ...(transaction.accountAccessList\n                ? { accountAccessList: transaction.accountAccessList }\n                : {}),\n            options: {\n                ...transaction.options,\n                signatureMode,\n                ...(auxiliaryFunds ? { auxiliaryFunds } : {}),\n            },\n            ...(Object.keys(sourceExecutions).length > 0\n                ? { preClaimExecutions: sourceExecutions }\n                : {}),\n        },\n    };\n}\nfunction buildDestination(input) {\n    const { transaction, chainId, tokenRequests } = input;\n    const recipient = transaction.recipient\n        ? toWireRecipient(transaction.recipient)\n        : undefined;\n    switch (input.vm) {\n        case 'evm': {\n            const execution = evmExecution(input.executions, transaction.gasLimit);\n            return {\n                vm: 'evm',\n                chainId,\n                ...(recipient ? { recipient } : {}),\n                tokenRequests,\n                ...(execution ? { execution } : {}),\n            };\n        }\n        case 'svm': {\n            // An EVM-origin intent delivers tokens to Solana; instructions are a\n            // Solana-origin capability and travel their own path.\n            return {\n                vm: 'svm',\n                chainId,\n                ...(recipient ? { recipient: { address: recipient.address } } : {}),\n                tokenRequests,\n            };\n        }\n        case 'tvm':\n        case 'stellar': {\n            if (!recipient) {\n                throw new Error(`An intent to ${chainId} requires an explicit recipient: the account holds no ${input.vm} identity`);\n            }\n            return {\n                vm: input.vm,\n                chainId,\n                recipient: { address: recipient.address },\n                tokenRequests,\n            };\n        }\n        case 'hypercore': {\n            const action = transaction.options?.hyperCore?.action;\n            // The actions run on HyperCore; the caller's calls are the HyperEVM\n            // transaction that settles them, which is a different chain and a\n            // different execution block.\n            const settlement = evmExecution(input.executions, transaction.gasLimit);\n            const execution = action || settlement\n                ? {\n                    ...(action ? { actions: [action] } : {}),\n                    ...(settlement ? { settlement } : {}),\n                }\n                : undefined;\n            return {\n                vm: 'hypercore',\n                chainId,\n                ...(recipient ? { recipient } : {}),\n                tokenRequests,\n                ...(execution ? { execution } : {}),\n            };\n        }\n    }\n}\nfunction evmExecution(calls, gasLimit) {\n    // Omitted rather than sent empty: an execution block with no calls is not the\n    // same request as a plain delivery.\n    if (calls.length === 0 && gasLimit === undefined)\n        return undefined;\n    return {\n        calls,\n        ...(gasLimit === undefined ? {} : { gasLimit }),\n    };\n}\nfunction toSponsorship(settings) {\n    // Caucasus renamed the block but kept the categories, including the\n    // difference between an explicit `false` and an omitted key.\n    return settings ? { ...settings } : undefined;\n}\nfunction mapMockSignatures(input) {\n    return Object.fromEntries(Object.entries(input).map(([chainId, signature]) => [\n        formatCaip2(Number(chainId)),\n        signature,\n    ]));\n}\nexport function toExecution(call) {\n    return { to: call.target, value: call.value, data: call.data };\n}\nfunction mergeAuxiliaryFunds(configured, provided) {\n    const result = {};\n    for (const [chainId, balances] of Object.entries(configured ?? {})) {\n        result[Number(chainId)] = { ...balances };\n    }\n    for (const [chainId, balances] of Object.entries(provided)) {\n        const target = (result[Number(chainId)] ??= {});\n        for (const [token, amount] of Object.entries(balances)) {\n            target[token] = (target[token] ?? 0n) + amount;\n        }\n    }\n    return Object.keys(result).length > 0 ? result : undefined;\n}\n","import { base64 } from '@scure/base';\nimport { solanaAddress } from '../../chains/non-evm.js';\nimport { InvalidSolanaTransactionArtifactError } from '../../errors/execution.js';\n// Mirrors the limits the orchestrator publishes on the quote request, so an\n// oversized instruction set fails before a round trip.\nconst MAX_INSTRUCTIONS = 32;\nconst MAX_ACCOUNTS_PER_INSTRUCTION = 64;\nconst MAX_INSTRUCTION_DATA_BYTES = 1232;\nconst MAX_ADDRESS_LOOKUP_TABLES = 8;\nconst BASE64 = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;\nconst ACCEPTED_SHAPES = 'an instruction must be either `{ programId, accounts, data }` with base58 addresses and base64 data, or a `@solana/web3.js` instruction with `programId`, `keys` and `data`';\nfunction fail(message) {\n    throw new InvalidSolanaTransactionArtifactError(message);\n}\nfunction base58(value, label) {\n    if (typeof value === 'object' && value !== null) {\n        const encode = value.toBase58;\n        if (typeof encode === 'function') {\n            return base58(encode.call(value), label);\n        }\n    }\n    if (typeof value !== 'string')\n        fail(`${label} must be a base58 address`);\n    try {\n        return solanaAddress(value);\n    }\n    catch {\n        return fail(`${label} must be a base58 address`);\n    }\n}\nfunction accountMeta(value, label) {\n    if (!value || typeof value !== 'object' || Array.isArray(value)) {\n        fail(`${label} must be an object`);\n    }\n    const entry = value;\n    if (typeof entry.isSigner !== 'boolean' ||\n        typeof entry.isWritable !== 'boolean') {\n        fail(`${label}.isSigner and ${label}.isWritable must be booleans`);\n    }\n    return Object.freeze({\n        pubkey: base58(entry.pubkey, `${label}.pubkey`),\n        isSigner: entry.isSigner,\n        isWritable: entry.isWritable,\n    });\n}\nfunction instructionData(value, label) {\n    if (value instanceof Uint8Array)\n        return base64.encode(value);\n    if (typeof value !== 'string' || !BASE64.test(value)) {\n        fail(`${label} must be base64-encoded instruction data`);\n    }\n    return value;\n}\nfunction dataByteLength(value) {\n    if (value.length === 0)\n        return 0;\n    const padding = value.endsWith('==') ? 2 : value.endsWith('=') ? 1 : 0;\n    return (value.length / 4) * 3 - padding;\n}\nfunction instruction(value, label) {\n    if (!value || typeof value !== 'object' || Array.isArray(value)) {\n        fail(`${label} must be an object; ${ACCEPTED_SHAPES}`);\n    }\n    const entry = value;\n    const accounts = 'keys' in entry ? entry.keys : entry.accounts;\n    if (!Array.isArray(accounts)) {\n        fail(`${label} is not a recognized Solana instruction; ${ACCEPTED_SHAPES}`);\n    }\n    if (accounts.length > MAX_ACCOUNTS_PER_INSTRUCTION) {\n        fail(`${label} references more than ${MAX_ACCOUNTS_PER_INSTRUCTION} accounts`);\n    }\n    return Object.freeze({\n        programId: base58(entry.programId, `${label}.programId`),\n        accounts: Object.freeze(accounts.map((account, index) => accountMeta(account, `${label}.accounts[${index}]`))),\n        data: instructionData(entry.data, `${label}.data`),\n    });\n}\n/**\n * Normalizes caller-supplied instructions to the orchestrator's wire shape.\n * The result is JSON-round-trippable, so a prepared transaction can be\n * persisted and restored without a Solana runtime.\n */\nexport function normalizeSolanaInstructions(input) {\n    if (!Array.isArray(input) || input.length === 0) {\n        fail('a Solana instruction execution requires at least one instruction');\n    }\n    if (input.length > MAX_INSTRUCTIONS) {\n        fail(`a Solana intent carries at most ${MAX_INSTRUCTIONS} instructions`);\n    }\n    const instructions = input.map((entry, index) => instruction(entry, `instructions[${index}]`));\n    const bytes = instructions.reduce((total, entry) => total + dataByteLength(entry.data), 0);\n    if (bytes > MAX_INSTRUCTION_DATA_BYTES) {\n        fail(`Solana instruction data must total at most ${MAX_INSTRUCTION_DATA_BYTES} bytes`);\n    }\n    return Object.freeze(instructions);\n}\n/**\n * Normalizes the address lookup tables the instructions resolve accounts\n * through. Returns `undefined` when there are none, so the wire field is\n * omitted rather than sent empty.\n */\nexport function normalizeSolanaAddressLookupTables(input) {\n    if (input === undefined)\n        return undefined;\n    if (!Array.isArray(input)) {\n        fail('addressLookupTables must be an array of base58 addresses');\n    }\n    if (input.length === 0)\n        return undefined;\n    if (input.length > MAX_ADDRESS_LOOKUP_TABLES) {\n        fail(`a Solana intent carries at most ${MAX_ADDRESS_LOOKUP_TABLES} address lookup tables`);\n    }\n    return Object.freeze(input.map((table, index) => base58(table, `addressLookupTables[${index}]`)));\n}\n","import { bytesToHex, hexToBytes, isAddress, isAddressEqual } from 'viem';\nimport { publicKeyToAddress } from 'viem/utils';\nimport { asSwigNamespace, locateSwig, locateSwigById, locateSwigWallet, MANAGED_SWIG_NAMESPACES, } from '../accounts/solana/address.js';\nimport { formatCaip2, parseCaip2, toEvmChainReference } from '../chains/caip2.js';\nimport { getChainById, getChainReference } from '../chains/catalog.js';\nimport { solanaAddress, } from '../chains/non-evm.js';\nimport { normalizeTokenAddress, validateTokenAddresses } from '../chains/tokens.js';\nimport { isSolanaAccountAlreadyCreated } from '../clients/orchestrator/errors.js';\nimport { projectCompatibleIntentInput } from '../clients/orchestrator/normalized.js';\nimport { createStaticAccountRuntime } from '../config/account-runtime.js';\nimport { materializeAccountInvocationContext, resolveAccountConfig, } from '../config/resolve.js';\nimport { AccountVmNotConfiguredError, ManagedSolanaAccountNotSupportedError, UnsupportedAccountCapabilityError, } from '../errors/capability.js';\nimport { IndependentSigningNotSupportedError, InvalidSolanaTransactionArtifactError, MismatchedOwnerSignaturesError, QuoteNotInPreparedTransactionError, } from '../errors/execution.js';\nimport { resolveHyperCoreAction } from '../hypercore/resolve.js';\nimport { ecdsaSignerId, webauthnSignerId, } from '../modules/validators/signer-id.js';\nimport { asIntentRecipient, projectIntentAccount, projectIntentRecipient, } from '../transactions/intents/account.js';\nimport { assertPreparedBinding, projectCompatibleQuote, projectPreparedBinding, restorePreparedBinding, } from '../transactions/intents/compatibility.js';\nimport { normalizeIntentQuote } from '../transactions/intents/normalize.js';\nimport { assertSupportedSigningRequests } from '../transactions/intents/prepare.js';\nimport { compressP256PublicKey, NATIVE_SOL_SENTINEL, solanaChainId, } from '../transactions/intents/solana.js';\nimport { normalizeSolanaAddressLookupTables, normalizeSolanaInstructions, } from '../transactions/intents/solana-instructions.js';\nimport { toPublicTransactionStatus } from './project-mappers.js';\nimport { adaptSignerSelection, adaptUserOperationSignerSelection, } from './signer-selection.js';\nfunction cloneArtifactValue(value) {\n    if (Array.isArray(value)) {\n        return value.map(cloneArtifactValue);\n    }\n    if (value && typeof value === 'object') {\n        return Object.fromEntries(Object.entries(value).map(([key, item]) => [\n            key,\n            cloneArtifactValue(item),\n        ]));\n    }\n    return value;\n}\nfunction toPublicQuote(quote) {\n    const compatible = projectCompatibleQuote(quote);\n    return cloneArtifactValue({\n        intentId: compatible.intentId,\n        purpose: compatible.purpose,\n        expiresAt: compatible.expiresAt,\n        estimatedFillTime: compatible.estimatedFillTime,\n        settlementLayer: compatible.settlementLayer,\n        plan: compatible.plan,\n        cost: compatible.cost,\n        requirements: [...compatible.requirements],\n        signingRequests: [...compatible.signingRequests],\n        ...(compatible.bridgeFill ? { bridgeFill: compatible.bridgeFill } : {}),\n    });\n}\nfunction toPreparedTransactionData(prepared, transaction, cache) {\n    const data = {\n        quotes: {\n            traceId: prepared.traceId,\n            best: toPublicQuote(prepared.quote),\n            all: prepared.quotes.map(toPublicQuote),\n        },\n        intentInput: projectCompatibleIntentInput(prepared.normalized),\n        request: projectPreparedBinding(prepared.request),\n        transaction,\n    };\n    cache.set(data, prepared);\n    return data;\n}\nfunction solanaMetadata(input) {\n    const binding = {\n        namespace: input.namespace,\n        endpoint: input.endpoint,\n        chain: solanaChainId(input.chain),\n        caip2: input.chain.caip2,\n        accountAddress: input.accountAddress,\n        // Omitted, not undefined: persisted JSON drops the key, and the binding\n        // check compares key counts.\n        ...(input.accountType ? { accountType: input.accountType } : {}),\n        authority: input.authority.kind === 'secp256k1'\n            ? input.authority.address\n            : input.authority.publicKey,\n        swigAddress: input.swigAddress,\n        walletAddress: input.walletAddress,\n    };\n    const action = input.action;\n    if (action.kind === 'instructions') {\n        return { kind: 'solana-instructions', ...binding };\n    }\n    const delivery = action.delivery;\n    return delivery.kind === 'cross-chain'\n        ? {\n            kind: 'solana-cross-chain',\n            ...binding,\n            mint: action.mint,\n            destinationChain: delivery.chainId,\n            destinationToken: delivery.token,\n            recipient: delivery.recipient,\n        }\n        : {\n            kind: 'solana',\n            ...binding,\n            mint: action.mint,\n            recipient: delivery.recipient,\n        };\n}\nfunction toPreparedSolanaTransactionData(prepared, transaction) {\n    return {\n        quotes: {\n            traceId: prepared.traceId,\n            best: toPublicQuote(prepared.quote),\n            all: prepared.quotes.map(toPublicQuote),\n        },\n        execution: solanaMetadata(prepared.input),\n        intentInput: projectCompatibleIntentInput(prepared.normalized),\n        request: projectPreparedBinding(prepared.request),\n        transaction,\n    };\n}\nfunction selectedPublicQuote(prepared, intentId) {\n    if (!intentId)\n        return prepared.quotes.best;\n    const quote = prepared.quotes.all.find((candidate) => candidate.intentId === intentId);\n    if (!quote) {\n        throw new QuoteNotInPreparedTransactionError({ context: { intentId } });\n    }\n    return quote;\n}\nfunction reconstructInput(context, prepared, intentId) {\n    const selected = selectedPublicQuote(prepared, intentId);\n    const quote = normalizeIntentQuote(selected);\n    return {\n        traceId: prepared.quotes.traceId,\n        normalized: prepared.intentInput,\n        quote,\n        quotes: prepared.quotes.all.map((candidate) => candidate.intentId === quote.intentId\n            ? quote\n            : normalizeIntentQuote(candidate)),\n        // The persisted Caucasus request, not a reconstruction from `intentInput`:\n        // that projection is lossy about account capability and signing state, and\n        // an artifact from an earlier wire version is refused here rather than\n        // silently reinterpreted.\n        request: restorePreparedBinding(prepared.request),\n        intentInput: adaptTransaction(context, prepared.transaction),\n    };\n}\nfunction toSignedTransactionData(prepared, signed, cache) {\n    const data = {\n        ...prepared,\n        quote: toPublicQuote(signed.prepared.quote),\n        proofs: [...signed.proofs],\n    };\n    cache.set(data, signed);\n    return data;\n}\nfunction referenceChain() {\n    // Account addresses are CREATE2 and chain-independent, so initialization only\n    // needs some EVM chain reference. With no bundled chain set, use mainnet.\n    return toEvmChainReference(1);\n}\nexport function createAccountFacade(compatibilityConfig, publicConfig, composition) {\n    // Intent identity caches are facade-scoped. Values crossing account/SDK\n    // instances are reconstructed and validated by the receiving account.\n    const preparedIntents = new WeakMap();\n    const signedIntents = new WeakMap();\n    const context = (method) => materializeAccountInvocationContext(composition.config, compatibilityConfig, method);\n    const workflowsFor = (ctx) => composition.createAccount(ctx).workflows;\n    const solana = (() => {\n        const branch = publicConfig.solana;\n        if (!branch || !('owner' in branch) || !branch.owner)\n            return undefined;\n        const ctx = context('get-address');\n        const identity = workflowsFor(ctx).getAddress(ctx, referenceChain());\n        const kind = ctx.account.account.kind;\n        return createSolanaOrigin({\n            owner: branch.owner,\n            walletAddress: locateSwigWallet(branch.swig).address,\n            swigAddress: branch.swig,\n            environment: ctx.sdk.environment,\n            endpoint: ctx.sdk.orchestratorUrl,\n            evmRecipient: identity,\n            evmExecution: {\n                address: identity,\n                accountType: kind === 'eoa' ? 'EOA' : kind === 'hca' ? 'GENERIC' : 'ERC7579',\n            },\n        }, publicConfig);\n    })();\n    const requireSolana = () => {\n        if (!solana) {\n            throw new UnsupportedAccountCapabilityError('A managed Solana source is not configured on this account.', { vm: 'solana' });\n        }\n        return solana;\n    };\n    const resolvePrepared = (ctx, prepared, intentId) => {\n        assertSupportedTransaction(prepared.transaction, publicConfig);\n        assertPreparedBinding(prepared.request);\n        if (!isSolanaOrigin(prepared.transaction)) {\n            // Before any account state is read: a quote this SDK cannot sign should\n            // not cost an RPC round trip first.\n            assertSupportedSigningRequests(selectedPublicQuote(prepared, intentId).signingRequests);\n        }\n        const cached = preparedIntents.get(prepared);\n        if (cached && !intentId)\n            return Promise.resolve(cached);\n        return workflowsFor(ctx).reconstructPreparedIntent(ctx, reconstructInput(ctx, prepared, intentId));\n    };\n    const account = {\n        config: publicConfig,\n        deploy: (async (vm, chain, params) => {\n            if (vm === 'solana') {\n                const solana = requireSolana();\n                const ctx = context('deploy');\n                const workflows = workflowsFor(ctx);\n                return solana.deploy(ctx.sdk, workflows, (intentId) => workflows.waitForIntentStatus(ctx, intentId), chain, params);\n            }\n            if (vm !== 'evm')\n                throw new AccountVmNotConfiguredError(String(vm));\n            if (chain.kind === 'svm') {\n                throw new UnsupportedAccountCapabilityError(\"An EVM deployment needs an EVM chain; create a Swig with `deploy('solana', chain)`.\", { vm: 'evm' });\n            }\n            const ctx = context('deploy');\n            const sponsored = params\n                ?.sponsored;\n            return workflowsFor(ctx).deploy(ctx, toEvmChainReference(chain.id), { ...(sponsored !== undefined ? { sponsored } : {}) });\n        }),\n        isDeployed(chain) {\n            const ctx = context('is-deployed');\n            return workflowsFor(ctx).isDeployed(ctx, toEvmChainReference(chain.id));\n        },\n        setup(chain) {\n            const ctx = context('setup');\n            return workflowsFor(ctx).setup(ctx, toEvmChainReference(chain.id));\n        },\n        getInitData() {\n            const ctx = context('get-init-data');\n            return workflowsFor(ctx).getInitData(ctx);\n        },\n        async signEip7702InitData() {\n            const ctx = context('sign-eip7702-init-data');\n            const result = await workflowsFor(ctx).signEip7702InitData(ctx);\n            return result.signature;\n        },\n        async prepareTransaction(transaction) {\n            const ctx = context('prepare-intent');\n            const initiallyNormalized = normalizeTransaction(transaction, publicConfig);\n            const normalized = 'targetChain' in initiallyNormalized &&\n                initiallyNormalized.targetChain !== undefined &&\n                'kind' in initiallyNormalized.targetChain &&\n                initiallyNormalized.targetChain.kind === 'svm' &&\n                initiallyNormalized.recipient === undefined &&\n                solana\n                ? Object.freeze({\n                    ...initiallyNormalized,\n                    recipient: solana.walletAddress,\n                })\n                : initiallyNormalized;\n            if (isSolanaOrigin(normalized)) {\n                const origin = requireSolana();\n                const workflows = workflowsFor(ctx);\n                let execution;\n                if (isCrossChainSolanaOrigin(normalized) && normalized.calls?.length) {\n                    origin.assertDestinationCallsSupported();\n                    const chainId = normalized.targetChain.id;\n                    const resolved = await workflows.resolveSolanaEvmDestination(ctx, {\n                        chain: toEvmChainReference(chainId),\n                        calls: normalized.calls.map((call) => adaptCall(call, chainId)),\n                        ...(normalized.eip7702InitSignature\n                            ? { eip7702InitSignature: normalized.eip7702InitSignature }\n                            : {}),\n                    });\n                    // Lazy calls can resolve to none, which leaves a plain delivery.\n                    execution =\n                        resolved.calls.length > 0\n                            ? {\n                                ...resolved,\n                                ...(normalized.gasLimit === undefined\n                                    ? {}\n                                    : { gasLimit: normalized.gasLimit }),\n                            }\n                            : undefined;\n                }\n                return origin.prepare(ctx.sdk, workflows, normalized, execution);\n            }\n            // Before the quote, not after: the quote's signing requests register an agent\n            // derived from the action's bytes, so the action has to be concrete here.\n            const hyperCoreAction = await resolveHyperCoreAction({\n                options: normalized.hyperCore,\n                account: workflowsFor(ctx).getAddress(ctx, referenceChain()),\n                ...(ctx.sdk.hyperliquid ? { hyperliquid: ctx.sdk.hyperliquid } : {}),\n            });\n            const automaticSources = 'targetChain' in normalized &&\n                normalized.targetChain !== undefined &&\n                normalized.sourceChains === undefined\n                ? await workflowsFor(ctx).getEligibleEvmSourceChains(destinationChainReference(normalized.targetChain))\n                : undefined;\n            if (automaticSources && automaticSources.length === 0) {\n                throw new UnsupportedAccountCapabilityError('No managed EVM source chains are eligible for this destination.');\n            }\n            const prepared = await workflowsFor(ctx).prepareIntent(ctx, adaptTransaction(ctx, normalized, hyperCoreAction, automaticSources?.map(({ id }) => id)));\n            return toPreparedTransactionData(prepared, normalized, preparedIntents);\n        },\n        getTransactionMessages(preparedTransaction, options) {\n            assertSupportedTransaction(preparedTransaction.transaction, publicConfig);\n            assertPreparedBinding(preparedTransaction.request);\n            const quote = selectedPublicQuote(preparedTransaction, options?.intentId);\n            if (isSolanaOrigin(preparedTransaction.transaction)) {\n                const ctx = context('get-intent-messages');\n                requireSolana().resolve(ctx.sdk, workflowsFor(ctx), preparedTransaction, options?.intentId);\n            }\n            return [...quote.signingRequests];\n        },\n        signTransaction: (async (preparedTransaction, options) => {\n            const ctx = context('sign-intent');\n            const workflows = workflowsFor(ctx);\n            if (isSolanaOrigin(preparedTransaction.transaction)) {\n                return requireSolana().sign(ctx.sdk, workflows, preparedTransaction, options, async (signingRequests, chainId) => (await workflows.signIntentFromRequests(ctx, {\n                    signingRequests,\n                    targetChain: toEvmChainReference(chainId),\n                })).proofs);\n            }\n            if (options && 'owner' in options) {\n                // Independent owner signing is unsupported for smart-session intents;\n                // reject before resolving sessions (which would issue an RPC read),\n                // matching the legacy fast-fail.\n                if (preparedTransaction.transaction.signers?.type === 'session') {\n                    throw new IndependentSigningNotSupportedError();\n                }\n                const signerId = signerIdForOwner(options.owner);\n                const internal = await resolvePrepared(ctx, preparedTransaction, options.intentId);\n                return workflows.signIntentAsOwner(ctx, internal, {\n                    signerId,\n                    ...(options.validatorId === undefined\n                        ? {}\n                        : { validatorId: options.validatorId }),\n                });\n            }\n            const internal = await resolvePrepared(ctx, preparedTransaction, options?.intentId);\n            const { intent } = await workflows.signIntent(ctx, internal);\n            return toSignedTransactionData(preparedTransaction, intent, signedIntents);\n        }),\n        async assembleTransaction(preparedTransaction, signatures, options) {\n            if (isSolanaOrigin(preparedTransaction.transaction)) {\n                refuseSolanaAssembly();\n            }\n            const ctx = context('assemble-intent');\n            const workflows = workflowsFor(ctx);\n            const intentIds = [...new Set(signatures.map(({ intentId }) => intentId))];\n            if (intentIds.length > 1) {\n                throw new MismatchedOwnerSignaturesError({ context: { intentIds } });\n            }\n            const internal = await resolvePrepared(ctx, preparedTransaction, intentIds[0]);\n            const signed = await workflows.assembleIntent(ctx, internal, signatures, options?.proofs ? { proofs: options.proofs } : undefined);\n            return toSignedTransactionData(preparedTransaction, signed, signedIntents);\n        },\n        async signAuthorizations(preparedTransaction, options) {\n            assertSupportedTransaction(preparedTransaction.transaction, publicConfig);\n            if (isSolanaOrigin(preparedTransaction.transaction)) {\n                throw new UnsupportedAccountCapabilityError('EIP-7702 authorizations are unavailable for Solana-origin transactions.', { vm: 'solana' });\n            }\n            const ctx = context('sign-authorizations');\n            const internal = await resolvePrepared(ctx, preparedTransaction, options?.intentId);\n            return workflowsFor(ctx).signRequestedDelegations(ctx, internal);\n        },\n        async signMessage(message, chain, signers) {\n            const ctx = context('sign-message');\n            const result = await workflowsFor(ctx).signMessage(ctx, {\n                message,\n                chain: toEvmChainReference(chain.id),\n                ...(signers\n                    ? { signers: adaptSignerSelection(ctx.account, signers) }\n                    : {}),\n            });\n            return result.signature;\n        },\n        async signTypedData(parameters, chain, signers) {\n            const ctx = context('sign-typed-data');\n            const result = await workflowsFor(ctx).signTypedData(ctx, {\n                typedData: parameters,\n                chain: toEvmChainReference(chain.id),\n                ...(signers\n                    ? { signers: adaptSignerSelection(ctx.account, signers) }\n                    : {}),\n            });\n            return result.signature;\n        },\n        async signIntent(signingRequests, targetChain, signers) {\n            const ctx = context('sign-intent');\n            const result = await workflowsFor(ctx).signIntentFromRequests(ctx, {\n                signingRequests,\n                targetChain: destinationChainReference(targetChain),\n                ...(signers\n                    ? { signers: adaptSignerSelection(ctx.account, signers) }\n                    : {}),\n            });\n            return { proofs: [...result.proofs] };\n        },\n        async submitTransaction(signedTransaction, options) {\n            assertSupportedTransaction(signedTransaction.transaction, publicConfig);\n            const ctx = context('submit-intent');\n            const workflows = workflowsFor(ctx);\n            if (isSolanaOrigin(signedTransaction.transaction)) {\n                return requireSolana().submit(ctx.sdk, workflows, signedTransaction, options);\n            }\n            // Fast path for the same-instance signed object; otherwise (cross-instance\n            // replay or caller-tampered proofs) rebuild from the public shape.\n            const cached = signedIntents.get(signedTransaction);\n            const base = cached ?? {\n                prepared: await resolvePrepared(ctx, signedTransaction, signedTransaction.quote.intentId),\n                proofs: signedTransaction.proofs,\n                transcript: { planKind: 'intent-full', payloadId: '0x', stages: [] },\n            };\n            const signed = {\n                ...base,\n                ...(options?.internal_dryRun ? { dryRun: true } : {}),\n            };\n            const submitted = await workflows.submitIntent(ctx, signed);\n            return {\n                type: 'intent',\n                id: submitted.intentId,\n                traceId: submitted.traceId,\n                ...(submitted.sourceChains\n                    ? { sourceChains: [...submitted.sourceChains] }\n                    : {}),\n                targetChain: submitted.targetChain,\n            };\n        },\n        async prepareUserOperation(transaction) {\n            const ctx = context('prepare-user-operation');\n            const signers = userOperationSignerSelection(ctx, transaction);\n            const prepared = await workflowsFor(ctx).prepareUserOperation(ctx, {\n                chain: toEvmChainReference(transaction.chain.id),\n                calls: transaction.calls.map((call) => adaptCall(call, transaction.chain.id)),\n                ...(transaction.gasLimit === undefined\n                    ? {}\n                    : { gasLimit: transaction.gasLimit }),\n                ...(signers ? { signers } : {}),\n            });\n            const data = {\n                userOperation: prepared.operation,\n                hash: prepared.hash,\n                transaction,\n            };\n            return data;\n        },\n        async signUserOperation(preparedUserOperation) {\n            const ctx = context('sign-user-operation');\n            const signers = userOperationSignerSelection(ctx, preparedUserOperation.transaction);\n            // Recompute from the current public operation and live owners.\n            const internal = await workflowsFor(ctx).reconstructPreparedUserOperation(ctx, {\n                chain: toEvmChainReference(preparedUserOperation.transaction.chain.id),\n                operation: preparedUserOperation.userOperation,\n                ...(signers ? { signers } : {}),\n            });\n            const signed = await workflowsFor(ctx).signUserOperation(ctx, internal);\n            const data = {\n                ...preparedUserOperation,\n                signature: signed.signature,\n            };\n            return data;\n        },\n        async submitUserOperation(signedUserOperation) {\n            const ctx = context('submit-user-operation');\n            const signers = userOperationSignerSelection(ctx, signedUserOperation.transaction);\n            // The public operation and top-level signature remain authoritative.\n            const internal = await workflowsFor(ctx).reconstructSignedUserOperation(ctx, {\n                chain: toEvmChainReference(signedUserOperation.transaction.chain.id),\n                operation: signedUserOperation.userOperation,\n                signature: signedUserOperation.signature,\n                ...(signers ? { signers } : {}),\n            });\n            const submitted = await workflowsFor(ctx).submitUserOperation(ctx, internal);\n            return {\n                type: 'userop',\n                hash: submitted.hash,\n                chain: submitted.chain.id,\n            };\n        },\n        async sendUserOperation(transaction) {\n            const ctx = context('send-user-operation');\n            const signers = userOperationSignerSelection(ctx, transaction);\n            const submitted = await workflowsFor(ctx).sendUserOperation(ctx, {\n                chain: toEvmChainReference(transaction.chain.id),\n                calls: transaction.calls.map((call) => adaptCall(call, transaction.chain.id)),\n                ...(transaction.gasLimit === undefined\n                    ? {}\n                    : { gasLimit: transaction.gasLimit }),\n                ...(signers ? { signers } : {}),\n            });\n            return {\n                type: 'userop',\n                hash: submitted.hash,\n                chain: submitted.chain.id,\n            };\n        },\n        waitForExecution: ((result) => {\n            if (result.type === 'intent') {\n                const ctx = context('wait-for-execution');\n                return workflowsFor(ctx)\n                    .waitForIntentStatus(ctx, result.id)\n                    .then(toPublicTransactionStatus);\n            }\n            const ctx = context('wait-for-execution');\n            return workflowsFor(ctx)\n                .waitForUserOperationStatus(ctx, {\n                type: 'userop',\n                chain: toEvmChainReference(result.chain),\n                hash: result.hash,\n            })\n                .then((status) => status.receipt);\n        }),\n        getAddress: ((vm) => {\n            if (vm === 'solana') {\n                if (publicConfig.solana &&\n                    'address' in publicConfig.solana &&\n                    publicConfig.solana.address) {\n                    return publicConfig.solana.address;\n                }\n                if (solana)\n                    return solana.walletAddress;\n                throw new AccountVmNotConfiguredError('solana');\n            }\n            if (vm !== 'evm' || !publicConfig.evm) {\n                throw new AccountVmNotConfiguredError(String(vm));\n            }\n            const ctx = context('get-address');\n            return workflowsFor(ctx).getAddress(ctx, referenceChain());\n        }),\n        getPortfolio(onTestnets = false) {\n            const ctx = context('get-portfolio');\n            return workflowsFor(ctx)\n                .getPortfolio(ctx, onTestnets)\n                .then((portfolio) => portfolio.tokens);\n        },\n        getSessionDetails(sessions) {\n            const ctx = context('get-session-details');\n            return workflowsFor(ctx).getSessionDetails(ctx, sessions);\n        },\n        isSessionEnabled(session) {\n            const ctx = context('is-session-enabled');\n            return workflowsFor(ctx).isSessionEnabled(ctx, session);\n        },\n        signEnableSession(details) {\n            const ctx = context('sign-enable-session');\n            return workflowsFor(ctx).signEnableSession(ctx, details);\n        },\n        getOwners(chain) {\n            const ctx = context('get-owners');\n            return workflowsFor(ctx)\n                .getOwners(ctx, toEvmChainReference(chain.id))\n                .then((owners) => owners\n                ? { accounts: [...owners.accounts], threshold: owners.threshold }\n                : null);\n        },\n        getValidators(chain) {\n            const ctx = context('get-validators');\n            return workflowsFor(ctx)\n                .getValidators(ctx, toEvmChainReference(chain.id))\n                .then((addresses) => [...addresses]);\n        },\n        getExecutors(chain) {\n            const ctx = context('get-executors');\n            return workflowsFor(ctx)\n                .getExecutors(ctx, toEvmChainReference(chain.id))\n                .then((addresses) => [...addresses]);\n        },\n    };\n    return account;\n}\n/**\n * The orchestrator each environment serves managed Solana from. Any other\n * environment/endpoint pair has no matching Swig namespace behind it.\n */\nconst MANAGED_SOLANA_ENDPOINTS = {\n    development: 'https://dev.v1.orchestrator.rhinestone.dev',\n    production: 'https://v1.orchestrator.rhinestone.dev',\n};\nexport function isManagedSolanaEndpoint(environment, orchestratorUrl) {\n    return (Object.hasOwn(MANAGED_SOLANA_ENDPOINTS, environment) &&\n        orchestratorUrl.replace(/\\/+$/u, '') ===\n            MANAGED_SOLANA_ENDPOINTS[environment]);\n}\nfunction refuseSolanaAssembly() {\n    throw new IndependentSigningNotSupportedError({ context: { vm: 'solana' } });\n}\nfunction assertSolanaMetadata(actual, expected) {\n    const expectedEntries = Object.entries(solanaMetadata(expected));\n    if (!actual ||\n        Object.keys(actual).length !== expectedEntries.length ||\n        expectedEntries.some(([key, value]) => actual[key] !== value)) {\n        throw new InvalidSolanaTransactionArtifactError('the execution binding does not match this account, environment, chain, recipient, or mint');\n    }\n}\nfunction createSolanaOrigin(source, publicConfig) {\n    const namespace = MANAGED_SWIG_NAMESPACES[source.environment];\n    const assertDestinationCallsSupported = () => {\n        if (!source.evmExecution) {\n            throw new UnsupportedAccountCapabilityError('EVM destination calls require a managed EVM account; an address-only receiver can only receive a plain delivery. Omit `calls`.', { vm: 'solana', field: 'calls' });\n        }\n        const compatible = locateSwig(asSwigNamespace(namespace), source.evmExecution.address);\n        if (compatible.wallet !== source.walletAddress ||\n            compatible.swig !== source.swigAddress) {\n            throw new UnsupportedAccountCapabilityError('This backend cannot execute EVM destination calls from the independently selected Swig. Omit `calls` to make a plain delivery.', { vm: 'solana', field: 'calls' });\n        }\n    };\n    const authority = source.owner.type === 'passkey'\n        ? {\n            kind: 'secp256r1',\n            publicKey: compressP256PublicKey(source.owner.account.publicKey),\n        }\n        : { kind: 'secp256k1', address: source.owner.account.address };\n    const transfer = (sdk, transaction, execution) => {\n        assertSupportedTransaction(transaction, publicConfig);\n        assertCapturedEnvironment(sdk);\n        if (!isSolanaOrigin(transaction)) {\n            throw new InvalidSolanaTransactionArtifactError('the transaction is not a Solana-origin transfer');\n        }\n        if (execution)\n            assertDestinationCallsSupported();\n        const common = {\n            ...(execution && source.evmExecution\n                ? {\n                    accountAddress: source.evmExecution.address,\n                    accountType: source.evmExecution.accountType,\n                }\n                : { accountAddress: source.walletAddress }),\n            authority,\n            walletAddress: source.walletAddress,\n            swigAddress: source.swigAddress,\n            namespace,\n            endpoint: sdk.orchestratorUrl,\n            ...(transaction.appFees ? { appFees: transaction.appFees } : {}),\n            ...(transaction.protocolFees\n                ? { protocolFees: transaction.protocolFees }\n                : {}),\n            ...(() => {\n                const sponsorSettings = toSponsorSettings(transaction.sponsored);\n                return sponsorSettings ? { sponsorSettings } : {};\n            })(),\n        };\n        if (isCrossChainSolanaOrigin(transaction)) {\n            // Resolved here rather than in `normalizeTransaction` so the prepare and\n            // reconstruct paths agree on the same recipient.\n            const recipient = transaction.recipient ?? source.evmRecipient;\n            if (!recipient) {\n                throw new UnsupportedAccountCapabilityError('A Solana-origin delivery from an account with no EVM entry needs an explicit EVM `recipient`.', { vm: 'solana', field: 'recipient' });\n            }\n            const sourceAsset = transaction.sourceAssets[0];\n            return {\n                ...common,\n                chain: transaction.sourceChains[0],\n                action: {\n                    kind: 'transfer',\n                    mint: sourceAsset.address,\n                    ...(transaction.tokenRequests[0].amount === undefined\n                        ? {}\n                        : { amount: transaction.tokenRequests[0].amount }),\n                    ...(sourceAsset.amount === undefined\n                        ? {}\n                        : { sourceLimit: sourceAsset.amount }),\n                    delivery: {\n                        kind: 'cross-chain',\n                        chainId: transaction.targetChain.id,\n                        token: transaction.tokenRequests[0].address,\n                        recipient,\n                        ...(execution ? { execution } : {}),\n                    },\n                },\n            };\n        }\n        if (isSolanaInstructionExecution(transaction)) {\n            return {\n                ...common,\n                chain: transaction.chain,\n                action: {\n                    kind: 'instructions',\n                    instructions: normalizeSolanaInstructions(transaction.instructions),\n                    ...(transaction.addressLookupTables\n                        ? { addressLookupTables: transaction.addressLookupTables }\n                        : {}),\n                },\n            };\n        }\n        const sourceLimit = transaction.sourceAssets?.[0].amount;\n        return {\n            ...common,\n            chain: transaction.chain,\n            action: {\n                kind: 'transfer',\n                mint: transaction.tokenRequests[0].address,\n                ...(transaction.tokenRequests[0].amount === undefined\n                    ? {}\n                    : { amount: transaction.tokenRequests[0].amount }),\n                ...(sourceLimit === undefined ? {} : { sourceLimit }),\n                delivery: { kind: 'same-chain', recipient: transaction.recipient },\n            },\n        };\n    };\n    const resolve = (sdk, workflows, prepared, intentId, explicitQuote) => {\n        assertPreparedBinding(prepared.request);\n        // Read back from the canonical input rather than resolved again: resolving\n        // reads the chain and runs caller code, and a replay has to rebuild the\n        // request that was quoted.\n        if (isCrossChainSolanaOrigin(prepared.transaction) &&\n            prepared.transaction.calls?.length) {\n            assertDestinationCallsSupported();\n        }\n        const stored = prepared.intentInput;\n        const execution = prepared.transaction.calls?.length &&\n            stored.destinationExecutions.length > 0\n            ? {\n                calls: stored.destinationExecutions.map(({ to, value, data }) => ({\n                    target: to,\n                    value: BigInt(value),\n                    data,\n                })),\n                ...(stored.destinationGasUnits === undefined\n                    ? {}\n                    : { gasLimit: BigInt(stored.destinationGasUnits) }),\n                account: {\n                    kind: stored.account.accountType === 'EOA' ? 'eoa' : 'erc7579',\n                    address: stored.account.address,\n                    setupOps: stored.account.setupOps ?? [],\n                    ...(stored.account.delegations?.[0]\n                        ? { delegationContract: stored.account.delegations[0].contract }\n                        : {}),\n                },\n            }\n            : undefined;\n        const input = transfer(sdk, prepared.transaction, execution);\n        assertSolanaMetadata(prepared.execution, input);\n        const quote = explicitQuote ?? selectedPublicQuote(prepared, intentId);\n        return workflows.reconstructSolanaIntent({\n            traceId: prepared.quotes.traceId,\n            transfer: input,\n            request: restorePreparedBinding(prepared.request),\n            intentInput: prepared.intentInput,\n            quote: normalizeIntentQuote(quote),\n            quotes: prepared.quotes.all.map((candidate) => normalizeIntentQuote(candidate)),\n        });\n    };\n    const assertCapturedEnvironment = (sdk) => {\n        if (sdk.environment !== source.environment ||\n            sdk.orchestratorUrl !== source.endpoint ||\n            !isManagedSolanaEndpoint(sdk.environment, sdk.orchestratorUrl)) {\n            throw new ManagedSolanaAccountNotSupportedError('Managed Solana execution remains bound to the environment and endpoint captured when the account was created.');\n        }\n    };\n    const resolveSwigId = (swigId) => {\n        const refuse = (message) => {\n            throw new UnsupportedAccountCapabilityError(message, {\n                vm: 'solana',\n                field: 'swigId',\n                swig: source.swigAddress,\n            });\n        };\n        if (swigId !== undefined) {\n            if (typeof swigId !== 'string' || !/^0x[0-9a-fA-F]{64}$/u.test(swigId)) {\n                refuse('`swigId` must be the 32-byte Swig id as 0x-prefixed hex.');\n            }\n            const id = swigId.toLowerCase();\n            if (locateSwigById(hexToBytes(id)).swig !== source.swigAddress) {\n                refuse(`\\`swigId\\` does not derive the configured Swig ${source.swigAddress}. Pass the id saved with that Swig.`);\n            }\n            return id;\n        }\n        if (source.evmExecution) {\n            const derived = locateSwig(asSwigNamespace(namespace), source.evmExecution.address);\n            if (derived.swig === source.swigAddress)\n                return bytesToHex(derived.id);\n        }\n        return refuse(`Creating the Swig ${source.swigAddress} needs the id it was minted with. Mint an independent Swig with \\`createSolanaSwigId()\\`, save its \\`id\\` with the \\`swig\\` address, and pass \\`{ swigId: id }\\` to \\`deploy\\`.`);\n    };\n    // The permanent root role, derived from the configured owner and never from\n    // caller input.\n    const rootAuthority = () => {\n        if (authority.kind === 'secp256r1') {\n            return { kind: 'secp256r1', publicKey: authority.publicKey };\n        }\n        const refuse = (message) => {\n            throw new UnsupportedAccountCapabilityError(message, {\n                vm: 'solana',\n                field: 'owner',\n            });\n        };\n        const publicKey = source.owner.account\n            .publicKey;\n        if (typeof publicKey !== 'string' ||\n            !/^0x04[0-9a-fA-F]{128}$/u.test(publicKey)) {\n            refuse(\"Creating a Swig installs the ECDSA owner's public key as its root, and this owner account exposes none. Configure the Solana owner with a viem local account (such as `privateKeyToAccount`), which carries `publicKey`.\");\n        }\n        if (!isAddressEqual(publicKeyToAddress(publicKey), authority.address)) {\n            refuse(\"The ECDSA owner's `publicKey` does not belong to its `address`.\");\n        }\n        return { kind: 'secp256k1', publicKey: publicKey };\n    };\n    const deploy = async (sdk, workflows, wait, chain, options) => {\n        assertCapturedEnvironment(sdk);\n        const chainId = solanaChainId(chain);\n        const input = {\n            chain,\n            walletAddress: source.walletAddress,\n            swigAddress: source.swigAddress,\n            authorization: authority,\n            initAuthority: rootAuthority(),\n            swigId: resolveSwigId(options?.swigId),\n            namespace,\n            endpoint: sdk.orchestratorUrl,\n        };\n        let prepared;\n        try {\n            prepared = await workflows.prepareSolanaDeployment(input);\n        }\n        catch (error) {\n            // Idempotent: the Swig existing is the outcome the caller asked for. Its\n            // root is not verified; a foreign root only fails the owner's spends.\n            if (isSolanaAccountAlreadyCreated(error) &&\n                error.swigAddress === source.swigAddress &&\n                error.chainId === chainId) {\n                return true;\n            }\n            throw error;\n        }\n        const submitted = await workflows.submitSolanaDeployment(prepared);\n        // Throws on a failed intent, so a resolved wait is a created Swig.\n        await wait(submitted.intentId);\n        return true;\n    };\n    return {\n        walletAddress: source.walletAddress,\n        assertDestinationCallsSupported,\n        deploy,\n        resolve,\n        async prepare(sdk, workflows, transaction, execution) {\n            const prepared = await workflows.prepareSolanaIntent(transfer(sdk, transaction, execution));\n            return toPreparedSolanaTransactionData(prepared, transaction);\n        },\n        async sign(sdk, workflows, preparedTransaction, options, signEvmRequests) {\n            if (options && 'owner' in options)\n                refuseSolanaAssembly();\n            const prepared = resolve(sdk, workflows, preparedTransaction, options?.intentId);\n            const signed = await workflows.signSolanaIntent({\n                prepared,\n                owner: source.owner.account,\n                ...(signEvmRequests ? { signEvmRequests } : {}),\n            });\n            return {\n                ...preparedTransaction,\n                quote: toPublicQuote(signed.prepared.quote),\n                proofs: [...signed.proofs],\n            };\n        },\n        async submit(sdk, workflows, signedTransaction, options) {\n            if (options && Object.keys(options).length > 0) {\n                throw new UnsupportedAccountCapabilityError('Solana submission does not accept submission options.', { vm: 'solana' });\n            }\n            const [proof, ...evmProofs] = signedTransaction.proofs;\n            if ((proof?.kind !== 'personalSign' && proof?.kind !== 'webauthn') ||\n                signedTransaction.proofs.length !==\n                    signedTransaction.quote.signingRequests.length ||\n                evmProofs.some(({ kind }) => kind !== 'eip712' && kind !== 'eip7702')) {\n                throw new InvalidSolanaTransactionArtifactError('submission requires the personal-sign or WebAuthn spend proof, then an EIP-712 or EIP-7702 proof for each further signing request', { intentId: signedTransaction.quote.intentId });\n            }\n            const prepared = resolve(sdk, workflows, signedTransaction, signedTransaction.quote.intentId, signedTransaction.quote);\n            const submitted = await workflows.submitSolanaIntent({\n                prepared,\n                proofs: [proof, ...evmProofs],\n            });\n            return {\n                type: 'intent',\n                id: submitted.intentId,\n                traceId: submitted.traceId,\n                ...(submitted.sourceChains\n                    ? { sourceChains: [...submitted.sourceChains] }\n                    : {}),\n                targetChain: submitted.targetChain,\n            };\n        },\n    };\n}\n/**\n * The restricted facade of a managed Solana account without managed EVM\n * capabilities. An optional EVM receiver is used only for address access and\n * plain-delivery defaults.\n */\nexport function createSolanaAccountFacade(source, publicConfig, composition) {\n    const solana = createSolanaOrigin(source, publicConfig);\n    const sdk = composition.config;\n    const workflows = composition.project.solana;\n    return {\n        config: publicConfig,\n        getAddress: ((vm) => {\n            if (vm === 'solana')\n                return source.walletAddress;\n            if (vm === 'evm' && source.evmRecipient)\n                return source.evmRecipient;\n            throw new AccountVmNotConfiguredError(String(vm));\n        }),\n        async prepareTransaction(transaction) {\n            const normalized = normalizeTransaction(transaction, publicConfig);\n            if (!isSolanaOrigin(normalized)) {\n                throw new UnsupportedAccountCapabilityError('An account without a managed EVM entry can only originate on Solana.', { vm: 'evm' });\n            }\n            return solana.prepare(sdk, workflows, normalized);\n        },\n        getTransactionMessages(preparedTransaction, options) {\n            solana.resolve(sdk, workflows, preparedTransaction, options?.intentId);\n            return [\n                ...selectedPublicQuote(preparedTransaction, options?.intentId)\n                    .signingRequests,\n            ];\n        },\n        signTransaction: (preparedTransaction, options) => solana.sign(sdk, workflows, preparedTransaction, options),\n        // Untyped callers passing options are refused rather than ignored.\n        submitTransaction: (signedTransaction, options) => solana.submit(sdk, workflows, signedTransaction, options),\n        waitForExecution: (result) => composition.project\n            .waitForIntentStatus(result.id)\n            .then(toPublicTransactionStatus),\n        deploy: async (vm, chain, options) => {\n            if (vm !== 'solana') {\n                throw new UnsupportedAccountCapabilityError('An account without a managed EVM entry can only create its Swig.', { vm: String(vm) });\n            }\n            return solana.deploy(sdk, workflows, composition.project.waitForIntentStatus, chain, options);\n        },\n    };\n}\nfunction signerIdForOwner(owner) {\n    // ECDSA local accounts also expose `publicKey`, so discriminate on the\n    // account type rather than the presence of a public key.\n    if (owner.type === 'webAuthn') {\n        return webauthnSignerId(owner.publicKey);\n    }\n    return ecdsaSignerId(owner.address);\n}\nfunction userOperationSignerSelection(context, transaction) {\n    if (!transaction.signers)\n        return undefined;\n    if (transaction.signers?.type === 'session') {\n        throw new Error('No account found');\n    }\n    const selection = adaptUserOperationSignerSelection(context.account, transaction.signers);\n    if (selection.kind !== 'owner')\n        throw new Error('No account found');\n    return selection;\n}\nfunction destinationChainReference(targetChain) {\n    if ('kind' in targetChain && typeof targetChain.caip2 === 'string') {\n        return parseCaip2(targetChain.caip2);\n    }\n    return getChainReference(targetChain.id);\n}\n// Public `Transaction` -> internal `IntentInput`. Owned here because the facade\n// is the only translation point between the compatibility surface and the\n// intent workflow.\n/**\n * Derives the quoter pin a venue-scoped session implies.\n *\n * A session created with `swap: { via: [...] }` already names the venues it will\n * authorise on-chain, but the orchestrator picks the venue *after* the session is\n * signed. Sending the matching pin closes that gap, and deriving it here means a\n * caller states the venue once — stating it twice and keeping the two in sync by\n * hand is the drift this is meant to prevent.\n *\n * Returns undefined (no pin) when the scope cannot imply one: a bare Rhinestone\n * Swapper venue is aggregator-agnostic, so any quoter may legitimately fill it,\n * and pinning would reject routes the session actually permits.\n *\n * Across a per-chain session set the pin is the INTERSECTION, not the union.\n * `options.quoters` is one global filter with no chain dimension, so a venue is\n * only safe to allow if every session would accept it — unioning a 0x-only and\n * a fynd-only session would permit fynd everywhere and be rejected on-chain by\n * the first. An empty intersection means no single venue satisfies every\n * session, which is unservable rather than unconstrained — it yields an empty\n * filter so the request fails at quote time, instead of no filter, which would\n * hand the orchestrator back the free choice the pin exists to take away.\n */\nfunction venuesForSession(session) {\n    const via = session?.swap?.via;\n    // No venue list means the scope defaults to the Swapper — unconstrained.\n    if (!via?.length)\n        return null;\n    const quoters = new Set();\n    for (const venue of via) {\n        if (venue.id === '0x')\n            quoters.add('0x');\n        else if (venue.id === 'fynd')\n            quoters.add('fynd');\n        else if (venue.id === 'rhinestone') {\n            // The Swapper routes through whichever aggregator wins unless the scope\n            // pinned one, so an unpinned Swapper venue admits any quoter.\n            if (venue.route === 'zeroEx')\n                quoters.add('0x');\n            else if (venue.route === 'fynd')\n                quoters.add('fynd');\n            else\n                return null;\n        }\n        else\n            return null;\n    }\n    return quoters;\n}\nfunction quoterPinFromSession(signers, \n/**\n * Chains this intent can actually touch. A per-chain session map is reusable\n * and may carry chains the intent never signs on; `prepareIntentSessions`\n * selects only the intent's own chains, so intersecting the rest would let an\n * unrelated entry veto a venue and fail the quote for nothing.\n */\nchainIds) {\n    if (signers?.type !== 'session')\n        return undefined;\n    const relevant = new Set(chainIds);\n    const sessions = 'session' in signers\n        ? [signers.session]\n        : Object.entries(signers.sessions ?? {})\n            .filter(([chainId]) => relevant.has(Number(chainId)))\n            .map(([, s]) => s.session);\n    let pinned = null;\n    for (const session of sessions) {\n        const venues = venuesForSession(session);\n        // An unconstrained session admits every venue, so it narrows nothing.\n        if (!venues)\n            continue;\n        if (!pinned) {\n            pinned = venues;\n            continue;\n        }\n        const narrowed = new Set();\n        for (const quoter of pinned) {\n            if (venues.has(quoter))\n                narrowed.add(quoter);\n        }\n        pinned = narrowed;\n    }\n    // Null means nothing constrained anything — genuinely unpinned. An empty set\n    // is the opposite: the sessions conflict, so no venue is safe and the empty\n    // filter fails the request closed.\n    if (!pinned)\n        return undefined;\n    return { include: [...pinned] };\n}\n/**\n * Combine an explicit `quoters` filter with the one a venue-scoped session\n * implies.\n *\n * An explicit filter cannot WIDEN the session: the venues it names are what the\n * on-chain policy will accept, so allowing a caller to replace the derived pin\n * would route outside them and be rejected at execution — or, where the scope\n * left the tail open, spend inside a venue the session was never meant to\n * authorise. With no session scope there is nothing to narrow against and the\n * explicit filter stands on its own.\n */\nfunction isSameChainSolanaOrigin(transaction) {\n    return ('chain' in transaction &&\n        typeof transaction.chain === 'object' &&\n        transaction.chain !== null &&\n        'kind' in transaction.chain &&\n        transaction.chain.kind === 'svm');\n}\nfunction isCrossChainSolanaOrigin(transaction) {\n    const source = transaction\n        .sourceChains?.[0];\n    return (typeof source === 'object' &&\n        source !== null &&\n        'kind' in source &&\n        source.kind === 'svm');\n}\nfunction isSolanaInstructionExecution(transaction) {\n    return (isSameChainSolanaOrigin(transaction) &&\n        transaction.instructions !== undefined);\n}\nfunction isSolanaOrigin(transaction) {\n    return (isSameChainSolanaOrigin(transaction) ||\n        isCrossChainSolanaOrigin(transaction));\n}\nfunction assertSolanaObjectKeys(value, allowed, label) {\n    if (!value || typeof value !== 'object' || Array.isArray(value)) {\n        throw new UnsupportedAccountCapabilityError(`Managed Solana ${label} must be an object.`, { vm: 'solana', field: label });\n    }\n    const unsupported = Object.keys(value).find((key) => !allowed.includes(key));\n    if (unsupported) {\n        throw new UnsupportedAccountCapabilityError(`Solana-origin transfers do not support \\`${label}.${unsupported}\\`.`, { vm: 'solana', field: `${label}.${unsupported}` });\n    }\n}\n/**\n * Checks the one source asset of a Solana-origin transfer: an SPL mint on\n * `cluster`, with an optional positive ceiling.\n */\nfunction assertSolanaSourceAsset(sourceAssets, cluster) {\n    const refuse = (message, field) => {\n        throw new UnsupportedAccountCapabilityError(message, {\n            vm: 'solana',\n            field,\n        });\n    };\n    if (!Array.isArray(sourceAssets) || sourceAssets.length !== 1) {\n        refuse('A Solana-origin transfer names exactly one source asset: `sourceAssets: [{ chain, address, amount? }]`.', 'sourceAssets');\n    }\n    const asset = sourceAssets[0];\n    assertSolanaObjectKeys(asset, ['chain', 'address', 'amount'], 'sourceAssets[0]');\n    let chainId;\n    try {\n        chainId = solanaChainId(asset.chain);\n    }\n    catch {\n        // Refused below with the field it concerns.\n    }\n    if (chainId === undefined ||\n        asset.chain.caip2 !== cluster.caip2) {\n        refuse('The source asset must be on the Solana cluster the transaction spends from.', 'sourceAssets[0].chain');\n    }\n    let mint;\n    try {\n        mint = solanaAddress(asset.address);\n    }\n    catch {\n        // Refused below with the field it concerns.\n    }\n    if (mint === undefined || mint === NATIVE_SOL_SENTINEL) {\n        refuse('The source asset must be a valid SPL mint address; native SOL is not supported.', 'sourceAssets[0].address');\n    }\n    if (asset.amount !== undefined &&\n        (typeof asset.amount !== 'bigint' || asset.amount <= 0n)) {\n        refuse('A source asset `amount` caps what the wallet may debit and must be a positive bigint when provided.', 'sourceAssets[0].amount');\n    }\n    return {\n        address: mint,\n        ...(asset.amount === undefined ? {} : { amount: asset.amount }),\n    };\n}\nfunction assertSupportedSolanaTransaction(input, config) {\n    const runsInstructions = input.instructions !== undefined;\n    const allowed = new Set(runsInstructions\n        ? ['chain', 'instructions', 'addressLookupTables', 'sponsored']\n        : [\n            'chain',\n            'tokenRequests',\n            'recipient',\n            'sourceAssets',\n            'sponsored',\n            'appFees',\n            'protocolFees',\n        ]);\n    const unsupported = Object.keys(input).find((key) => !allowed.has(key));\n    if (unsupported) {\n        throw new UnsupportedAccountCapabilityError(`Solana-origin transfers do not support \\`${unsupported}\\`.`, { vm: 'solana', field: unsupported });\n    }\n    if (!config.solana || !('owner' in config.solana)) {\n        throw new UnsupportedAccountCapabilityError('A managed Solana source is required for Solana-origin transfers.', { vm: 'solana' });\n    }\n    solanaChainId(input.chain);\n    if (runsInstructions) {\n        // Shape and limits are enforced by the normalizer, which also produces the\n        // canonical form `normalizeTransaction` stores.\n        normalizeSolanaInstructions(input.instructions);\n        normalizeSolanaAddressLookupTables(input.addressLookupTables);\n        return;\n    }\n    if (!Array.isArray(input.tokenRequests) || input.tokenRequests.length !== 1) {\n        throw new UnsupportedAccountCapabilityError('Managed Solana transfers require exactly one SPL token request.', { vm: 'solana' });\n    }\n    const request = input.tokenRequests[0];\n    assertSolanaObjectKeys(request, ['address', 'amount'], 'tokenRequests[0]');\n    if (typeof request.address !== 'string') {\n        throw new UnsupportedAccountCapabilityError('Managed Solana transfers require one valid SPL mint address.', { vm: 'solana' });\n    }\n    try {\n        solanaAddress(request.address);\n    }\n    catch {\n        throw new UnsupportedAccountCapabilityError('Managed Solana transfers require one valid SPL mint address.', { vm: 'solana' });\n    }\n    if (request.amount !== undefined &&\n        (typeof request.amount !== 'bigint' || request.amount <= 0n)) {\n        throw new UnsupportedAccountCapabilityError('A Solana token amount must be a positive bigint when provided.', { vm: 'solana' });\n    }\n    if (input.sourceAssets !== undefined) {\n        const asset = assertSolanaSourceAsset(input.sourceAssets, input.chain);\n        if (asset.address !== request.address) {\n            throw new UnsupportedAccountCapabilityError('The source asset must be the mint the transfer sends.', { vm: 'solana', field: 'sourceAssets[0].address' });\n        }\n        if (asset.amount !== undefined &&\n            request.amount !== undefined &&\n            request.amount > asset.amount) {\n            throw new UnsupportedAccountCapabilityError('The token amount exceeds the source asset `amount` that caps it.', { vm: 'solana', field: 'sourceAssets[0].amount' });\n        }\n    }\n    if (input.appFees !== undefined) {\n        assertSolanaObjectKeys(input.appFees, ['feeBps'], 'appFees');\n    }\n    if (input.protocolFees !== undefined) {\n        assertSolanaObjectKeys(input.protocolFees, ['feeBps'], 'protocolFees');\n    }\n    if (typeof input.recipient !== 'string') {\n        throw new UnsupportedAccountCapabilityError('Managed Solana transfers require an explicit recipient wallet.', { vm: 'solana' });\n    }\n    try {\n        solanaAddress(input.recipient);\n    }\n    catch {\n        throw new UnsupportedAccountCapabilityError('Managed Solana transfers require a valid recipient wallet.', { vm: 'solana' });\n    }\n}\nfunction assertSupportedSolanaOriginDelivery(input, config) {\n    if (Object.hasOwn(input, 'sourceTokens')) {\n        throw new UnsupportedAccountCapabilityError('`sourceTokens` was replaced by `sourceAssets: [{ chain, address, amount? }]`.', { vm: 'solana', field: 'sourceTokens' });\n    }\n    const allowed = new Set([\n        'sourceChains',\n        'sourceAssets',\n        'targetChain',\n        'tokenRequests',\n        'recipient',\n        'calls',\n        'gasLimit',\n        'eip7702InitSignature',\n        'sponsored',\n        'appFees',\n        'protocolFees',\n    ]);\n    const unsupported = Object.keys(input).find((key) => !allowed.has(key));\n    if (unsupported) {\n        throw new UnsupportedAccountCapabilityError(`Solana-origin transfers do not support \\`${unsupported}\\`.`, { vm: 'solana', field: unsupported });\n    }\n    if (!config.solana || !('owner' in config.solana)) {\n        throw new UnsupportedAccountCapabilityError('A managed Solana source is required for Solana-origin transfers.', { vm: 'solana' });\n    }\n    if (input.calls !== undefined && !Array.isArray(input.calls)) {\n        throw new UnsupportedAccountCapabilityError('`calls` must be an array of destination calls.', { vm: 'solana', field: 'calls' });\n    }\n    const runsCalls = Array.isArray(input.calls) && input.calls.length > 0;\n    const hasManagedEvm = config.evm !== undefined && !Object.hasOwn(config.evm, 'address');\n    if (runsCalls && !hasManagedEvm) {\n        throw new UnsupportedAccountCapabilityError('Destination calls require a managed EVM account; an address-only receiver can only receive a plain delivery. Omit `calls`.', { vm: 'solana', field: 'calls' });\n    }\n    if (runsCalls && input.recipient !== undefined) {\n        throw new UnsupportedAccountCapabilityError('An explicit delivery recipient cannot execute destination calls. Omit `recipient` to execute with the invoking managed EVM account.', { vm: 'solana', field: 'recipient' });\n    }\n    for (const field of ['gasLimit', 'eip7702InitSignature']) {\n        if (input[field] !== undefined && !runsCalls) {\n            throw new UnsupportedAccountCapabilityError(`\\`${field}\\` applies to destination \\`calls\\`, and this delivery has none.`, { vm: 'solana', field });\n        }\n    }\n    const sources = input.sourceChains;\n    if (sources.length !== 1) {\n        throw new UnsupportedAccountCapabilityError('A Solana-origin delivery spends exactly one Solana cluster.', { vm: 'solana', field: 'sourceChains' });\n    }\n    solanaChainId(sources[0]);\n    assertSolanaSourceAsset(input.sourceAssets, sources[0]);\n    const target = input.targetChain;\n    if (!target ||\n        typeof target !== 'object' ||\n        'kind' in target ||\n        'caip2' in target ||\n        typeof target.id !== 'number' ||\n        !Number.isSafeInteger(target.id) ||\n        target.id < 0 ||\n        !formatCaip2(target.id).startsWith('eip155:')) {\n        throw new UnsupportedAccountCapabilityError('A Solana-origin delivery requires a viem EVM destination chain.', { vm: 'solana', field: 'targetChain' });\n    }\n    if (!Array.isArray(input.tokenRequests) || input.tokenRequests.length !== 1) {\n        throw new UnsupportedAccountCapabilityError('A Solana-origin delivery requires exactly one destination token request.', { vm: 'solana', field: 'tokenRequests' });\n    }\n    const request = input.tokenRequests[0];\n    assertSolanaObjectKeys(request, ['address', 'amount'], 'tokenRequests[0]');\n    if (typeof request.address !== 'string' || !isAddress(request.address)) {\n        throw new UnsupportedAccountCapabilityError('A Solana-origin delivery requires an EVM destination token address.', { vm: 'solana', field: 'tokenRequests[0].address' });\n    }\n    if (request.amount !== undefined &&\n        (typeof request.amount !== 'bigint' || request.amount <= 0n)) {\n        throw new UnsupportedAccountCapabilityError('A delivery amount must be a positive bigint when provided.', { vm: 'solana', field: 'tokenRequests[0].amount' });\n    }\n    if (input.recipient !== undefined &&\n        (typeof input.recipient !== 'string' || !isAddress(input.recipient))) {\n        throw new UnsupportedAccountCapabilityError('A Solana-origin delivery recipient must be an EVM address.', { vm: 'solana', field: 'recipient' });\n    }\n    if (input.appFees !== undefined) {\n        assertSolanaObjectKeys(input.appFees, ['feeBps'], 'appFees');\n    }\n    if (input.protocolFees !== undefined) {\n        assertSolanaObjectKeys(input.protocolFees, ['feeBps'], 'protocolFees');\n    }\n}\nfunction assertSupportedTransaction(transaction, config) {\n    const input = transaction;\n    if (isCrossChainSolanaOrigin(transaction)) {\n        assertSupportedSolanaOriginDelivery(input, config);\n        return;\n    }\n    const hasChain = Object.hasOwn(input, 'chain') && input.chain !== undefined;\n    const hasTarget = Object.hasOwn(input, 'targetChain') && input.targetChain !== undefined;\n    if (hasChain === hasTarget) {\n        throw new UnsupportedAccountCapabilityError('A transaction must set exactly one of `chain` or `targetChain`.');\n    }\n    if (hasChain && typeof input.chain === 'object' && input.chain !== null) {\n        const chain = input.chain;\n        if (chain.kind === 'svm') {\n            assertSupportedSolanaTransaction(input, config);\n            return;\n        }\n    }\n    if (hasTarget && typeof input.targetChain === 'object' && input.targetChain) {\n        const target = input.targetChain;\n        if (!('kind' in target || 'caip2' in target) &&\n            (typeof target.id !== 'number' ||\n                !Number.isSafeInteger(target.id) ||\n                target.id < 0 ||\n                !formatCaip2(target.id).startsWith('eip155:'))) {\n            throw new UnsupportedAccountCapabilityError('A viem EVM destination must use an eip155 chain ID.');\n        }\n        if (('kind' in target || 'caip2' in target) &&\n            !((target.kind === 'svm' &&\n                typeof target.caip2 === 'string' &&\n                target.caip2.startsWith('solana:')) ||\n                (target.kind === 'tvm' &&\n                    typeof target.caip2 === 'string' &&\n                    target.caip2.startsWith('tron:')) ||\n                (target.kind === 'stellar' &&\n                    typeof target.caip2 === 'string' &&\n                    target.caip2.startsWith('stellar:')) ||\n                (target.kind === 'hypercore' &&\n                    (target.caip2 === 'hypercore:spot' ||\n                        target.caip2 === 'hypercore:perp')))) {\n            throw new UnsupportedAccountCapabilityError('The destination chain descriptor has mismatched VM and CAIP-2 fields.');\n        }\n        if (target.kind === 'svm') {\n            if (!Array.isArray(input.tokenRequests) ||\n                input.tokenRequests.length === 0) {\n                throw new UnsupportedAccountCapabilityError('Solana destinations require at least one token request.', { vm: 'solana' });\n            }\n            for (const request of input.tokenRequests) {\n                if (typeof request.address !== 'string') {\n                    throw new UnsupportedAccountCapabilityError('Solana token requests require a Solana address.');\n                }\n                solanaAddress(request.address);\n                if (request.amount !== undefined &&\n                    (typeof request.amount !== 'bigint' || request.amount <= 0n)) {\n                    throw new UnsupportedAccountCapabilityError('Solana token request amounts must be positive.');\n                }\n            }\n            // Anything other than a Solana address string would slip past both\n            // recipient defaults and then be dropped downstream, quoting a delivery\n            // with no receiver at all.\n            if (input.recipient !== undefined) {\n                if (typeof input.recipient !== 'string') {\n                    throw new UnsupportedAccountCapabilityError('A Solana delivery recipient must be a Solana address.', { vm: 'solana' });\n                }\n                solanaAddress(input.recipient);\n            }\n            if (input.calls !== undefined ||\n                input.instructions !== undefined ||\n                input.hyperCore !== undefined) {\n                throw new UnsupportedAccountCapabilityError('Solana destinations support token delivery only; calls, custom instructions and HyperCore actions are unavailable.', { vm: 'solana' });\n            }\n            if (input.recipient === undefined && !config.solana) {\n                throw new AccountVmNotConfiguredError('solana');\n            }\n        }\n    }\n    if (input.sourceChains !== undefined) {\n        if (!Array.isArray(input.sourceChains)) {\n            throw new UnsupportedAccountCapabilityError('`sourceChains` must be an array of managed source chains.');\n        }\n        if (input.sourceChains.length === 0) {\n            throw new UnsupportedAccountCapabilityError('`sourceChains` must contain at least one managed source.');\n        }\n        const ids = input.sourceChains.map((value) => typeof value === 'object' && value\n            ? value.id\n            : null);\n        const invalidSource = input.sourceChains.some((value) => {\n            if (!value || typeof value !== 'object')\n                return true;\n            const source = value;\n            return (typeof source.id !== 'number' ||\n                !Number.isSafeInteger(source.id) ||\n                source.id < 0 ||\n                Object.hasOwn(source, 'kind') ||\n                Object.hasOwn(source, 'caip2') ||\n                !formatCaip2(source.id).startsWith('eip155:'));\n        });\n        if (invalidSource) {\n            throw new UnsupportedAccountCapabilityError('Only viem EVM chains from the managed EVM account can be used as sources.');\n        }\n        if (new Set(ids).size !== ids.length) {\n            throw new UnsupportedAccountCapabilityError('`sourceChains` cannot contain duplicate chains.');\n        }\n    }\n    const calls = input.calls;\n    if (input.recipient !== undefined) {\n        if (Array.isArray(calls) && calls.length > 0) {\n            throw new UnsupportedAccountCapabilityError('An explicit delivery recipient cannot execute destination calls. Omit `recipient` to execute with the invoking managed EVM account.');\n        }\n        if (!Array.isArray(input.tokenRequests) ||\n            input.tokenRequests.length === 0) {\n            throw new UnsupportedAccountCapabilityError('An explicit delivery recipient requires at least one token request.');\n        }\n    }\n}\nfunction freezeSponsorship(sponsored) {\n    if (sponsored === undefined || typeof sponsored === 'boolean')\n        return {};\n    return { sponsored: Object.freeze({ ...sponsored }) };\n}\nexport function normalizeTransaction(transaction, config) {\n    assertSupportedTransaction(transaction, config);\n    if (isCrossChainSolanaOrigin(transaction)) {\n        return Object.freeze({\n            ...transaction,\n            sourceChains: [\n                Object.freeze({ ...transaction.sourceChains[0] }),\n            ],\n            sourceAssets: [\n                Object.freeze({\n                    ...transaction.sourceAssets[0],\n                    chain: Object.freeze({ ...transaction.sourceAssets[0].chain }),\n                }),\n            ],\n            tokenRequests: [\n                Object.freeze({ ...transaction.tokenRequests[0] }),\n            ],\n            ...(transaction.appFees\n                ? { appFees: Object.freeze({ ...transaction.appFees }) }\n                : {}),\n            ...(transaction.protocolFees\n                ? { protocolFees: Object.freeze({ ...transaction.protocolFees }) }\n                : {}),\n            ...freezeSponsorship(transaction.sponsored),\n        });\n    }\n    if (isSolanaInstructionExecution(transaction)) {\n        const lookupTables = normalizeSolanaAddressLookupTables(transaction.addressLookupTables);\n        const { addressLookupTables: _tables, ...rest } = transaction;\n        return Object.freeze({\n            ...rest,\n            chain: Object.freeze({ ...transaction.chain }),\n            instructions: normalizeSolanaInstructions(transaction.instructions),\n            ...(lookupTables ? { addressLookupTables: lookupTables } : {}),\n            ...freezeSponsorship(transaction.sponsored),\n        });\n    }\n    if (isSameChainSolanaOrigin(transaction)) {\n        const request = transaction.tokenRequests[0];\n        const asset = transaction.sourceAssets?.[0];\n        return Object.freeze({\n            ...transaction,\n            chain: Object.freeze({ ...transaction.chain }),\n            tokenRequests: [Object.freeze({ ...request })],\n            ...(asset\n                ? {\n                    sourceAssets: [\n                        Object.freeze({\n                            ...asset,\n                            chain: Object.freeze({ ...asset.chain }),\n                        }),\n                    ],\n                }\n                : {}),\n            ...(transaction.appFees\n                ? { appFees: Object.freeze({ ...transaction.appFees }) }\n                : {}),\n            ...(transaction.protocolFees\n                ? { protocolFees: Object.freeze({ ...transaction.protocolFees }) }\n                : {}),\n            ...freezeSponsorship(transaction.sponsored),\n        });\n    }\n    if ('targetChain' in transaction &&\n        transaction.targetChain !== undefined &&\n        'kind' in transaction.targetChain &&\n        transaction.targetChain.kind === 'svm' &&\n        transaction.recipient === undefined &&\n        config.solana &&\n        'address' in config.solana) {\n        return Object.freeze({\n            ...transaction,\n            recipient: config.solana.address,\n        });\n    }\n    return Object.freeze({ ...transaction });\n}\nfunction narrowQuoterPin(derived, explicit) {\n    if (!explicit)\n        return derived;\n    if (!derived || !('include' in derived))\n        return explicit;\n    const allowed = new Set(derived.include);\n    const narrowed = 'include' in explicit\n        ? explicit.include.filter((quoter) => allowed.has(quoter))\n        : derived.include.filter((quoter) => !explicit.exclude.includes(quoter));\n    return { include: narrowed };\n}\n/**\n * Translates the public `sponsored` input into the wire's `sponsorSettings`.\n * Shared by both VMs so the two cannot drift.\n */\nfunction toSponsorSettings(sponsored) {\n    if (!sponsored)\n        return undefined;\n    if (typeof sponsored === 'boolean') {\n        return {\n            gas: sponsored,\n            bridgeFees: sponsored,\n            swapFees: sponsored,\n            protocolFees: sponsored,\n        };\n    }\n    return {\n        gas: sponsored.gas,\n        bridgeFees: sponsored.bridging,\n        swapFees: sponsored.swaps,\n        protocolFees: sponsored.protocolFees ?? false,\n    };\n}\nexport function adaptTransaction(context, transaction, hyperCoreAction, automaticSourceChainIds) {\n    const nonEvmOrigin = 'chain' in transaction && transaction.chain && 'kind' in transaction.chain\n        ? transaction.chain.kind\n        : transaction.sourceChains?.find((chain) => 'kind' in chain)?.kind;\n    if (nonEvmOrigin) {\n        throw new UnsupportedAccountCapabilityError('Non-EVM origin execution is not supported yet. Use a viem EVM chain as the managed source.', { vm: nonEvmOrigin });\n    }\n    const destination = 'chain' in transaction\n        ? getChainReference(transaction.chain.id)\n        : 'kind' in transaction.targetChain\n            ? parseCaip2(transaction.targetChain.caip2)\n            : getChainReference(transaction.targetChain.id);\n    const destinationChainId = destination.kind === 'evm' ? destination.id : undefined;\n    const sourceChains = 'chain' in transaction\n        ? [getChainReference(transaction.chain.id)]\n        : (transaction.sourceChains?.map((chain) => getChainReference(chain.id)) ?? automaticSourceChainIds?.map(getChainReference));\n    const evmSources = sourceChains?.flatMap((chain) => chain.kind === 'evm' ? [chain] : []);\n    return {\n        destination,\n        ...(evmSources ? { sourceChains: evmSources } : {}),\n        calls: (transaction.calls ?? []).map((call) => adaptCall(call, destinationChainId)),\n        tokenRequests: (transaction.tokenRequests ?? []).map((request) => ({\n            token: destinationChainId === undefined\n                ? request.address\n                : normalizeTokenAddress(request.address, destinationChainId, false),\n            ...(request.amount === undefined ? {} : { amount: request.amount }),\n        })),\n        ...(transaction.recipient\n            ? {\n                recipient: adaptRecipient(context, transaction.recipient, destination, transaction.eip7702InitSignature, transaction.experimental_accountOverride?.setupOps),\n            }\n            : {}),\n        ...(transaction.gasLimit === undefined\n            ? {}\n            : { gasLimit: transaction.gasLimit }),\n        ...(transaction.eip7702InitSignature\n            ? { eip7702InitSignature: transaction.eip7702InitSignature }\n            : {}),\n        ...(transaction.sourceAssets || sourceChains\n            ? {\n                accountAccessList: adaptSourceAssets(\n                // Solana origins, whose source asset is a tuple, are refused above.\n                transaction.sourceAssets, evmSources?.map(({ id }) => id)),\n            }\n            : {}),\n        options: {\n            ...(transaction.appFees ? { appFees: transaction.appFees } : {}),\n            ...(transaction.protocolFees\n                ? { protocolFees: transaction.protocolFees }\n                : {}),\n            ...('chain' in transaction && transaction.customDeadline !== undefined\n                ? { customDeadline: transaction.customDeadline }\n                : {}),\n            ...(() => {\n                const sponsorSettings = toSponsorSettings(transaction.sponsored);\n                return sponsorSettings ? { sponsorSettings } : {};\n            })(),\n            ...(transaction.settlementLayers\n                ? { settlementLayers: transaction.settlementLayers }\n                : {}),\n            ...(() => {\n                const derived = quoterPinFromSession(transaction.signers, [\n                    ...(destinationChainId === undefined ? [] : [destinationChainId]),\n                    ...(evmSources?.map(({ id }) => id) ?? []),\n                ]);\n                const quoters = narrowQuoterPin(derived, transaction.quoters);\n                return quoters ? { quoters } : {};\n            })(),\n            ...(transaction.auxiliaryFunds\n                ? { auxiliaryFunds: transaction.auxiliaryFunds }\n                : {}),\n            ...(hyperCoreAction ? { hyperCore: { action: hyperCoreAction } } : {}),\n        },\n        ...(transaction.sourceCalls\n            ? {\n                sourceCalls: Object.fromEntries(Object.entries(transaction.sourceCalls).map(([chainId, calls]) => [\n                    Number(chainId),\n                    calls.map((call) => ({\n                        call: adaptCall(call, Number(chainId)),\n                        ...(call.provides ? { provides: call.provides } : {}),\n                    })),\n                ])),\n            }\n            : {}),\n        ...(transaction.experimental_accountOverride?.setupOps\n            ? {\n                accountSetupOverride: transaction.experimental_accountOverride.setupOps,\n            }\n            : {}),\n        ...(transaction.signers\n            ? {\n                signers: transaction.signers.type === 'session'\n                    ? {\n                        kind: 'smart-session',\n                        byChain: adaptSessionSelection(transaction, sourceChains ?? []),\n                    }\n                    : adaptSignerSelection(context.account, transaction.signers),\n            }\n            : {}),\n    };\n}\nfunction adaptRecipient(context, recipient, destination, eip7702InitSignature, setupOverride) {\n    if (typeof recipient === 'string') {\n        return projectIntentRecipient(recipient);\n    }\n    if (destination.kind !== 'evm') {\n        throw new Error('Smart-account recipients require an EVM destination');\n    }\n    const resolved = resolveAccountConfig(context.sdk, toAccountConstructionInput(recipient));\n    return asIntentRecipient(projectIntentAccount({\n        runtime: createStaticAccountRuntime(resolved, destination, false),\n        ...(setupOverride ? { setupOverride } : {}),\n        ...(eip7702InitSignature ? { eip7702InitSignature } : {}),\n    }));\n}\nfunction toAccountConstructionInput(config) {\n    return {\n        ...(config.account ? { account: config.account } : {}),\n        ...(config.owners ? { owners: config.owners } : {}),\n        ...(config.sessions ? { sessions: config.sessions } : {}),\n        ...(config.recovery ? { recovery: config.recovery } : {}),\n        ...(config.eoa ? { eoa: config.eoa } : {}),\n        ...(config.modules ? { modules: config.modules } : {}),\n        ...(config.initData ? { initData: config.initData } : {}),\n    };\n}\nfunction adaptCall(call, chainId) {\n    if ('resolve' in call) {\n        return {\n            resolve: async (ctx) => {\n                const chain = getChainById(ctx.chain.id);\n                const value = await call.resolve({\n                    config: ctx.config,\n                    chain,\n                    accountAddress: ctx.account,\n                });\n                return (Array.isArray(value) ? value : [value]).map((item) => normalizeCall(item, ctx.chain.id));\n            },\n        };\n    }\n    if (chainId === undefined) {\n        throw new Error('Destination calls are not supported for non-EVM chains');\n    }\n    return normalizeCall(call, chainId);\n}\nfunction normalizeCall(call, chainId) {\n    return {\n        target: normalizeTokenAddress(call.to, chainId, false),\n        value: call.value ?? 0n,\n        data: call.data ?? '0x',\n    };\n}\nfunction adaptSessionSelection(transaction, chains) {\n    const signers = transaction.signers;\n    if (!signers || signers.type !== 'session')\n        return {};\n    if ('sessions' in signers) {\n        return Object.fromEntries(Object.entries(signers.sessions).map(([chainId, selection]) => [\n            Number(chainId),\n            selection,\n        ]));\n    }\n    const chainIds = new Set(chains.flatMap((chain) => chain.kind === 'evm' && chain.id !== undefined ? [chain.id] : []));\n    if ('chain' in transaction && !('kind' in transaction.chain)) {\n        chainIds.add(transaction.chain.id);\n    }\n    if ('targetChain' in transaction &&\n        transaction.targetChain &&\n        'id' in transaction.targetChain) {\n        chainIds.add(transaction.targetChain.id);\n    }\n    return Object.fromEntries([...chainIds].map((chainId) => [\n        chainId,\n        {\n            session: signers.session,\n            ...(signers.enableData ? { enableData: signers.enableData } : {}),\n        },\n    ]));\n}\nfunction adaptSourceAssets(sourceAssets, chainIds) {\n    if (!sourceAssets)\n        return chainIds ? { chainIds } : undefined;\n    // An explicit but empty selection fails closed, and it fails here: sent on,\n    // it is a wire-schema rejection naming fields the caller never wrote.\n    if ((Array.isArray(sourceAssets) ? sourceAssets : Object.keys(sourceAssets))\n        .length === 0) {\n        throw new UnsupportedAccountCapabilityError('`sourceAssets` is empty, so the intent has nothing to spend from. Name at least one source asset, or omit `sourceAssets` to use every eligible source.');\n    }\n    const eligible = chainIds ? new Set(chainIds) : undefined;\n    const assertEligible = (chainId) => {\n        if (eligible && !eligible.has(chainId)) {\n            throw new UnsupportedAccountCapabilityError(`Source assets reference chain ${chainId}, which is outside the eligible source scope.`, { chainId });\n        }\n    };\n    if (Array.isArray(sourceAssets)) {\n        if (sourceAssets.length > 0 && typeof sourceAssets[0] === 'object') {\n            const chainTokens = {};\n            const chainTokenAmounts = {};\n            for (const item of sourceAssets) {\n                assertEligible(item.chain.id);\n                const token = normalizeTokenAddress(item.address, item.chain.id, false);\n                if (item.amount === undefined)\n                    (chainTokens[item.chain.id] ??= []).push(token);\n                else\n                    (chainTokenAmounts[item.chain.id] ??= {})[token] = item.amount;\n            }\n            return {\n                ...(Object.keys(chainTokens).length > 0 ? { chainTokens } : {}),\n                ...(Object.keys(chainTokenAmounts).length > 0\n                    ? { chainTokenAmounts }\n                    : {}),\n            };\n        }\n        const tokens = sourceAssets;\n        validateTokenAddresses(tokens);\n        return {\n            ...(chainIds ? { chainIds } : {}),\n            tokens,\n        };\n    }\n    // ChainTokenMap: validate every per-chain list too, so symbols can't slip\n    // through this input the way they can't through tokenRequests / ExactInputConfig.\n    for (const [chainId, tokens] of Object.entries(sourceAssets)) {\n        assertEligible(Number(chainId));\n        if (tokens.length === 0) {\n            throw new UnsupportedAccountCapabilityError(`\\`sourceAssets\\` names chain ${chainId} with no tokens, so that chain has nothing to spend. Name at least one token, or drop the chain.`, { chainId: Number(chainId) });\n        }\n        validateTokenAddresses(tokens);\n    }\n    return { chainTokens: sourceAssets };\n}\n","import { defineChain } from 'viem';\nimport * as viemChains from 'viem/chains';\nimport { formatCaip2, isHyperCoreWireId } from './caip2.js';\n// Chain objects (rpc / nativeCurrency / formatters, needed for signing and\n// `createPublicClient`) come from viem — not from bundled chain config. The\n// supported *set* is gated by the orchestrator; this resolves any known viem\n// chain by id.\nconst allViemChains = Object.values(viemChains).filter((chain) => typeof chain?.id === 'number');\nexport function getChainById(chainId) {\n    const known = allViemChains.find((chain) => chain.id === chainId);\n    if (known)\n        return known;\n    // The SDK must not gate signing/execution on its bundled viem version: a chain\n    // the orchestrator supports before viem knows it must still resolve. Fall back\n    // to a minimal chain carrying the id — the field EIP-712 signing needs. Richer\n    // metadata (formatters, default RPC) is only available for viem-known chains;\n    // RPC-needing paths already accept a caller-supplied transport.\n    return defineChain({\n        id: chainId,\n        name: `Chain ${chainId}`,\n        nativeCurrency: { name: 'Ether', symbol: 'ETH', decimals: 18 },\n        rpcUrls: { default: { http: [] } },\n    });\n}\nexport function getChainReference(chainId) {\n    const caip2 = formatCaip2(chainId);\n    if (caip2.startsWith('eip155:') || isHyperCoreWireId(chainId)) {\n        return {\n            kind: 'evm',\n            id: chainId,\n            caip2: caip2,\n        };\n    }\n    const separator = caip2.indexOf(':');\n    return {\n        kind: 'non-evm',\n        namespace: caip2.slice(0, separator),\n        reference: caip2.slice(separator + 1),\n        caip2: caip2,\n    };\n}\n","import { keccak256, stringToHex } from 'viem';\nimport { planModuleSetup } from '../modules/plan.js';\nimport { resolveValidator } from '../modules/validators/resolve.js';\nimport { orderWebauthnCredentials, toWebauthnInstallCredentials, webauthnDefinitionCredentials, } from '../modules/validators/webauthn.js';\nimport { accountSupportsSaltSearch, assertPasskeySetInstallable, selectPasskeyAccount, } from './passkey-install.js';\nimport { createAccountAdapter } from './registry.js';\nfunction passkeyOwner(owner) {\n    return owner?.kind === 'passkey' ? owner : undefined;\n}\nfunction setupFingerprint(input) {\n    return keccak256(stringToHex(JSON.stringify(input, (_key, value) => typeof value === 'bigint' ? `${value}n` : value)));\n}\nexport function createAccountConstruction(input) {\n    const material = input.material;\n    const passkey = passkeyOwner(material.owner);\n    // Caller-pinned init data carrying a factory is used verbatim, so neither the\n    // credential order nor the salt has any effect on the deployed account.\n    const pinned = material.initData !== undefined && 'factory' in material.initData;\n    const knownAddress = material.eoa?.address ?? material.initData?.address;\n    const credentials = passkey && !pinned\n        ? toWebauthnInstallCredentials(webauthnDefinitionCredentials(passkey))\n        : undefined;\n    const searchable = credentials !== undefined &&\n        credentials.length > 1 &&\n        knownAddress === undefined &&\n        accountSupportsSaltSearch(material.account);\n    if (credentials && (knownAddress !== undefined || searchable)) {\n        assertPasskeySetInstallable({ credentials, atDeployment: searchable });\n    }\n    const ordering = knownAddress\n        ? // The address is already fixed (EIP-7702 adoption or a caller-supplied\n            // address), so the exact order the validator requires is computable.\n            { kind: 'credential-id', account: knownAddress }\n        : searchable\n            ? { kind: 'canonical' }\n            : undefined;\n    const ownerModule = material.owner\n        ? resolveValidator(material.owner, ordering)\n        : undefined;\n    if (!ownerModule && material.account.kind !== 'eoa') {\n        throw new Error('Smart account owner is required');\n    }\n    const setup = input.setup ??\n        (ownerModule\n            ? planModuleSetup({\n                accountKind: material.account.kind,\n                owner: ownerModule,\n                configured: material.modules,\n                environment: material.sessions.environment,\n                sessions: material.sessions,\n            })\n            : { validators: [], executors: [], hooks: [], fallbacks: [] });\n    const base = {\n        account: material.account,\n        ...(material.owner ? { owner: material.owner } : {}),\n        modules: material.modules,\n        setup,\n        sessions: {\n            enabled: material.sessions.enabled,\n            environment: material.sessions.environment,\n        },\n        ...(material.initData ? { initData: material.initData } : {}),\n        ...(material.eoa ? { eoa: material.eoa } : {}),\n        chain: input.chain,\n        deployed: input.deployed,\n    };\n    if (!searchable || !credentials)\n        return base;\n    // The module setup is salt-independent, so only the account definition varies\n    // across attempts.\n    const account = selectPasskeyAccount({\n        account: material.account,\n        credentials: orderWebauthnCredentials(credentials, { kind: 'canonical' }),\n        fingerprint: setupFingerprint({ account: material.account, setup }),\n        deriveAddress: (candidate) => {\n            const construction = { ...base, account: candidate };\n            return createAccountAdapter(construction).getIdentity(construction)\n                .address;\n        },\n    });\n    return { ...base, account };\n}\n","import { encodeAbiParameters } from 'viem';\nimport { getIntentExecutorModule } from './intent-executor.js';\nimport { normalizeModules } from './normalize.js';\nimport { resolveSmartSessionModule } from './validators/smart-sessions/module.js';\nexport function planModuleOperation(module, operation, encodeAccountCall) {\n    return {\n        module,\n        operation,\n        accountCallData: encodeAccountCall(module, operation),\n    };\n}\nconst SAFE_SESSION_COMPATIBILITY_FALLBACK_ADDRESS = '0x000000000052e9685932845660777DF43C2dC496';\nexport function planModuleSetup(input) {\n    const custom = normalizeModules(input.configured);\n    const session = resolveSmartSessionModule({\n        enabled: input.sessions.enabled,\n        address: input.sessions.module,\n        environment: input.environment,\n    });\n    const validators = [\n        input.owner,\n        ...(session ? [session] : []),\n        ...custom.filter((module) => module.kind === 'validator'),\n    ];\n    const executors = [\n        getIntentExecutorModule(input.environment),\n        ...custom.filter((module) => module.kind === 'executor'),\n    ];\n    const fallbacks = [];\n    if (input.sessions.enabled && input.accountKind === 'safe') {\n        fallbacks.push({\n            kind: 'fallback',\n            address: input.sessions.compatibilityFallback ??\n                SAFE_SESSION_COMPATIBILITY_FALLBACK_ADDRESS,\n            initData: encodeAbiParameters([\n                { name: 'selector', type: 'bytes4' },\n                { name: 'flags', type: 'bytes1' },\n                { name: 'data', type: 'bytes' },\n            ], ['0x84b0196e', '0xfe', '0x']),\n            deInitData: '0x',\n            additionalContext: '0x',\n        });\n    }\n    fallbacks.push(...custom.filter((module) => module.kind === 'fallback'));\n    return {\n        validators,\n        executors,\n        fallbacks,\n        hooks: custom.filter((module) => module.kind === 'hook'),\n    };\n}\n","export const INTENT_EXECUTOR_ADDRESS = '0x00000000005aD9ce1f5035FD62CA96CEf16AdAAF';\nexport const INTENT_EXECUTOR_ADDRESS_DEV = '0xbf9b5b917a83f8adac17b0752846d41d8d7b7e17';\nexport function getIntentExecutorModule(environment) {\n    return {\n        kind: 'executor',\n        address: environment === 'development'\n            ? INTENT_EXECUTOR_ADDRESS_DEV\n            : INTENT_EXECUTOR_ADDRESS,\n        initData: '0x',\n        deInitData: '0x',\n        additionalContext: '0x',\n    };\n}\n","function materializeData(selection) {\n    return selection.source === 'explicit' ? selection.value : '0x';\n}\nexport function normalizeModule(module) {\n    return {\n        kind: module.kind,\n        address: module.address,\n        initData: materializeData(module.initData),\n        deInitData: materializeData(module.deInitData),\n        additionalContext: materializeData(module.additionalContext),\n    };\n}\nexport function normalizeModules(modules) {\n    return modules.map(normalizeModule);\n}\n","export const SMART_SESSION_EMISSARY_ADDRESS = '0xad568b3f825a8d5ffc06dd3253526b64d810ae89';\nexport const SMART_SESSION_EMISSARY_ADDRESS_DEV = '0x60731de80d78548875f8a67c4fec2a8660194e0c';\nexport function getSmartSessionEmissaryAddress(environment) {\n    return environment === 'development'\n        ? SMART_SESSION_EMISSARY_ADDRESS_DEV\n        : SMART_SESSION_EMISSARY_ADDRESS;\n}\nexport function resolveSmartSessionModule(input) {\n    if (!input.enabled)\n        return undefined;\n    return {\n        kind: 'validator',\n        address: input.address ?? getSmartSessionEmissaryAddress(input.environment),\n        initData: '0x',\n        deInitData: '0x',\n        additionalContext: '0x',\n    };\n}\n","import { encodeAbiParameters, maxUint48 } from 'viem';\nimport { compareHexValues } from './ordering.js';\nexport const ENS_HCA_MODULE = '0x5049ecBd4d961aE6DFEED9b7ccCe7f026454970E';\nfunction ensOwners(definition) {\n    return definition.owners\n        .map((owner) => {\n        if (owner.kind !== 'ens') {\n            throw new Error('ENS validator contains a non-ENS owner');\n        }\n        return {\n            addr: owner.account.address.toLowerCase(),\n            expiration: owner.expiration\n                ? Math.floor(owner.expiration.getTime() / 1000)\n                : Number(maxUint48),\n        };\n    })\n        .sort((left, right) => compareHexValues(left.addr, right.addr));\n}\n/**\n * The configuration the ENS validator's stateless path expects: the threshold\n * followed by the sorted owner addresses, without expirations. That path\n * deliberately skips the expiration check, because expiry lives in the\n * validator's own storage and a stateless caller has none — so an expired owner\n * still satisfies an ENS factor nested under multi-factor.\n */\nexport function encodeEnsStatelessData(definition) {\n    return encodeAbiParameters([\n        { name: 'threshold', type: 'uint256' },\n        { name: 'owners', type: 'address[]' },\n    ], [\n        BigInt(definition.threshold),\n        ensOwners(definition).map((owner) => owner.addr),\n    ]);\n}\nexport function resolveEnsValidator(definition) {\n    return {\n        kind: 'validator',\n        address: ENS_HCA_MODULE,\n        initData: encodeAbiParameters([\n            { name: 'threshold', type: 'uint256' },\n            {\n                name: 'owners',\n                type: 'tuple[]',\n                components: [\n                    { name: 'addr', type: 'address' },\n                    { name: 'expiration', type: 'uint48' },\n                ],\n            },\n        ], [BigInt(definition.threshold), ensOwners(definition)]),\n        deInitData: '0x',\n        additionalContext: '0x',\n    };\n}\n","// Order by value, never by host collation: `localeCompare` sorts `0xaa…` after\n// `0xb1…` on Danish-family locales, which would change derived addresses and\n// break the validators' ascending-order requirement.\nexport function compareHexValues(left, right) {\n    const leftValue = BigInt(left);\n    const rightValue = BigInt(right);\n    if (leftValue === rightValue) {\n        return 0;\n    }\n    return leftValue < rightValue ? -1 : 1;\n}\n","import { concat, encodeAbiParameters, encodePacked, pad, toHex, } from 'viem';\nexport const MULTI_FACTOR_VALIDATOR_ADDRESS = '0xf6bdf42c9be18ceca5c06c42a43daf7fbbe7896b';\nexport const MULTI_FACTOR_VALIDATOR_V2_ADDRESS = '0x0000007261E4E2F1a892A58fd0708c9321e76020';\nexport function encodeValidatorId(id) {\n    return pad(typeof id === 'number' ? toHex(id) : id, { size: 12 });\n}\nexport function resolveMultiFactorValidator(definition, resolveAtomic) {\n    const validators = definition.validators.map((validator) => {\n        const { module, statelessData } = resolveAtomic(validator);\n        return {\n            packedValidatorAndId: concat([\n                encodeValidatorId(validator.publicId),\n                module.address,\n            ]),\n            data: statelessData,\n        };\n    });\n    return {\n        kind: 'validator',\n        address: definition.module.source === 'explicit'\n            ? definition.module.address\n            : MULTI_FACTOR_VALIDATOR_ADDRESS,\n        initData: encodePacked(['uint8', 'bytes'], [\n            definition.threshold,\n            encodeAbiParameters([\n                {\n                    name: 'validators',\n                    type: 'tuple[]',\n                    components: [\n                        { name: 'packedValidatorAndId', type: 'bytes32' },\n                        { name: 'data', type: 'bytes' },\n                    ],\n                },\n            ], [validators]),\n        ]),\n        deInitData: '0x',\n        additionalContext: '0x',\n    };\n}\nexport function encodeMultiFactorContribution(input) {\n    if (input.threshold < 1 || input.threshold > input.factorOrder.length) {\n        throw new Error('Validator threshold is outside the configured factor set');\n    }\n    const configured = new Set(input.factorOrder);\n    const contributions = new Map();\n    for (const contribution of input.contributions) {\n        if (!configured.has(contribution.factorId)) {\n            throw new Error(`Unknown validator factor ${contribution.factorId}`);\n        }\n        if (contributions.has(contribution.factorId)) {\n            throw new Error(`Duplicate validator factor ${contribution.factorId}`);\n        }\n        contributions.set(contribution.factorId, contribution);\n    }\n    const ordered = input.factorOrder.flatMap((factorId) => {\n        const contribution = contributions.get(factorId);\n        return contribution ? [contribution] : [];\n    });\n    if (ordered.length < input.threshold) {\n        throw new Error(`Insufficient validator contributions: required ${input.threshold}, received ${ordered.length}`);\n    }\n    return encodeAbiParameters([\n        {\n            name: 'validators',\n            type: 'tuple[]',\n            components: [\n                { name: 'packedValidatorAndId', type: 'bytes32' },\n                { name: 'data', type: 'bytes' },\n            ],\n        },\n    ], [\n        ordered.map((contribution) => ({\n            packedValidatorAndId: concat([\n                encodeValidatorId(contribution.publicId),\n                contribution.validator,\n            ]),\n            data: contribution.contribution,\n        })),\n    ]);\n}\n","import { concat, encodeAbiParameters, hashTypedData, keccak256, size, toHex, } from 'viem';\nimport { compareHexValues } from './ordering.js';\nconst MAX_QUORUM_OWNERS = 32;\nconst MAX_UINT96 = (1n << 96n) - 1n;\nconst QUORUM_MESSAGE_TYPEHASH = keccak256(toHex('WeightedOwnableValidatorMessage(address validator,uint256 chainId,address account,bytes32 hash)'));\n/** Bind an ERC-1271 digest to its Quorum module, chain, and smart account. */\nexport function getQuorumSignableHash(input) {\n    return keccak256(encodeAbiParameters([\n        { type: 'bytes32' },\n        { type: 'address' },\n        { type: 'uint256' },\n        { type: 'address' },\n        { type: 'bytes32' },\n    ], [\n        QUORUM_MESSAGE_TYPEHASH,\n        input.validator,\n        BigInt(input.chainId),\n        input.account,\n        input.hash,\n    ]));\n}\n/** Build account-bound leaves and Solady-compatible sorted-pair proofs. */\nexport function buildQuorumMerkleTree(operations) {\n    if (operations.length < 2) {\n        throw new Error('Quorum Merkle signing requires at least two operations');\n    }\n    const leaves = operations.map(({ account, digest }) => keccak256(encodeAbiParameters([{ type: 'address' }, { type: 'bytes32' }], [account, digest])));\n    const layers = [leaves];\n    while (layers.at(-1).length > 1) {\n        const current = layers.at(-1);\n        const next = [];\n        for (let index = 0; index < current.length; index += 2) {\n            next.push(index + 1 < current.length\n                ? hashQuorumMerklePair(current[index], current[index + 1])\n                : current[index]);\n        }\n        layers.push(next);\n    }\n    const root = layers.at(-1)[0];\n    return {\n        root,\n        operations: operations.map(({ account, digest }, leafIndex) => {\n            const proof = [];\n            let index = leafIndex;\n            for (const layer of layers.slice(0, -1)) {\n                const siblingIndex = index % 2 === 0 ? index + 1 : index - 1;\n                if (siblingIndex < layer.length)\n                    proof.push(layer[siblingIndex]);\n                index = Math.floor(index / 2);\n            }\n            return { account, digest, leaf: leaves[leafIndex], root, proof };\n        }),\n    };\n}\n/** Hash the chain-agnostic EIP-712 root message signed by every owner. */\nexport function getQuorumMerkleRootSignableHash(input) {\n    return hashTypedData({\n        domain: {\n            name: 'Quorum Signer',\n            version: '1',\n            verifyingContract: input.validator,\n        },\n        types: {\n            WeightedMerkleRoot: [{ name: 'root', type: 'bytes32' }],\n        },\n        primaryType: 'WeightedMerkleRoot',\n        message: { root: input.root },\n    });\n}\nfunction hashQuorumMerklePair(left, right) {\n    return compareHexValues(left, right) < 0\n        ? keccak256(concat([left, right]))\n        : keccak256(concat([right, left]));\n}\nconst MAX_SIGNATURE_LENGTH = 65_535;\nconst QUORUM_MOCK_SIGNATURE = `0x${'00'.repeat(64)}1b`;\n/** Resolve Quorum Signer installation data from a weighted owner definition. */\nexport function resolveQuorumValidator(definition) {\n    if (definition.kind !== 'quorum') {\n        throw new Error('Quorum resolver received a non-quorum validator');\n    }\n    const owners = resolveOwners(definition).sort((left, right) => compareHexValues(left.signer, right.signer));\n    const thresholdWeight = requireThresholdWeight(definition);\n    validateQuorumConfig(owners, thresholdWeight);\n    if (definition.module.source !== 'explicit') {\n        throw new Error('Quorum validator requires a deployed module address');\n    }\n    return {\n        kind: 'validator',\n        address: definition.module.address,\n        initData: encodeAbiParameters([\n            { name: 'thresholdWeight', type: 'uint256' },\n            {\n                name: 'owners',\n                type: 'tuple[]',\n                components: [\n                    { name: 'addr', type: 'address' },\n                    { name: 'weight', type: 'uint96' },\n                ],\n            },\n        ], [\n            thresholdWeight,\n            owners.map(({ signer, weight }) => ({ addr: signer, weight })),\n        ]),\n        deInitData: '0x',\n        additionalContext: '0x',\n    };\n}\n/** Encode a regular Quorum Signer envelope from owner signature contributions. */\nexport function encodeQuorumValidatorContribution(input) {\n    return concat(['0x00', encodeSelectedQuorumSignatures(input)]);\n}\nfunction encodeSelectedQuorumSignatures(input) {\n    validateQuorumConfig(input.owners, input.thresholdWeight);\n    const configured = new Map(input.owners.map((owner) => [owner.ownerId, owner]));\n    const contributions = new Map();\n    for (const contribution of input.contributions) {\n        if (!configured.has(contribution.ownerId)) {\n            throw new Error(`Unknown validator owner ${contribution.ownerId}`);\n        }\n        if (contributions.has(contribution.ownerId)) {\n            throw new Error(`Duplicate validator owner ${contribution.ownerId}`);\n        }\n        contributions.set(contribution.ownerId, contribution.signature);\n    }\n    const selected = input.owners\n        .filter((owner) => contributions.has(owner.ownerId))\n        .sort((left, right) => compareAddresses(left.signer, right.signer));\n    const signedWeight = selected.reduce((sum, owner) => sum + owner.weight, 0n);\n    if (signedWeight < input.thresholdWeight) {\n        throw new Error(`Insufficient validator contribution weight: required ${input.thresholdWeight}, received ${signedWeight}`);\n    }\n    return encodeQuorumEntries(selected.map((owner) => ({\n        signer: owner.signer,\n        signature: contributions.get(owner.ownerId),\n    })));\n}\n/** Encode one Merkle proof with an already packed weighted quorum. */\nexport function encodeQuorumMerkleEnvelope(input) {\n    if (input.proof.proof.length < 1 || input.proof.proof.length > 32) {\n        throw new Error('Quorum Merkle proof length must be between 1 and 32');\n    }\n    if (input.signatures === '0x') {\n        throw new Error('Quorum Merkle signatures must not be empty');\n    }\n    return concat([\n        toHex(input.proof.proof.length, { size: 1 }),\n        input.proof.root,\n        ...input.proof.proof,\n        input.signatures,\n    ]);\n}\n/** Encode weighted entries without the regular or Merkle envelope prefix. */\nexport function encodeQuorumWeightedSignatures(input) {\n    return encodeSelectedQuorumSignatures(input);\n}\n/** Build a structurally valid maximum-cost signature for bundler gas estimation. */\nexport function encodeQuorumMockSignature(definition) {\n    if (definition.kind !== 'quorum') {\n        throw new Error('Quorum mock signature requires a quorum validator');\n    }\n    const owners = resolveOwners(definition);\n    validateQuorumConfig(owners, requireThresholdWeight(definition));\n    return concat([\n        '0x00',\n        encodeQuorumEntries(owners\n            .map(({ signer }) => ({ signer, signature: QUORUM_MOCK_SIGNATURE }))\n            .sort((left, right) => compareAddresses(left.signer, right.signer))),\n    ]);\n}\nfunction encodeQuorumEntries(entries) {\n    if (entries.length === 0)\n        throw new Error('Quorum signature must not be empty');\n    let previous;\n    const packed = entries.map(({ signer, signature }) => {\n        if (previous && compareAddresses(previous, signer) >= 0) {\n            throw new Error('Quorum signer addresses must be strictly sorted and unique');\n        }\n        previous = signer;\n        const signatureLength = size(signature);\n        if (signatureLength > MAX_SIGNATURE_LENGTH) {\n            throw new Error(`Quorum inner signature exceeds ${MAX_SIGNATURE_LENGTH} bytes`);\n        }\n        return concat([signer, toHex(signatureLength, { size: 2 }), signature]);\n    });\n    return concat(packed);\n}\nfunction resolveOwners(definition) {\n    return definition.owners.map((owner) => {\n        if (owner.kind === 'webauthn' || owner.weight === undefined) {\n            throw new Error('Quorum validator requires weighted ECDSA owners');\n        }\n        return {\n            ownerId: owner.id,\n            signer: owner.account.address,\n            weight: owner.weight,\n        };\n    });\n}\nfunction requireThresholdWeight(definition) {\n    if (definition.thresholdWeight === undefined) {\n        throw new Error('Quorum validator threshold weight is missing');\n    }\n    return definition.thresholdWeight;\n}\nfunction validateQuorumConfig(owners, thresholdWeight) {\n    if (owners.length < 1 || owners.length > MAX_QUORUM_OWNERS) {\n        throw new Error(`Quorum owners length must be between 1 and ${MAX_QUORUM_OWNERS}`);\n    }\n    const seen = new Set();\n    let totalWeight = 0n;\n    for (const [index, owner] of owners.entries()) {\n        const signer = owner.signer.toLowerCase();\n        if (signer === '0x0000000000000000000000000000000000000000') {\n            throw new Error(`Quorum owner ${index} cannot be the zero address`);\n        }\n        if (seen.has(signer))\n            throw new Error(`Duplicate quorum owner ${owner.signer}`);\n        seen.add(signer);\n        if (owner.weight <= 0n || owner.weight > MAX_UINT96) {\n            throw new Error(`Quorum owner ${owner.signer} weight must fit uint96 and be non-zero`);\n        }\n        totalWeight += owner.weight;\n    }\n    if (thresholdWeight <= 0n || thresholdWeight > totalWeight) {\n        throw new Error(`Quorum threshold weight must be between 1 and total owner weight ${totalWeight}`);\n    }\n}\nfunction compareAddresses(left, right) {\n    return compareHexValues(left, right);\n}\n","import { bytesToHex, decodeAbiParameters, encodeAbiParameters, hexToBytes, keccak256, stringToBytes, } from 'viem';\nimport { compareHexValues } from './ordering.js';\nexport const WEBAUTHN_VALIDATOR_ADDRESS = '0x0000000000578c4cb0e472a5462da43c495c3f33';\nexport const WEBAUTHN_V0_VALIDATOR_ADDRESS = WEBAUTHN_VALIDATOR_ADDRESS;\n// The account address carried by a stateless WebAuthn configuration. The\n// validator only uses it to re-derive the credential IDs in the same blob and\n// check they match, never to read storage, so any constant works as long as the\n// IDs are derived from it. The real account address cannot be used: it is\n// derived from the init data that would contain it.\nexport const WEBAUTHN_STATELESS_ACCOUNT = '0x0000000000000000000000000000000000000000';\nexport const WEBAUTHN_MOCK_SIGNATURE = '0x0000000000000000000000000000000000000000000000000000000000000060000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000001b9b86eb98fda3ed4d797d9e690588dfadf17b329a76a47cec935bebf92d7ddc80000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000c00000000000000000000000000000000000000000000000000000000000000120000000000000000000000000000000000000000000000000000000000000001700000000000000000000000000000000000000000000000000000000000000019b2e9410bb6850f9f660a03d609d5a844fb96bcdc87a15139b03ee22c70f469100d2b865a215c3bf786387064effa8fcedcb1d625b5148f8a1236d5e3ff11acf000000000000000000000000000000000000000000000000000000000000002549960de5880e8c687434170f6476605b8fe4aeb9a28632c7995cf3ba831d9763050000000100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000867b2274797065223a22776562617574686e2e676574222c226368616c6c656e6765223a22396a4546696a75684557724d34534f572d7443684a625545484550343456636a634a2d42716f3166544d38222c226f726967696e223a22687474703a2f2f6c6f63616c686f73743a38303830222c2263726f73734f726967696e223a66616c73657d0000000000000000000000000000000000000000000000000000';\nconst P256_CURVE_ORDER = 0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551n;\nconst P256_HALF_CURVE_ORDER = P256_CURVE_ORDER / 2n;\nconst WEBAUTHN_TYPE_LITERAL = stringToBytes('\"type\":\"webauthn.get\"');\nconst WEBAUTHN_CHALLENGE_LITERAL = stringToBytes('\"challenge\":\"');\nfunction findClientDataLiteral(clientData, literal, name) {\n    const lastStart = clientData.length - literal.length;\n    for (let start = 0; start <= lastStart; start++) {\n        if (literal.every((byte, offset) => clientData[start + offset] === byte)) {\n            return BigInt(start);\n        }\n    }\n    throw new Error(`WebAuthn clientDataJSON is missing the required ${name} field`);\n}\nfunction normalizeP256S(s) {\n    return s > P256_HALF_CURVE_ORDER ? P256_CURVE_ORDER - s : s;\n}\nfunction normalizeWebauthnSignature(signature) {\n    const clientData = stringToBytes(signature.clientDataJSON);\n    return {\n        ...signature,\n        challengeIndex: findClientDataLiteral(clientData, WEBAUTHN_CHALLENGE_LITERAL, 'challenge'),\n        typeIndex: findClientDataLiteral(clientData, WEBAUTHN_TYPE_LITERAL, 'type'),\n        s: normalizeP256S(signature.s),\n    };\n}\nfunction normalizeWebauthnSignatureV0(signature) {\n    const clientData = stringToBytes(signature.clientDataJSON);\n    return {\n        ...signature,\n        typeIndex: findClientDataLiteral(clientData, WEBAUTHN_TYPE_LITERAL, 'type'),\n        s: normalizeP256S(signature.s),\n    };\n}\nexport function parseWebauthnPublicKey(publicKey) {\n    const bytes = typeof publicKey === 'string' ? hexToBytes(publicKey) : publicKey;\n    const offset = bytes.length === 65 ? 1 : 0;\n    const prefix = offset === 1 ? bytes[0] : undefined;\n    return {\n        ...(prefix === undefined ? {} : { prefix }),\n        x: BigInt(bytesToHex(bytes.slice(offset, 32 + offset))),\n        y: BigInt(bytesToHex(bytes.slice(32 + offset, 64 + offset))),\n    };\n}\nexport function parseWebauthnSignature(signature) {\n    const bytes = typeof signature === 'string' ? hexToBytes(signature) : signature;\n    return {\n        r: BigInt(bytesToHex(bytes.slice(0, 32))),\n        s: BigInt(bytesToHex(bytes.slice(32, 64))),\n    };\n}\nexport function generateWebauthnCredentialId(pubKeyX, pubKeyY, account) {\n    return keccak256(encodeAbiParameters([{ type: 'uint256' }, { type: 'uint256' }, { type: 'address' }], [pubKeyX, pubKeyY, account]));\n}\nconst WEBAUTHN_AUTH_ABI = {\n    type: 'tuple[]',\n    name: 'webAuthns',\n    components: [\n        { type: 'bytes', name: 'authenticatorData' },\n        { type: 'string', name: 'clientDataJSON' },\n        { type: 'uint256', name: 'challengeIndex' },\n        { type: 'uint256', name: 'typeIndex' },\n        { type: 'uint256', name: 'r' },\n        { type: 'uint256', name: 's' },\n    ],\n};\n// The same mock assertion `WEBAUTHN_MOCK_SIGNATURE` carries, in the shape the\n// stateless path expects, so a passkey factor can be gas-estimated.\nexport function webauthnStatelessMockSignature() {\n    return encodeAbiParameters([WEBAUTHN_AUTH_ABI], [\n        decodeAbiParameters([\n            { type: 'bytes32[]', name: 'credIds' },\n            { type: 'bool', name: 'usePrecompile' },\n            WEBAUTHN_AUTH_ABI,\n        ], WEBAUTHN_MOCK_SIGNATURE)[2],\n    ]);\n}\nexport function encodeWebauthnSignatures(credentialIds, usePrecompile, signatures) {\n    const ordered = credentialIds\n        .map((credentialId, index) => ({\n        credentialId,\n        signature: normalizeWebauthnSignature(signatures[index]),\n    }))\n        .sort((left, right) => compareHexValues(left.credentialId, right.credentialId));\n    return encodeAbiParameters([\n        { type: 'bytes32[]', name: 'credIds' },\n        { type: 'bool', name: 'usePrecompile' },\n        WEBAUTHN_AUTH_ABI,\n    ], [\n        ordered.map(({ credentialId }) => credentialId),\n        usePrecompile,\n        ordered.map(({ signature }) => signature),\n    ]);\n}\n// The signature format the validator's stateless path expects: the assertions\n// alone, paired with the configuration's credentials by position.\nexport function encodeWebauthnStatelessSignatures(signatures) {\n    return encodeAbiParameters([WEBAUTHN_AUTH_ABI], [signatures.map(normalizeWebauthnSignature)]);\n}\nexport function encodeWebauthnSignatureV0(signature, usePrecompile) {\n    const normalized = normalizeWebauthnSignatureV0(signature);\n    return encodeAbiParameters([\n        { type: 'bytes', name: 'authenticatorData' },\n        { type: 'string', name: 'clientDataJSON' },\n        { type: 'uint256', name: 'responseTypeLocation' },\n        { type: 'uint256', name: 'r' },\n        { type: 'uint256', name: 's' },\n        { type: 'bool', name: 'usePrecompiled' },\n    ], [\n        normalized.authenticatorData,\n        normalized.clientDataJSON,\n        normalized.typeIndex,\n        normalized.r,\n        normalized.s,\n        usePrecompile,\n    ]);\n}\n// Orders owners the way the stateless configuration lays their credentials out.\nfunction statelessCredentialOrder(credentials) {\n    return [...credentials]\n        .map((credential) => {\n        const publicKey = parseWebauthnPublicKey(credential.publicKey);\n        return {\n            ownerId: credential.ownerId,\n            credentialId: generateWebauthnCredentialId(publicKey.x, publicKey.y, WEBAUTHN_STATELESS_ACCOUNT),\n        };\n    })\n        .sort((left, right) => compareHexValues(left.credentialId, right.credentialId))\n        .map(({ ownerId }) => ownerId);\n}\nexport function encodeWebauthnValidatorContribution(input) {\n    if (input.threshold < 1 || input.threshold > input.ownerOrder.length) {\n        throw new Error('Validator threshold is outside the configured owner set');\n    }\n    const configured = new Set(input.ownerOrder);\n    const contributions = new Map();\n    for (const contribution of input.contributions) {\n        if (!configured.has(contribution.ownerId)) {\n            throw new Error(`Unknown validator owner ${contribution.ownerId}`);\n        }\n        if (contributions.has(contribution.ownerId)) {\n            throw new Error(`Duplicate validator owner ${contribution.ownerId}`);\n        }\n        contributions.set(contribution.ownerId, contribution);\n    }\n    const ordered = input.ownerOrder.flatMap((ownerId) => {\n        const contribution = contributions.get(ownerId);\n        return contribution ? [contribution] : [];\n    });\n    if (ordered.length < input.threshold) {\n        throw new Error(`Insufficient validator contributions: required ${input.threshold}, received ${ordered.length}`);\n    }\n    const signatures = ordered.map((contribution) => ({\n        authenticatorData: contribution.authenticatorData,\n        clientDataJSON: contribution.clientDataJSON,\n        challengeIndex: BigInt(contribution.challengeIndex),\n        typeIndex: BigInt(contribution.typeIndex),\n        ...parseWebauthnSignature(contribution.signature),\n    }));\n    if (input.format === 'v0') {\n        if (signatures.length !== 1) {\n            throw new Error('WebAuthn V0 accepts exactly one contribution');\n        }\n        return encodeWebauthnSignatureV0(signatures[0], input.usePrecompile);\n    }\n    if (input.format === 'stateless') {\n        if (!input.credentials) {\n            throw new Error('Stateless WebAuthn contributions require the configured credentials');\n        }\n        const configuredOrder = statelessCredentialOrder(input.credentials);\n        const signingOrder = statelessCredentialOrder(ordered.map((contribution) => ({\n            ownerId: contribution.ownerId,\n            publicKey: contribution.publicKey,\n        })));\n        const expected = configuredOrder.slice(0, signingOrder.length);\n        if (signingOrder.some((ownerId, index) => expected[index] !== ownerId)) {\n            throw new Error('A WebAuthn factor pairs each signature with the credential at the same position, so a partial signer set must be the lowest-ordered credentials of that factor');\n        }\n        const byOwnerId = new Map(ordered.map((contribution, index) => [\n            contribution.ownerId,\n            signatures[index],\n        ]));\n        return encodeWebauthnStatelessSignatures(signingOrder.map((ownerId) => byOwnerId.get(ownerId)));\n    }\n    const credentialIds = ordered.map((contribution) => {\n        const publicKey = parseWebauthnPublicKey(contribution.publicKey);\n        return generateWebauthnCredentialId(publicKey.x, publicKey.y, input.account);\n    });\n    return encodeWebauthnSignatures(credentialIds, input.usePrecompile, signatures);\n}\nexport function toWebauthnInstallCredentials(credentials) {\n    return credentials.map((credential) => {\n        const publicKey = typeof credential.pubKey === 'object' &&\n            !(credential.pubKey instanceof Uint8Array)\n            ? credential.pubKey\n            : parseWebauthnPublicKey(credential.pubKey);\n        return {\n            pubKeyX: publicKey.x,\n            pubKeyY: publicKey.y,\n            requireUV: false,\n        };\n    });\n}\nfunction comparePublicKeys(left, right) {\n    if (left.pubKeyX !== right.pubKeyX) {\n        return left.pubKeyX < right.pubKeyX ? -1 : 1;\n    }\n    if (left.pubKeyY === right.pubKeyY)\n        return 0;\n    return left.pubKeyY < right.pubKeyY ? -1 : 1;\n}\nexport function orderWebauthnCredentials(credentials, ordering) {\n    switch (ordering.kind) {\n        case 'as-provided':\n            return credentials;\n        case 'canonical':\n            return [...credentials].sort(comparePublicKeys);\n        case 'credential-id': {\n            const account = ordering.account;\n            return [...credentials].sort((left, right) => compareHexValues(generateWebauthnCredentialId(left.pubKeyX, left.pubKeyY, account), generateWebauthnCredentialId(right.pubKeyX, right.pubKeyY, account)));\n        }\n    }\n}\n// The validator's `onInstall` predicate: credential IDs strictly ascending,\n// which also rules out duplicates.\nexport function webauthnCredentialsAreAscending(credentials, account) {\n    let previous;\n    for (const credential of credentials) {\n        const credentialId = generateWebauthnCredentialId(credential.pubKeyX, credential.pubKeyY, account);\n        if (previous !== undefined &&\n            compareHexValues(previous, credentialId) >= 0) {\n            return false;\n        }\n        previous = credentialId;\n    }\n    return true;\n}\nexport function hasDuplicateWebauthnCredentials(credentials) {\n    const seen = new Set();\n    for (const credential of credentials) {\n        const key = `${credential.pubKeyX}:${credential.pubKeyY}`;\n        if (seen.has(key))\n            return true;\n        seen.add(key);\n    }\n    return false;\n}\nexport function resolveWebauthnCredentials(input) {\n    const credentials = orderWebauthnCredentials(toWebauthnInstallCredentials(input.credentials), input.ordering ?? { kind: 'as-provided' });\n    return {\n        kind: 'validator',\n        address: input.address ?? WEBAUTHN_VALIDATOR_ADDRESS,\n        initData: encodeAbiParameters([\n            { name: 'threshold', type: 'uint256' },\n            {\n                name: 'credentials',\n                type: 'tuple[]',\n                components: [\n                    { name: 'pubKeyX', type: 'uint256' },\n                    { name: 'pubKeyY', type: 'uint256' },\n                    { name: 'requireUV', type: 'bool' },\n                ],\n            },\n        ], [BigInt(input.threshold), [...credentials]]),\n        deInitData: '0x',\n        additionalContext: '0x',\n    };\n}\nexport function webauthnDefinitionCredentials(definition) {\n    return definition.owners.map((owner) => {\n        if (owner.kind !== 'webauthn') {\n            throw new Error('WebAuthn validator contains a non-WebAuthn owner');\n        }\n        return {\n            pubKey: owner.account.publicKey,\n            authenticatorId: owner.account.id,\n        };\n    });\n}\n/**\n * The configuration `WebAuthnValidator.validateSignatureWithData` expects, which\n * is *not* the validator's install data: a verification context plus the account\n * the credential IDs were derived from. Multi-factor stores this blob verbatim\n * and hands it back on every factor validation.\n *\n * Written for the deployed validator ({@link WEBAUTHN_VALIDATOR_ADDRESS}); a\n * future deployment that drops the account from credential-ID derivation would\n * need its own encoder.\n */\nexport function encodeWebauthnStatelessData(input) {\n    const credentials = orderWebauthnCredentials(toWebauthnInstallCredentials(input.credentials), { kind: 'credential-id', account: WEBAUTHN_STATELESS_ACCOUNT });\n    return encodeAbiParameters([\n        {\n            name: 'context',\n            type: 'tuple',\n            components: [\n                { name: 'usePrecompile', type: 'bool' },\n                { name: 'threshold', type: 'uint256' },\n                { name: 'credentialIds', type: 'bytes32[]' },\n                {\n                    name: 'credentialData',\n                    type: 'tuple[]',\n                    components: [\n                        { name: 'pubKeyX', type: 'uint256' },\n                        { name: 'pubKeyY', type: 'uint256' },\n                        { name: 'requireUV', type: 'bool' },\n                    ],\n                },\n            ],\n        },\n        { name: 'account', type: 'address' },\n    ], [\n        {\n            usePrecompile: input.usePrecompile ?? false,\n            threshold: BigInt(input.threshold),\n            credentialIds: credentials.map((credential) => generateWebauthnCredentialId(credential.pubKeyX, credential.pubKeyY, WEBAUTHN_STATELESS_ACCOUNT)),\n            credentialData: [...credentials],\n        },\n        WEBAUTHN_STATELESS_ACCOUNT,\n    ]);\n}\n// A passkey factor signs through the sub-validator's stateless path: the\n// assertions alone, paired with credentials derived from the pinned account.\nexport function webauthnStatelessCodecContext(definition) {\n    return {\n        account: WEBAUTHN_STATELESS_ACCOUNT,\n        usePrecompile: false,\n        format: 'stateless',\n        credentials: definition.owners.flatMap((owner) => owner.kind === 'webauthn'\n            ? [{ ownerId: owner.id, publicKey: owner.account.publicKey }]\n            : []),\n    };\n}\nexport function resolveWebauthnStatelessData(definition) {\n    return encodeWebauthnStatelessData({\n        credentials: webauthnDefinitionCredentials(definition),\n        threshold: definition.threshold,\n    });\n}\nexport function resolveWebauthnValidator(definition, ordering) {\n    return resolveWebauthnCredentials({\n        credentials: webauthnDefinitionCredentials(definition),\n        threshold: definition.threshold,\n        address: definition.module.source === 'explicit'\n            ? definition.module.address\n            : WEBAUTHN_VALIDATOR_ADDRESS,\n        ...(ordering ? { ordering } : {}),\n    });\n}\n","import { encodeEnsStatelessData, resolveEnsValidator } from './ens.js';\nimport { resolveMultiFactorValidator } from './multi-factor.js';\nimport { resolveOwnableStatelessData, resolveOwnableValidator } from './ownable.js';\nimport { resolveQuorumValidator } from './quorum.js';\nimport { resolveWebauthnStatelessData, resolveWebauthnValidator, } from './webauthn.js';\nexport function resolveAtomicValidator(definition, webauthnOrdering) {\n    switch (definition.kind) {\n        case 'ecdsa':\n            return resolveOwnableValidator(definition);\n        case 'quorum':\n            return resolveQuorumValidator(definition);\n        case 'ens':\n            return resolveEnsValidator(definition);\n        case 'passkey':\n            return resolveWebauthnValidator(definition, webauthnOrdering);\n        case 'k1':\n        case 'smart-session':\n            throw new Error(`Validator ${definition.kind} requires feature input`);\n    }\n}\n// What a validator's `validateSignatureWithData` expects as its `data`. Only\n// Ownable's happens to equal its install data; for WebAuthn and ENS the two\n// differ, and multi-factor factor slots need this one.\nexport function resolveAtomicValidatorStatelessData(definition) {\n    switch (definition.kind) {\n        case 'ecdsa':\n            return resolveOwnableStatelessData(definition);\n        case 'ens':\n            return encodeEnsStatelessData(definition);\n        case 'passkey':\n            return resolveWebauthnStatelessData(definition);\n        case 'quorum':\n            throw new Error('Validator quorum cannot be used as a multi-factor factor');\n        case 'k1':\n        case 'smart-session':\n            throw new Error(`Validator ${definition.kind} requires feature input`);\n    }\n}\nexport function resolveAtomicValidatorFactor(definition) {\n    return {\n        module: resolveAtomicValidator(definition),\n        statelessData: resolveAtomicValidatorStatelessData(definition),\n    };\n}\n// `webauthnOrdering` only applies to a top-level passkey validator: multi-factor\n// stores the stateless configuration for its factors, whose credential order is\n// fixed by the pinned account the IDs are derived from.\nexport function resolveValidator(definition, webauthnOrdering) {\n    return definition.kind === 'multi-factor'\n        ? resolveMultiFactorValidator(definition, resolveAtomicValidatorFactor)\n        : resolveAtomicValidator(definition, webauthnOrdering);\n}\n","import { encodeAbiParameters, keccak256 } from 'viem';\nimport { hasDuplicateWebauthnCredentials, webauthnCredentialsAreAscending, } from '../modules/validators/webauthn.js';\nimport { KERNEL_SALT_DEFAULTS, NEXUS_SALT_DEFAULTS, SAFE_NONCE_DEFAULTS, STARTALE_SALT_DEFAULTS, selectedValue, } from './deployment.js';\nimport { PasskeyConfigurationNotInstallableError } from './error.js';\n// The validator's install data must list credentials with strictly ascending\n// `keccak(x, y, account)`, so the number of salts that have to be tried grows\n// with the factorial of the credential count. Six passkeys is ~0.2s of\n// synchronous work in the worst realistic case; beyond that the remaining\n// passkeys are added after deployment, which the validator accepts in any order.\nexport const MAX_DEPLOYMENT_PASSKEYS = 6;\n// The validator's own `MAX_CREDENTIALS`.\nexport const MAX_PASSKEY_CREDENTIALS = 32;\n// A fixed attempt count, never a wall-clock budget: a slower host must derive\n// the same address as a faster one.\nexport const MAX_PASSKEY_SALT_ATTEMPTS = 65_536;\nconst MEMO_LIMIT = 256;\nconst memo = new Map();\nexport function accountSupportsSaltSearch(account) {\n    return (account.kind === 'nexus' ||\n        account.kind === 'kernel' ||\n        account.kind === 'startale' ||\n        account.kind === 'safe');\n}\nfunction saltAttempt(base, attempt) {\n    return keccak256(encodeAbiParameters([{ type: 'bytes32' }, { type: 'uint256' }], [base, BigInt(attempt)]));\n}\n// Attempt 0 is the caller's own salt, so a configuration that already installs\n// cleanly keeps the address it derives today.\nexport function accountWithSaltAttempt(account, attempt) {\n    if (attempt === 0)\n        return account;\n    switch (account.kind) {\n        case 'nexus':\n            return {\n                ...account,\n                salt: {\n                    source: 'explicit',\n                    value: saltAttempt(selectedValue(account.salt, NEXUS_SALT_DEFAULTS), attempt),\n                },\n            };\n        case 'kernel':\n            return {\n                ...account,\n                salt: {\n                    source: 'explicit',\n                    value: saltAttempt(selectedValue(account.salt, KERNEL_SALT_DEFAULTS), attempt),\n                },\n            };\n        case 'startale':\n            return {\n                ...account,\n                salt: {\n                    source: 'explicit',\n                    value: saltAttempt(selectedValue(account.salt, STARTALE_SALT_DEFAULTS), attempt),\n                },\n            };\n        case 'safe': {\n            const nonce = selectedValue(account.nonce, SAFE_NONCE_DEFAULTS);\n            return {\n                ...account,\n                nonce: {\n                    source: 'explicit',\n                    value: BigInt(keccak256(encodeAbiParameters([{ type: 'uint256' }, { type: 'uint256' }], [nonce, BigInt(attempt)]))),\n                },\n            };\n        }\n        case 'hca':\n        case 'eoa':\n            throw new PasskeyConfigurationNotInstallableError(`${account.kind} accounts have no salt to search`);\n    }\n}\nexport function assertPasskeySetInstallable(input) {\n    if (hasDuplicateWebauthnCredentials(input.credentials)) {\n        throw new PasskeyConfigurationNotInstallableError('the owner set contains duplicate passkeys');\n    }\n    if (input.credentials.length > MAX_PASSKEY_CREDENTIALS) {\n        throw new PasskeyConfigurationNotInstallableError(`the WebAuthn validator supports at most ${MAX_PASSKEY_CREDENTIALS} passkeys, received ${input.credentials.length}`);\n    }\n    if (input.atDeployment &&\n        input.credentials.length > MAX_DEPLOYMENT_PASSKEYS) {\n        throw new PasskeyConfigurationNotInstallableError(`at most ${MAX_DEPLOYMENT_PASSKEYS} passkeys can be installed at deployment, received ${input.credentials.length}. Deploy with ${MAX_DEPLOYMENT_PASSKEYS} or fewer and add the rest with \\`passkeys.addOwner\\``);\n    }\n}\n/**\n * Picks the account salt whose derived address makes the (canonically ordered)\n * passkey set installable. Deterministic: the same inputs select the same salt\n * on every host and in every run.\n */\nexport function selectPasskeyAccount(input) {\n    const cached = memo.get(input.fingerprint);\n    if (cached)\n        return cached;\n    const maxAttempts = input.maxAttempts ?? MAX_PASSKEY_SALT_ATTEMPTS;\n    for (let attempt = 0; attempt < maxAttempts; attempt++) {\n        const candidate = accountWithSaltAttempt(input.account, attempt);\n        const address = input.deriveAddress(candidate);\n        if (webauthnCredentialsAreAscending(input.credentials, address)) {\n            if (memo.size >= MEMO_LIMIT)\n                memo.clear();\n            memo.set(input.fingerprint, candidate);\n            return candidate;\n        }\n    }\n    throw new PasskeyConfigurationNotInstallableError(`no account salt in ${maxAttempts} attempts installs these ${input.credentials.length} passkeys. Deploy with fewer passkeys and add the rest with \\`passkeys.addOwner\\``);\n}\n","import { keccak256, zeroHash } from 'viem';\n// Salt/nonce defaults live here rather than in the adapters so the passkey salt\n// search grinds the same values the adapters derive addresses from.\nexport const NEXUS_SALT_DEFAULTS = {\n    'nexus-empty-calldata-salt': keccak256('0x'),\n};\nexport const KERNEL_SALT_DEFAULTS = { 'kernel-zero-salt': zeroHash };\nexport const STARTALE_SALT_DEFAULTS = {\n    'startale-zero-salt': zeroHash,\n};\nexport const SAFE_NONCE_DEFAULTS = { 'safe-zero-nonce': 0n };\nexport function selectedValue(selection, defaults) {\n    return selection.source === 'explicit'\n        ? selection.value\n        : defaults[selection.profile];\n}\nexport function deploymentPlan(chain, material, deployed) {\n    return {\n        chain,\n        address: material.address,\n        ...(material.factory ? { factory: material.factory } : {}),\n        ...(material.factoryData ? { factoryData: material.factoryData } : {}),\n        ...(material.factory && material.factoryData\n            ? {\n                initCode: `${material.factory}${material.factoryData.slice(2)}`,\n            }\n            : {}),\n        deployed,\n    };\n}\nexport function initDataMaterial(initData) {\n    if (!initData)\n        return undefined;\n    return 'factory' in initData\n        ? {\n            address: initData.address,\n            factory: initData.factory,\n            factoryData: initData.factoryData,\n        }\n        : { address: initData.address };\n}\nexport function accountKind(definition) {\n    return definition.kind;\n}\n","import { deploymentPlan } from '../deployment.js';\nimport { ModuleInstallationNotSupportedError } from '../error.js';\nfunction eoaAddress(input) {\n    if (input.account.kind !== 'eoa')\n        throw new Error('Expected EOA account');\n    if (!input.eoa)\n        throw new Error('EOA account is required');\n    return input.eoa.address;\n}\nexport function createEoaAdapter(construction) {\n    if (construction.account.kind !== 'eoa') {\n        throw new Error('Expected EOA account');\n    }\n    return {\n        account: construction.account,\n        capabilities: {\n            modular: false,\n            supportsDeployment: false,\n            supportsUserOperations: false,\n            supportsEip7702Adoption: false,\n            supportsSmartSessions: false,\n            supportsOriginSignatureReuse: true,\n            signatureEnvelope: { kind: 'none' },\n        },\n        getIdentity: (input) => ({\n            definition: input.account,\n            address: eoaAddress(input),\n        }),\n        getDeploymentPlan: (input) => deploymentPlan(input.chain, { address: eoaAddress(input) }, true),\n        encodeCalls: () => {\n            throw new Error('EOA calls do not use ERC-7579 encoding');\n        },\n        encodeModuleInstallation: () => {\n            throw new ModuleInstallationNotSupportedError('eoa');\n        },\n        encodeModuleUninstallation: () => {\n            throw new ModuleInstallationNotSupportedError('eoa');\n        },\n        encodeSignatureEnvelope: ({ envelope, validatorContribution }) => {\n            if (envelope.kind !== 'none')\n                throw new Error('Expected EOA envelope');\n            return validatorContribution;\n        },\n    };\n}\n","import { concat, decodeAbiParameters, decodeFunctionData, encodeFunctionData, encodePacked, keccak256, pad, parseAbi, slice, } from 'viem';\nimport { ENS_HCA_MODULE } from '../../modules/validators/ens.js';\nimport { deploymentPlan } from '../deployment.js';\nimport { encodeErc7579Calls } from '../erc7579-calls.js';\nimport { ModuleInstallationNotSupportedError } from '../error.js';\nimport { encodeAddressEnvelope } from './shared.js';\nexport const HCA_IMPLEMENTATION_ADDRESS = '0x7c2cC1e499a87ab480Df154e05164cD56D05d570';\nconst HCA_FACTORY_ADDRESS = '0x358680728dedb552adaa9f5eb5d4395b291cf943';\nconst CREATE3_PROXY_HASH = '0x21c35dbe1b344a2488cf3321d6ce542f8e9f305544ff09e4993a62319a497c1f';\nfunction primaryOwner(factoryData) {\n    const decoded = decodeFunctionData({\n        abi: parseAbi(['function createAccount(bytes)']),\n        data: factoryData,\n    });\n    const [, owners] = decodeAbiParameters([\n        { type: 'uint256' },\n        {\n            type: 'tuple[]',\n            components: [\n                { name: 'addr', type: 'address' },\n                { name: 'expiration', type: 'uint48' },\n            ],\n        },\n    ], decoded.args[0]);\n    const owner = owners[0];\n    if (!owner)\n        throw new Error('HCA primary owner is required');\n    return owner.addr;\n}\nfunction predictCreate3Address(factory, owner) {\n    const salt = pad(owner, { size: 32, dir: 'right' });\n    const proxyHash = keccak256(encodePacked(['bytes1', 'address', 'bytes32', 'bytes32'], ['0xff', factory, salt, CREATE3_PROXY_HASH]));\n    const proxyAddress = slice(proxyHash, 12, 32);\n    return slice(keccak256(concat(['0xd694', proxyAddress, '0x01'])), 12, 32);\n}\nfunction hcaMaterial(input) {\n    if (input.account.kind !== 'hca')\n        throw new Error('Expected HCA account');\n    if (input.eoa)\n        return { address: input.eoa.address };\n    // HCA derives its address from the ENS owner alone and has no module\n    // installation, so recovery, sessions, and extra modules can never be\n    // installed. `recovery` resolves into `modules`, so it is rejected here too.\n    if (input.sessions.enabled || input.modules.length > 0) {\n        throw new Error('HCA accounts cannot install recovery, sessions, or additional modules');\n    }\n    if (!input.owner || input.owner.kind !== 'ens') {\n        throw new Error('HCA accounts require ENS owners');\n    }\n    if (input.initData && !('factory' in input.initData)) {\n        return { address: input.initData.address };\n    }\n    let factory;\n    let factoryData;\n    if (input.initData && 'factory' in input.initData) {\n        factory = input.initData.factory;\n        factoryData = input.initData.factoryData;\n        try {\n            decodeFunctionData({\n                abi: parseAbi(['function createAccount(bytes)']),\n                data: factoryData,\n            });\n        }\n        catch {\n            return { address: input.initData.address };\n        }\n    }\n    else {\n        factory =\n            input.account.factory.source === 'explicit'\n                ? input.account.factory.value\n                : HCA_FACTORY_ADDRESS;\n        const validator = input.setup.validators[0];\n        if (!validator)\n            throw new Error('HCA owner validator is required');\n        factoryData = encodeFunctionData({\n            abi: parseAbi(['function createAccount(bytes)']),\n            functionName: 'createAccount',\n            args: [validator.initData],\n        });\n    }\n    return {\n        address: predictCreate3Address(factory, primaryOwner(factoryData)),\n        factory,\n        factoryData,\n    };\n}\nexport function createHcaAdapter(construction) {\n    if (construction.account.kind !== 'hca') {\n        throw new Error('Expected HCA account');\n    }\n    return {\n        account: construction.account,\n        capabilities: {\n            modular: false,\n            supportsDeployment: true,\n            supportsUserOperations: true,\n            supportsEip7702Adoption: false,\n            supportsSmartSessions: false,\n            supportsOriginSignatureReuse: true,\n            signatureEnvelope: { kind: 'hca', validator: ENS_HCA_MODULE },\n        },\n        getIdentity: (input) => ({\n            definition: input.account,\n            address: hcaMaterial(input).address,\n        }),\n        getDeploymentPlan: (input) => deploymentPlan(input.chain, hcaMaterial(input), input.deployed),\n        encodeCalls: encodeErc7579Calls,\n        encodeModuleInstallation: () => {\n            throw new ModuleInstallationNotSupportedError('hca');\n        },\n        encodeModuleUninstallation: () => {\n            throw new ModuleInstallationNotSupportedError('hca');\n        },\n        encodeSignatureEnvelope: ({ envelope, validatorContribution }) => {\n            if (envelope.kind !== 'hca')\n                throw new Error('Expected HCA envelope');\n            return encodeAddressEnvelope(envelope.validator, validatorContribution, ENS_HCA_MODULE);\n        },\n    };\n}\n","import { concatHex, encodeAbiParameters, encodeFunctionData, encodePacked, toBytes, toHex, } from 'viem';\nfunction executionMode(mode) {\n    return encodePacked(['bytes1', 'bytes1', 'bytes4', 'bytes4', 'bytes22'], [\n        toHex(toBytes(mode === 'batch' ? '0x01' : '0x00', { size: 1 })),\n        '0x00',\n        '0x00000000',\n        '0x00000000',\n        `0x${'00'.repeat(22)}`,\n    ]);\n}\nconst executeAbi = [\n    {\n        type: 'function',\n        name: 'execute',\n        inputs: [\n            { name: 'execMode', type: 'bytes32' },\n            { name: 'executionCalldata', type: 'bytes' },\n        ],\n        outputs: [],\n        stateMutability: 'payable',\n    },\n];\nexport function encodeErc7579Calls(input) {\n    if (input.calls.length === 0)\n        throw new Error('No calls to encode');\n    if (input.calls.length > 1 && input.mode !== 'batch') {\n        throw new Error('Single execution mode cannot encode multiple calls');\n    }\n    const calldata = input.mode === 'batch'\n        ? encodeAbiParameters([\n            {\n                name: 'executionBatch',\n                type: 'tuple[]',\n                components: [\n                    { name: 'target', type: 'address' },\n                    { name: 'value', type: 'uint256' },\n                    { name: 'callData', type: 'bytes' },\n                ],\n            },\n        ], [\n            input.calls.map((call) => ({\n                target: call.target,\n                value: call.value,\n                callData: call.data,\n            })),\n        ])\n        : concatHex([\n            input.calls[0].target,\n            toHex(input.calls[0].value, { size: 32 }),\n            input.calls[0].data,\n        ]);\n    return encodeFunctionData({\n        abi: executeAbi,\n        functionName: 'execute',\n        args: [executionMode(input.mode), calldata],\n    });\n}\n","import { encodeFunctionData, encodePacked, zeroAddress } from 'viem';\nimport { moduleTypeId } from '../../modules/erc7579-abi.js';\nimport { compareHexValues } from '../../modules/validators/ordering.js';\nexport function primaryOwnerAddresses(validator) {\n    if (validator.kind === 'passkey' || validator.kind === 'multi-factor') {\n        return ['0xbabe99e62d8bcbd3acf5ccbcfcd4f64fe75e5e72'];\n    }\n    return validator.owners.map((owner) => {\n        if (owner.kind === 'webauthn') {\n            throw new Error('Validator owner does not expose an address');\n        }\n        return owner.account.address;\n    });\n}\n// Safe keeps owners in a linked list and imposes no order on them, but the\n// owner array is part of the `setup` initializer that becomes the account's\n// CREATE2 salt — so it must be ordered by value, never by caller order.\nexport function canonicalOwnerAddresses(validator) {\n    return [...primaryOwnerAddresses(validator)].sort(compareHexValues);\n}\nexport function primaryThreshold(validator) {\n    return BigInt(validator.kind === 'passkey' || validator.kind === 'multi-factor'\n        ? 1\n        : validator.threshold);\n}\nexport function encodeInstallModule(module) {\n    return encodeFunctionData({\n        abi: [\n            {\n                type: 'function',\n                name: 'installModule',\n                inputs: [\n                    { type: 'uint256', name: 'moduleTypeId' },\n                    { type: 'address', name: 'module' },\n                    { type: 'bytes', name: 'initData' },\n                ],\n                outputs: [],\n                stateMutability: 'nonpayable',\n            },\n        ],\n        functionName: 'installModule',\n        args: [moduleTypeId(module.kind), module.address, module.initData],\n    });\n}\nexport function encodeUninstallModule(module) {\n    return encodeFunctionData({\n        abi: [\n            {\n                type: 'function',\n                name: 'uninstallModule',\n                inputs: [\n                    { type: 'uint256', name: 'moduleTypeId' },\n                    { type: 'address', name: 'module' },\n                    { type: 'bytes', name: 'deInitData' },\n                ],\n                outputs: [],\n                stateMutability: 'nonpayable',\n            },\n        ],\n        functionName: 'uninstallModule',\n        args: [moduleTypeId(module.kind), module.address, module.deInitData],\n    });\n}\nexport function encodeAddressEnvelope(validator, signature, defaultValidator) {\n    const address = defaultValidator?.toLowerCase() === validator.toLowerCase()\n        ? zeroAddress\n        : validator;\n    return encodePacked(['address', 'bytes'], [address, signature]);\n}\n","export function moduleTypeId(kind) {\n    switch (kind) {\n        case 'validator':\n            return 1n;\n        case 'executor':\n            return 2n;\n        case 'fallback':\n            return 3n;\n        case 'hook':\n            return 4n;\n    }\n}\n","import { concat, decodeAbiParameters, decodeFunctionData, encodeAbiParameters, encodeFunctionData, getContractAddress, keccak256, parseAbi, toHex, zeroAddress, } from 'viem';\nimport { moduleTypeId } from '../../modules/erc7579-abi.js';\nimport { deploymentPlan, KERNEL_SALT_DEFAULTS, selectedValue, } from '../deployment.js';\nimport { encodeErc7579Calls } from '../erc7579-calls.js';\nimport { encodeUninstallModule } from './shared.js';\nconst KERNEL_META_FACTORY_ADDRESS = '0xd703aae79538628d27099b8c4f621be4ccd142d5';\nexport const KERNEL_IMPLEMENTATION_ADDRESS = '0xd6cedde84be40893d153be9d467cd6ad37875b28';\nconst KERNEL_FACTORY_ADDRESS = '0x2577507b78c2008ff367261cb6285d44ba5ef2e9';\nconst KERNEL_BYTECODE = '0x603d3d8160223d3973d6cedde84be40893d153be9d467cd6ad37875b2860095155f3363d3d373d3d363d7f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc545af43d6000803e6038573d6000fd5b3d6000f3';\nconst HOOK_INSTALLED_ADDRESS = '0x0000000000000000000000000000000000000001';\nexport function kernelInstallData(module) {\n    const install = (initData) => encodeFunctionData({\n        abi: parseAbi(['function installModule(uint256,address,bytes)']),\n        functionName: 'installModule',\n        args: [moduleTypeId(module.kind), module.address, initData],\n    });\n    switch (module.kind) {\n        case 'validator': {\n            const data = encodeAbiParameters([{ type: 'bytes' }, { type: 'bytes' }, { type: 'bytes' }], [module.initData, '0x', '0x']);\n            return [\n                install(concat([HOOK_INSTALLED_ADDRESS, data])),\n                encodeFunctionData({\n                    abi: parseAbi(['function grantAccess(bytes21,bytes4,bool)']),\n                    functionName: 'grantAccess',\n                    args: [concat(['0x01', module.address]), '0xe9ae5c53', true],\n                }),\n            ];\n        }\n        case 'executor': {\n            const data = encodeAbiParameters([{ type: 'bytes' }, { type: 'bytes' }], [module.initData, '0x']);\n            return [install(concat([zeroAddress, data]))];\n        }\n        case 'fallback': {\n            const [selector, flags, selectorData] = decodeAbiParameters([{ type: 'bytes4' }, { type: 'bytes1' }, { type: 'bytes' }], module.initData);\n            const data = encodeAbiParameters([{ type: 'bytes' }, { type: 'bytes' }], [concat([flags, selectorData]), '0x']);\n            return [install(concat([selector, HOOK_INSTALLED_ADDRESS, data]))];\n        }\n        case 'hook':\n            return [install(module.initData)];\n    }\n}\nfunction kernelMaterial(input) {\n    if (input.account.kind !== 'kernel')\n        throw new Error('Expected Kernel account');\n    if (input.eoa)\n        return { address: input.eoa.address };\n    if (input.initData && !('factory' in input.initData)) {\n        return { address: input.initData.address };\n    }\n    let factoryData;\n    let salt;\n    let initializationCallData;\n    if (input.initData && 'factory' in input.initData) {\n        const decoded = decodeFunctionData({\n            abi: parseAbi([\n                'function deployWithFactory(address factory,bytes createData,bytes32 salt)',\n            ]),\n            data: input.initData.factoryData,\n        });\n        if (decoded.args[0].toLowerCase() !== KERNEL_FACTORY_ADDRESS.toLowerCase()) {\n            throw new Error('Unsupported Kernel implementation');\n        }\n        factoryData = input.initData.factoryData;\n        initializationCallData = decoded.args[1];\n        salt = decoded.args[2];\n    }\n    else {\n        const rootValidator = input.setup.validators[0];\n        if (!rootValidator)\n            throw new Error('Kernel root validator is required');\n        const initConfig = [\n            ...input.setup.validators.slice(1),\n            ...input.setup.executors,\n            ...input.setup.fallbacks,\n            ...input.setup.hooks,\n        ].flatMap(kernelInstallData);\n        initializationCallData = encodeFunctionData({\n            abi: parseAbi([\n                'function initialize(bytes21,address,bytes,bytes,bytes[])',\n            ]),\n            functionName: 'initialize',\n            args: [\n                concat(['0x01', rootValidator.address]),\n                zeroAddress,\n                rootValidator.initData,\n                '0x',\n                initConfig,\n            ],\n        });\n        salt = selectedValue(input.account.salt, KERNEL_SALT_DEFAULTS);\n        factoryData = encodeFunctionData({\n            abi: parseAbi(['function deployWithFactory(address,bytes,bytes32)']),\n            functionName: 'deployWithFactory',\n            args: [KERNEL_FACTORY_ADDRESS, initializationCallData, salt],\n        });\n    }\n    const actualSalt = keccak256(concat([initializationCallData, salt]));\n    const address = getContractAddress({\n        from: KERNEL_FACTORY_ADDRESS,\n        opcode: 'CREATE2',\n        bytecode: KERNEL_BYTECODE,\n        salt: actualSalt,\n    });\n    return {\n        address,\n        factory: input.initData?.factory ?? KERNEL_META_FACTORY_ADDRESS,\n        factoryData,\n    };\n}\nexport function createKernelAdapter(construction) {\n    if (construction.account.kind !== 'kernel') {\n        throw new Error('Expected Kernel account');\n    }\n    const validator = construction.setup.validators[0]?.address ?? zeroAddress;\n    return {\n        account: construction.account,\n        capabilities: {\n            modular: true,\n            supportsDeployment: true,\n            supportsUserOperations: true,\n            supportsEip7702Adoption: false,\n            supportsSmartSessions: true,\n            supportsOriginSignatureReuse: true,\n            signatureEnvelope: { kind: 'kernel', validator, isRoot: true },\n        },\n        getIdentity: (input) => ({\n            definition: input.account,\n            address: kernelMaterial(input).address,\n        }),\n        getDeploymentPlan: (input) => deploymentPlan(input.chain, kernelMaterial(input), input.deployed),\n        encodeCalls: encodeErc7579Calls,\n        encodeModuleInstallation: kernelInstallData,\n        encodeModuleUninstallation: encodeUninstallModule,\n        encodeSignatureEnvelope: ({ envelope, validatorContribution }) => {\n            if (envelope.kind !== 'kernel')\n                throw new Error('Expected Kernel envelope');\n            return concat([\n                envelope.isRoot ? '0x00' : concat(['0x01', envelope.validator]),\n                keccak256(toHex('kernel.replayable.signature')),\n                validatorContribution,\n            ]);\n        },\n    };\n}\n","import { concat, decodeFunctionData, encodeAbiParameters, encodeFunctionData, encodePacked, getContractAddress, parseAbi, size, zeroAddress, } from 'viem';\nimport { OWNABLE_VALIDATOR_ADDRESS } from '../../modules/validators/ownable.js';\nimport { deploymentPlan, NEXUS_SALT_DEFAULTS, selectedValue, } from '../deployment.js';\nimport { encodeErc7579Calls } from '../erc7579-calls.js';\nimport { encodeAddressEnvelope, encodeInstallModule, encodeUninstallModule, } from './shared.js';\nexport const NEXUS_IMPLEMENTATION_ADDRESS = '0x000000000032ddc454c3bdcba80484ad5a798705';\nexport const NEXUS_FACTORY_ADDRESS = '0x0000000000679a258c64d2f20f310e12b64b7375';\n// Current default (1.2.1): new implementation + factory, same bootstrap and\n// proxy creation code as 1.2.0. `version: '1.2.0'` opts back into the previous\n// implementation + factory so its counterfactual address doesn't change.\nexport const NEXUS_IMPLEMENTATION_1_2_1 = '0x000000000d41c0bf0063dba53343389cdb2c9c78';\nexport const NEXUS_FACTORY_1_2_1 = '0x0000000099d5576c73a3b190dabeeaa0f128ce6b';\nconst NEXUS_BOOTSTRAP_ADDRESS = '0x00000000006efb61d8c9546ff1b500de3f244ea7';\nconst NEXUS_CREATION_CODE = '0x60806040526102aa803803806100148161018c565b92833981016040828203126101885781516001600160a01b03811692909190838303610188576020810151906001600160401b03821161018857019281601f8501121561018857835161006e610069826101c5565b61018c565b9481865260208601936020838301011161018857815f926020809301865e8601015260017f90b772c2cb8a51aa7a8a65fc23543c6d022d5b3f8e2b92eed79fba7eef8293005d823b15610176577f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc80546001600160a01b031916821790557fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b5f80a282511561015e575f8091610146945190845af43d15610156573d91610137610069846101c5565b9283523d5f602085013e6101e0565b505b604051606b908161023f8239f35b6060916101e0565b50505034156101485763b398979f60e01b5f5260045ffd5b634c9c8ce360e01b5f5260045260245ffd5b5f80fd5b6040519190601f01601f191682016001600160401b038111838210176101b157604052565b634e487b7160e01b5f52604160045260245ffd5b6001600160401b0381116101b157601f01601f191660200190565b9061020457508051156101f557805190602001fd5b63d6bda27560e01b5f5260045ffd5b81511580610235575b610215575090565b639996b31560e01b5f9081526001600160a01b0391909116600452602490fd5b50803b1561020d56fe60806040523615605c575f8073ffffffffffffffffffffffffffffffffffffffff7f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc5416368280378136915af43d5f803e156058573d5ff35b3d5ffd5b00fea164736f6c634300081b000a';\n// Resolves the implementation + factory a fresh account deploys against. Only\n// the default (unset) and an explicit '1.2.1' deploy the current contracts;\n// '1.2.0' keeps the previous implementation + factory so its counterfactual\n// address doesn't change.\nfunction getNexusDeployment(version) {\n    if (!version || version === '1.2.1') {\n        return {\n            implementation: NEXUS_IMPLEMENTATION_1_2_1,\n            factory: NEXUS_FACTORY_1_2_1,\n        };\n    }\n    return {\n        implementation: NEXUS_IMPLEMENTATION_ADDRESS,\n        factory: NEXUS_FACTORY_ADDRESS,\n    };\n}\n// Maps a Nexus factory to the implementation it deploys, so a persisted\n// `initData` payload recomputes against the right implementation instead of\n// defaulting to one version.\nfunction implementationForFactory(factory) {\n    return factory.toLowerCase() === NEXUS_FACTORY_1_2_1\n        ? NEXUS_IMPLEMENTATION_1_2_1\n        : NEXUS_IMPLEMENTATION_ADDRESS;\n}\nexport function nexusMaterial(input) {\n    if (input.account.kind !== 'nexus')\n        throw new Error('Expected Nexus account');\n    if (input.eoa)\n        return { address: input.eoa.address };\n    if (input.initData && !('factory' in input.initData)) {\n        return { address: input.initData.address };\n    }\n    const version = input.account.version.source === 'explicit'\n        ? input.account.version.value\n        : undefined;\n    let factory;\n    let factoryData;\n    let implementation;\n    let initializationCallData;\n    let salt;\n    if (input.initData && 'factory' in input.initData) {\n        const decoded = decodeFunctionData({\n            abi: parseAbi(['function createAccount(bytes,bytes32)']),\n            data: input.initData.factoryData,\n        });\n        factory = input.initData.factory;\n        implementation = implementationForFactory(factory);\n        factoryData = input.initData.factoryData;\n        const initData = decoded.args[0];\n        salt = decoded.args[1];\n        initializationCallData = encodeFunctionData({\n            abi: parseAbi(['function initializeAccount(bytes)']),\n            functionName: 'initializeAccount',\n            args: [initData],\n        });\n    }\n    else {\n        const deployment = getNexusDeployment(version);\n        factory = deployment.factory;\n        implementation = deployment.implementation;\n        salt = selectedValue(input.account.salt, NEXUS_SALT_DEFAULTS);\n        const defaultValidator = input.setup.validators.find((module) => module.address === OWNABLE_VALIDATOR_ADDRESS);\n        const defaultValidatorInitData = defaultValidator?.initData ?? '0x';\n        const validators = input.setup.validators.filter((module) => module.address !== OWNABLE_VALIDATOR_ADDRESS);\n        const configs = (modules) => modules.map((module) => ({\n            module: module.address,\n            initData: module.initData,\n        }));\n        const bootstrapData = size(defaultValidatorInitData) > 0\n            ? encodeFunctionData({\n                abi: parseAbi([\n                    'struct BootstrapConfig {address module;bytes initData;}',\n                    'struct BootstrapPreValidationHookConfig {uint256 hookType;address module;bytes data;}',\n                    'function initNexusWithDefaultValidatorAndOtherModulesNoRegistry(bytes defaultValidatorInitData,BootstrapConfig[] validators,BootstrapConfig[] executors,BootstrapConfig hook,BootstrapConfig[] fallbacks,BootstrapPreValidationHookConfig[] preValidationHooks)',\n                ]),\n                functionName: 'initNexusWithDefaultValidatorAndOtherModulesNoRegistry',\n                args: [\n                    defaultValidatorInitData,\n                    configs(validators),\n                    configs(input.setup.executors),\n                    { module: zeroAddress, initData: '0x' },\n                    configs(input.setup.fallbacks),\n                    [],\n                ],\n            })\n            : encodeFunctionData({\n                abi: parseAbi([\n                    'struct BootstrapConfig {address module;bytes initData;}',\n                    'struct BootstrapPreValidationHookConfig {uint256 hookType;address module;bytes data;}',\n                    'function initNexusNoRegistry(BootstrapConfig[] validators,BootstrapConfig[] executors,BootstrapConfig hook,BootstrapConfig[] fallbacks,BootstrapPreValidationHookConfig[] preValidationHooks)',\n                ]),\n                functionName: 'initNexusNoRegistry',\n                args: [\n                    configs(validators),\n                    configs(input.setup.executors),\n                    { module: zeroAddress, initData: '0x' },\n                    configs(input.setup.fallbacks),\n                    [],\n                ],\n            });\n        const initData = encodeAbiParameters([{ type: 'address' }, { type: 'bytes' }], [NEXUS_BOOTSTRAP_ADDRESS, bootstrapData]);\n        factoryData = encodeFunctionData({\n            abi: parseAbi(['function createAccount(bytes,bytes32)']),\n            functionName: 'createAccount',\n            args: [initData, salt],\n        });\n        initializationCallData = encodeFunctionData({\n            abi: parseAbi(['function initializeAccount(bytes)']),\n            functionName: 'initializeAccount',\n            args: [initData],\n        });\n    }\n    const accountInitData = encodeAbiParameters([\n        { name: 'address', type: 'address' },\n        { name: 'calldata', type: 'bytes' },\n    ], [implementation, initializationCallData]);\n    const address = getContractAddress({\n        opcode: 'CREATE2',\n        from: factory,\n        salt,\n        bytecode: concat([NEXUS_CREATION_CODE, accountInitData]),\n    });\n    return {\n        address,\n        factory,\n        factoryData,\n        implementation,\n        initializationCallData,\n        salt,\n    };\n}\nfunction nexusEip7702AdoptionPlan(input) {\n    const { eoa: _eoa, ...factoryConstruction } = input;\n    const material = nexusMaterial(factoryConstruction);\n    if (!material.factoryData || !material.implementation) {\n        throw new Error('Nexus EIP-7702 initialization data is unavailable');\n    }\n    const decoded = decodeFunctionData({\n        abi: parseAbi(['function createAccount(bytes,bytes32)']),\n        data: material.factoryData,\n    });\n    if (decoded.functionName !== 'createAccount') {\n        throw new Error('Invalid Nexus EIP-7702 initialization data');\n    }\n    return {\n        contract: material.implementation,\n        initData: decoded.args[0],\n    };\n}\n// Builds the signed `initializeAccount` call sent as the account setup op when a\n// 7702 intent is prepared. The account authorizes initialization by prefixing\n// the raw module init data (packed with the any-chain sentinel) with its\n// EIP-7702 init signature.\nfunction nexusEip7702InitCall(input, eip7702InitSignature) {\n    const { initData } = nexusEip7702AdoptionPlan(input);\n    const packedInitData = encodePacked(['uint256', 'uint256', 'uint256', 'bytes'], [0n, 1n, 0n, initData]);\n    return encodeFunctionData({\n        abi: parseAbi(['function initializeAccount(bytes)']),\n        functionName: 'initializeAccount',\n        args: [concat([eip7702InitSignature, packedInitData])],\n    });\n}\nexport function createNexusAdapter(construction) {\n    if (construction.account.kind !== 'nexus') {\n        throw new Error('Expected Nexus account');\n    }\n    const validator = construction.setup.validators[0]?.address ?? zeroAddress;\n    return {\n        account: construction.account,\n        capabilities: {\n            modular: true,\n            supportsDeployment: true,\n            supportsUserOperations: true,\n            supportsEip7702Adoption: true,\n            supportsSmartSessions: true,\n            supportsOriginSignatureReuse: true,\n            signatureEnvelope: { kind: 'nexus', validator },\n        },\n        getIdentity: (input) => ({\n            definition: input.account,\n            address: nexusMaterial(input).address,\n        }),\n        getDeploymentPlan: (input) => deploymentPlan(input.chain, nexusMaterial(input), input.deployed),\n        getEip7702AdoptionPlan: nexusEip7702AdoptionPlan,\n        getEip7702InitCall: nexusEip7702InitCall,\n        encodeCalls: encodeErc7579Calls,\n        encodeModuleInstallation: (module) => [encodeInstallModule(module)],\n        encodeModuleUninstallation: encodeUninstallModule,\n        encodeSignatureEnvelope: ({ envelope, validatorContribution }) => {\n            if (envelope.kind !== 'nexus')\n                throw new Error('Expected Nexus envelope');\n            return encodeAddressEnvelope(envelope.validator, validatorContribution, OWNABLE_VALIDATOR_ADDRESS);\n        },\n    };\n}\n","import { concat, decodeFunctionData, encodeAbiParameters, encodeFunctionData, encodePacked, getContractAddress, keccak256, parseAbi, parseAbiParameters, zeroAddress, } from 'viem';\nimport { getV0Attesters } from '../../modules/legacy-core.js';\nimport { deploymentPlan, SAFE_NONCE_DEFAULTS, selectedValue, } from '../deployment.js';\nimport { encodeErc7579Calls } from '../erc7579-calls.js';\nimport { canonicalOwnerAddresses, encodeAddressEnvelope, encodeInstallModule, encodeUninstallModule, primaryOwnerAddresses, primaryThreshold, } from './shared.js';\nconst SAFE_LAUNCHPAD = '0x75798463024bda64d83c94a64bc7d7eab41300ef';\nconst SAFE_ADAPTER = '0x7579f2ad53b01c3d8779fe17928e0d48885b0003';\nconst SAFE_V0_LAUNCHPAD = '0x7579011ab74c46090561ea277ba79d510c6c00ff';\nconst SAFE_V0_ADAPTER = '0x7579ee8307284f293b1927136486880611f20002';\nconst SAFE_SINGLETON = '0x29fcb43b46531bca003ddc8fcb67ffe91900c762';\nconst SAFE_FACTORY = '0x4e1dcf7ad4e460cfd30791ccc4f9c8a4f820ec67';\nconst SAFE_PROXY_INIT_CODE = '0x608060405234801561001057600080fd5b506040516101e63803806101e68339818101604052602081101561003357600080fd5b8101908080519060200190929190505050600073ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff1614156100ca576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260228152602001806101c46022913960400191505060405180910390fd5b806000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055505060ab806101196000396000f3fe608060405273ffffffffffffffffffffffffffffffffffffffff600054167fa619486e0000000000000000000000000000000000000000000000000000000060003514156050578060005260206000f35b3660008037600080366000845af43d6000803e60008114156070573d6000fd5b3d6000f3fea264697066735822122003d1488ee65e08fa41e58e888a9865554c535f2c77126a82cb4c0f917f31441364736f6c63430007060033496e76616c69642073696e676c65746f6e20616464726573732070726f7669646564';\nfunction safeMaterial(input) {\n    if (input.account.kind !== 'safe')\n        throw new Error('Expected Safe account');\n    if (input.eoa)\n        return { address: input.eoa.address };\n    if (input.initData && !('factory' in input.initData)) {\n        return { address: input.initData.address };\n    }\n    let factory = SAFE_FACTORY;\n    let factoryData;\n    let implementation = SAFE_SINGLETON;\n    let salt;\n    if (input.initData && 'factory' in input.initData) {\n        const decoded = decodeFunctionData({\n            abi: parseAbi([\n                'function createProxyWithNonce(address singleton,bytes initializer,uint256 saltNonce)',\n            ]),\n            data: input.initData.factoryData,\n        });\n        if (decoded.functionName !== 'createProxyWithNonce') {\n            throw new Error('Invalid Safe factory data');\n        }\n        factory = input.initData.factory;\n        factoryData = input.initData.factoryData;\n        implementation = decoded.args[0];\n        salt = keccak256(encodePacked(['bytes32', 'uint256'], [keccak256(decoded.args[1]), decoded.args[2]]));\n    }\n    else {\n        if (!input.owner)\n            throw new Error('Safe account owners are required');\n        const modules = [\n            ...input.setup.validators,\n            ...input.setup.executors,\n            ...input.setup.fallbacks,\n            ...input.setup.hooks,\n        ];\n        const addSafe7579 = encodeFunctionData({\n            abi: parseAbi([\n                'struct ModuleInit {address module;bytes initData;uint256 moduleType}',\n                'function addSafe7579(address safe7579,ModuleInit[] modules,address[] attesters,uint8 threshold)',\n            ]),\n            functionName: 'addSafe7579',\n            args: [\n                SAFE_ADAPTER,\n                modules.map((module) => ({\n                    module: module.address,\n                    initData: module.initData,\n                    moduleType: module.kind === 'validator'\n                        ? 1n\n                        : module.kind === 'executor'\n                            ? 2n\n                            : module.kind === 'fallback'\n                                ? 3n\n                                : 4n,\n                })),\n                [],\n                0,\n            ],\n        });\n        const initializer = encodeFunctionData({\n            abi: parseAbi([\n                'function setup(address[] _owners,uint256 _threshold,address to,bytes data,address fallbackHandler,address paymentToken,uint256 payment,address paymentReceiver)',\n            ]),\n            functionName: 'setup',\n            args: [\n                [...canonicalOwnerAddresses(input.owner)],\n                primaryThreshold(input.owner),\n                SAFE_LAUNCHPAD,\n                addSafe7579,\n                SAFE_ADAPTER,\n                zeroAddress,\n                0n,\n                zeroAddress,\n            ],\n        });\n        const nonce = selectedValue(input.account.nonce, SAFE_NONCE_DEFAULTS);\n        factoryData = encodeFunctionData({\n            abi: parseAbi([\n                'function createProxyWithNonce(address singleton,bytes initializer,uint256 saltNonce)',\n            ]),\n            functionName: 'createProxyWithNonce',\n            args: [SAFE_SINGLETON, initializer, nonce],\n        });\n        salt = keccak256(encodePacked(['bytes32', 'uint256'], [keccak256(initializer), nonce]));\n    }\n    const constructorArgs = encodeAbiParameters(parseAbiParameters('address singleton'), [implementation]);\n    const address = getContractAddress({\n        opcode: 'CREATE2',\n        from: factory,\n        salt,\n        bytecode: concat([SAFE_PROXY_INIT_CODE, constructorArgs]),\n    });\n    return { address, factory, factoryData };\n}\nexport function safeV0FactoryMaterial(input) {\n    if (input.account.kind !== 'safe')\n        throw new Error('Expected Safe account');\n    if (input.initData) {\n        throw new Error('Account configuration for Safe account is not supported: Custom V0 accounts are not supported');\n    }\n    if (!input.owner)\n        throw new Error('Safe account owners are required');\n    const attesters = getV0Attesters();\n    const modules = (items) => items.map((module) => ({\n        module: module.address,\n        initData: module.initData,\n    }));\n    const addSafe7579 = encodeFunctionData({\n        abi: parseAbi([\n            'struct ModuleInit {address module;bytes initData;}',\n            'function addSafe7579(address safe7579,ModuleInit[] validators,ModuleInit[] executors,ModuleInit[] fallbacks,ModuleInit[] hooks,address[] attesters,uint8 threshold)',\n        ]),\n        functionName: 'addSafe7579',\n        args: [\n            SAFE_V0_ADAPTER,\n            modules(input.setup.validators),\n            modules(input.setup.executors),\n            modules(input.setup.fallbacks),\n            modules(input.setup.hooks),\n            [...attesters.addresses],\n            attesters.threshold,\n        ],\n    });\n    const initializer = encodeFunctionData({\n        abi: parseAbi([\n            'function setup(address[] _owners,uint256 _threshold,address to,bytes data,address fallbackHandler,address paymentToken,uint256 payment,address paymentReceiver)',\n        ]),\n        functionName: 'setup',\n        args: [\n            // Caller order, not canonical order: this path reconstructs accounts that\n            // SDK v0 already deployed from the owner list as it was supplied.\n            [...primaryOwnerAddresses(input.owner)],\n            primaryThreshold(input.owner),\n            SAFE_V0_LAUNCHPAD,\n            addSafe7579,\n            SAFE_V0_ADAPTER,\n            zeroAddress,\n            0n,\n            zeroAddress,\n        ],\n    });\n    const nonce = selectedValue(input.account.nonce, SAFE_NONCE_DEFAULTS);\n    return {\n        factory: SAFE_FACTORY,\n        factoryData: encodeFunctionData({\n            abi: parseAbi([\n                'function createProxyWithNonce(address singleton,bytes initializer,uint256 saltNonce)',\n            ]),\n            functionName: 'createProxyWithNonce',\n            args: [SAFE_SINGLETON, initializer, nonce],\n        }),\n    };\n}\nexport function createSafeAdapter(construction) {\n    if (construction.account.kind !== 'safe') {\n        throw new Error('Expected Safe account');\n    }\n    const validator = construction.setup.validators[0]?.address ?? zeroAddress;\n    return {\n        account: construction.account,\n        capabilities: {\n            modular: true,\n            supportsDeployment: true,\n            supportsUserOperations: true,\n            supportsEip7702Adoption: false,\n            supportsSmartSessions: true,\n            supportsOriginSignatureReuse: true,\n            signatureEnvelope: { kind: 'safe', validator },\n        },\n        getIdentity: (input) => ({\n            definition: input.account,\n            address: safeMaterial(input).address,\n        }),\n        getDeploymentPlan: (input) => deploymentPlan(input.chain, safeMaterial(input), input.deployed),\n        encodeCalls: encodeErc7579Calls,\n        encodeModuleInstallation: (module) => [encodeInstallModule(module)],\n        encodeModuleUninstallation: encodeUninstallModule,\n        encodeSignatureEnvelope: ({ envelope, validatorContribution }) => {\n            if (envelope.kind !== 'safe')\n                throw new Error('Expected Safe envelope');\n            return encodeAddressEnvelope(envelope.validator, validatorContribution);\n        },\n    };\n}\n","import { encodeAbiParameters } from 'viem';\n// Legacy module-setup shapes preserved for the `experimental_getModuleSetup`\n// compatibility surface (note the historical `ModeleSetup` spelling, which is\n// part of the published type name).\nconst MODULE_TYPE_ID_VALIDATOR = 1n;\nconst MODULE_TYPE_ID_EXECUTOR = 2n;\nconst MODULE_TYPE_ID_FALLBACK = 3n;\nconst MODULE_TYPE_ID_HOOK = 4n;\nconst RHINESTONE_ATTESTER_ADDRESS = '0x000000333034E9f539ce08819E12c1b8Cb29084d';\nconst OMNI_ACCOUNT_MOCK_ATTESTER_ADDRESS = '0x6D0515e8E499468DCe9583626f0cA15b887f9d03';\nconst HOOK_ADDRESS = '0x0000000000f6Ed8Be424d673c63eeFF8b9267420';\nconst TARGET_MODULE_ADDRESS = '0x0000000000E5a37279A001301A837a91b5de1D5E';\nconst SAME_CHAIN_MODULE_ADDRESS = '0x000000000043ff16d5776c7F0f65Ec485C17Ca04';\nconst moduleType = (kind) => {\n    switch (kind) {\n        case 'validator':\n            return 1n;\n        case 'executor':\n            return 2n;\n        case 'fallback':\n            return 3n;\n        case 'hook':\n            return 4n;\n    }\n};\nexport function toLegacyModule(module) {\n    return {\n        address: module.address,\n        initData: module.initData,\n        deInitData: module.deInitData,\n        additionalContext: module.additionalContext,\n        type: moduleType(module.kind),\n    };\n}\nexport function toLegacyModuleSetup(setup) {\n    return {\n        validators: setup.validators.map(toLegacyModule),\n        executors: setup.executors.map(toLegacyModule),\n        fallbacks: setup.fallbacks.map(toLegacyModule),\n        hooks: setup.hooks.map(toLegacyModule),\n    };\n}\nexport function getV0Attesters() {\n    return {\n        addresses: [\n            RHINESTONE_ATTESTER_ADDRESS,\n            OMNI_ACCOUNT_MOCK_ATTESTER_ADDRESS,\n        ],\n        threshold: 1,\n    };\n}\nfunction v0Module(kind, address, initData = '0x') {\n    return {\n        kind,\n        address,\n        initData,\n        deInitData: '0x',\n        additionalContext: '0x',\n    };\n}\nexport function planV0ModuleSetup(setup) {\n    return {\n        validators: setup.validators,\n        executors: [\n            v0Module('executor', SAME_CHAIN_MODULE_ADDRESS),\n            v0Module('executor', TARGET_MODULE_ADDRESS),\n            v0Module('executor', HOOK_ADDRESS),\n            ...setup.executors,\n        ],\n        fallbacks: [\n            v0Module('fallback', TARGET_MODULE_ADDRESS, encodeAbiParameters([\n                { name: 'selector', type: 'bytes4' },\n                { name: 'flags', type: 'bytes1' },\n                { name: 'data', type: 'bytes' },\n            ], ['0x3a5be8cb', '0x00', '0x'])),\n            ...setup.fallbacks,\n        ],\n        hooks: setup.hooks,\n    };\n}\n","import { concat, decodeFunctionData, encodeAbiParameters, encodeFunctionData, encodePacked, keccak256, parseAbi, slice, zeroAddress, zeroHash, } from 'viem';\nimport { K1_DEFAULT_VALIDATOR_ADDRESS } from '../../modules/validators/k1.js';\nimport { deploymentPlan, STARTALE_SALT_DEFAULTS, selectedValue, } from '../deployment.js';\nimport { encodeErc7579Calls } from '../erc7579-calls.js';\nimport { AccountConfigurationNotSupportedError } from '../error.js';\nimport { encodeAddressEnvelope, encodeInstallModule, encodeUninstallModule, primaryOwnerAddresses, } from './shared.js';\nexport { K1_DEFAULT_VALIDATOR_ADDRESS };\nexport function startaleEip712Domain(account, chainId) {\n    return {\n        name: 'Startale',\n        version: '1.0.1',\n        chainId,\n        verifyingContract: account,\n        salt: zeroHash,\n    };\n}\n// Only Startale 1.0.1 is supported. It shares the bootstrap, K1 default\n// validator, and proxy creation code with 1.0.0 but uses a different\n// implementation, factory, and EIP-712 domain version.\nconst STARTALE_IMPLEMENTATION_ADDRESS = '0x000006b2874cf8a9bbe24fa1c3a32225ae826951';\nconst STARTALE_FACTORY_ADDRESS = '0x00000be75c267efe9ddd7044d1f236959af4c15f';\n// Rejected rather than recomputed: its accounts derive against a different\n// implementation and sign against a different domain.\nconst STARTALE_1_0_0_FACTORY_ADDRESS = '0x0000003b3e7b530b4f981ae80d9350392defef90';\nconst STARTALE_BOOTSTRAP_ADDRESS = '0x000000552a5fae3db7a8f3917c435448f49ba6a9';\nconst STARTALE_CREATION_CODE = '0x608060405261029d803803806100148161018c565b92833981016040828203126101885781516001600160a01b03811692909190838303610188576020810151906001600160401b03821161018857019281601f8501121561018857835161006e610069826101c5565b61018c565b9481865260208601936020838301011161018857815f926020809301865e8601015260017f754fd8b321c4649cb777ae6fdce7e89e9cceaa31a4f639795c7807eb7f1a27005d823b15610176577f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc80546001600160a01b031916821790557fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b5f80a282511561015e575f8091610146945190845af43d15610156573d91610137610069846101c5565b9283523d5f602085013e6101e0565b505b604051605e908161023f8239f35b6060916101e0565b50505034156101485763b398979f60e01b5f5260045ffd5b634c9c8ce360e01b5f5260045260245ffd5b5f80fd5b6040519190601f01601f191682016001600160401b038111838210176101b157604052565b634e487b7160e01b5f52604160045260245ffd5b6001600160401b0381116101b157601f01601f191660200190565b9061020457508051156101f557805190602001fd5b63d6bda27560e01b5f5260045ffd5b81511580610235575b610215575090565b639996b31560e01b5f9081526001600160a01b0391909116600452602490fd5b50803b1561020d56fe60806040523615605c575f8073ffffffffffffffffffffffffffffffffffffffff7f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc5416368280378136915af43d5f803e156058573d5ff35b3d5ffd5b00';\nfunction moduleConfigs(modules) {\n    return modules.map((module) => ({\n        module: module.address,\n        initData: module.initData,\n    }));\n}\nfunction startaleInitData(input) {\n    const ownerValidator = input.setup.validators[0];\n    if (!ownerValidator)\n        throw new Error('Startale owner validator is required');\n    const isK1 = ownerValidator.address.toLowerCase() ===\n        K1_DEFAULT_VALIDATOR_ADDRESS.toLowerCase();\n    let bootstrapData;\n    if (isK1) {\n        if (!input.owner)\n            throw new Error('Startale K1 owner is required');\n        const owners = primaryOwnerAddresses(input.owner);\n        if (owners.length !== 1) {\n            throw new Error('K1 validator only supports a single owner');\n        }\n        bootstrapData = encodeFunctionData({\n            abi: parseAbi([\n                'struct BootstrapConfig {address module;bytes initData;}',\n                'struct BootstrapPreValidationHookConfig {uint256 hookType;address module;bytes data;}',\n                'function initWithDefaultValidatorAndOtherModules(bytes defaultValidatorInitData,BootstrapConfig[] validators,BootstrapConfig[] executors,BootstrapConfig hook,BootstrapConfig[] fallbacks,BootstrapPreValidationHookConfig[] preValidationHooks)',\n            ]),\n            functionName: 'initWithDefaultValidatorAndOtherModules',\n            args: [\n                owners[0],\n                moduleConfigs(input.setup.validators.slice(1)),\n                moduleConfigs(input.setup.executors),\n                { module: zeroAddress, initData: zeroHash },\n                moduleConfigs(input.setup.fallbacks),\n                [],\n            ],\n        });\n    }\n    else {\n        bootstrapData = encodeFunctionData({\n            abi: parseAbi([\n                'struct BootstrapConfig {address module;bytes initData;}',\n                'struct BootstrapPreValidationHookConfig {uint256 hookType;address module;bytes data;}',\n                'function init(BootstrapConfig[] validators,BootstrapConfig[] executors,BootstrapConfig hook,BootstrapConfig[] fallbacks,BootstrapPreValidationHookConfig[] preValidationHooks)',\n            ]),\n            functionName: 'init',\n            args: [\n                moduleConfigs(input.setup.validators),\n                moduleConfigs(input.setup.executors),\n                { module: zeroAddress, initData: '0x' },\n                moduleConfigs(input.setup.fallbacks),\n                [],\n            ],\n        });\n    }\n    return encodeAbiParameters([{ type: 'address' }, { type: 'bytes' }], [STARTALE_BOOTSTRAP_ADDRESS, bootstrapData]);\n}\nfunction startaleMaterial(input) {\n    if (input.account.kind !== 'startale') {\n        throw new Error('Expected Startale account');\n    }\n    if (input.eoa)\n        return { address: input.eoa.address };\n    if (input.initData && !('factory' in input.initData)) {\n        return { address: input.initData.address };\n    }\n    let factory = STARTALE_FACTORY_ADDRESS;\n    let factoryData;\n    let salt;\n    let initializationCallData;\n    if (input.initData && 'factory' in input.initData) {\n        if (input.initData.factory.toLowerCase() === STARTALE_1_0_0_FACTORY_ADDRESS) {\n            throw new AccountConfigurationNotSupportedError(\"Startale v1.0.0 accounts are not supported; this SDK only supports Startale v1.0.1. Use @rhinestone/sdk v2 with `account: { type: 'startale', version: '1.0.0' }` for existing v1.0.0 accounts.\", 'startale', { context: { factory: input.initData.factory } });\n        }\n        try {\n            const decoded = decodeFunctionData({\n                abi: parseAbi(['function createAccount(bytes,bytes32)']),\n                data: input.initData.factoryData,\n            });\n            factory = input.initData.factory;\n            factoryData = input.initData.factoryData;\n            salt = decoded.args[1];\n            initializationCallData = encodeFunctionData({\n                abi: parseAbi(['function initializeAccount(bytes)']),\n                functionName: 'initializeAccount',\n                args: [decoded.args[0]],\n            });\n        }\n        catch {\n            return { address: input.initData.address };\n        }\n    }\n    else {\n        salt = selectedValue(input.account.salt, STARTALE_SALT_DEFAULTS);\n        const initData = startaleInitData(input);\n        factoryData = encodeFunctionData({\n            abi: parseAbi(['function createAccount(bytes,bytes32)']),\n            functionName: 'createAccount',\n            args: [initData, salt],\n        });\n        initializationCallData = encodeFunctionData({\n            abi: parseAbi(['function initializeAccount(bytes)']),\n            functionName: 'initializeAccount',\n            args: [initData],\n        });\n    }\n    const accountInitData = encodeAbiParameters([{ type: 'address' }, { type: 'bytes' }], [STARTALE_IMPLEMENTATION_ADDRESS, initializationCallData]);\n    const hash = keccak256(encodePacked(['bytes1', 'address', 'bytes32', 'bytes32'], [\n        '0xff',\n        factory,\n        salt,\n        keccak256(concat([STARTALE_CREATION_CODE, accountInitData])),\n    ]));\n    return { address: slice(hash, 12, 32), factory, factoryData };\n}\nexport function createStartaleAdapter(construction) {\n    if (construction.account.kind !== 'startale') {\n        throw new Error('Expected Startale account');\n    }\n    const validator = construction.setup.validators[0]?.address ?? zeroAddress;\n    return {\n        account: construction.account,\n        capabilities: {\n            modular: true,\n            supportsDeployment: true,\n            supportsUserOperations: true,\n            supportsEip7702Adoption: false,\n            supportsSmartSessions: true,\n            supportsOriginSignatureReuse: true,\n            signatureEnvelope: { kind: 'startale', validator },\n        },\n        getIdentity: (input) => ({\n            definition: input.account,\n            address: startaleMaterial(input).address,\n        }),\n        getDeploymentPlan: (input) => deploymentPlan(input.chain, startaleMaterial(input), input.deployed),\n        encodeCalls: encodeErc7579Calls,\n        encodeModuleInstallation: (module) => [encodeInstallModule(module)],\n        encodeModuleUninstallation: encodeUninstallModule,\n        encodeSignatureEnvelope: ({ envelope, validatorContribution }) => {\n            if (envelope.kind !== 'startale') {\n                throw new Error('Expected Startale envelope');\n            }\n            return encodeAddressEnvelope(envelope.validator, validatorContribution, K1_DEFAULT_VALIDATOR_ADDRESS);\n        },\n    };\n}\n","export const K1_DEFAULT_VALIDATOR_ADDRESS = '0x00000072f286204bb934ed49d8969e86f7dec7b1';\n","import { createEoaAdapter } from './adapters/eoa.js';\nimport { createHcaAdapter } from './adapters/hca.js';\nimport { createKernelAdapter } from './adapters/kernel.js';\nimport { createNexusAdapter } from './adapters/nexus.js';\nimport { createSafeAdapter } from './adapters/safe.js';\nimport { createStartaleAdapter } from './adapters/startale.js';\nexport function createAccountAdapter(construction) {\n    switch (construction.account.kind) {\n        case 'safe':\n            return createSafeAdapter(construction);\n        case 'nexus':\n            return createNexusAdapter(construction);\n        case 'kernel':\n            return createKernelAdapter(construction);\n        case 'startale':\n            return createStartaleAdapter(construction);\n        case 'hca':\n            return createHcaAdapter(construction);\n        case 'eoa':\n            return createEoaAdapter(construction);\n    }\n}\n","import { createAccountConstruction } from '../accounts/construction.js';\nimport { createAccountAdapter } from '../accounts/registry.js';\nexport function createStaticAccountRuntime(resolved, chain, deployed) {\n    const construction = createAccountConstruction({\n        material: accountMaterial(resolved),\n        chain,\n        deployed,\n    });\n    const adapter = createAccountAdapter(construction);\n    return {\n        construction,\n        adapter,\n        identity: adapter.getIdentity(construction),\n    };\n}\nexport function accountMaterial(resolved) {\n    return {\n        account: resolved.account,\n        ...(resolved.owners ? { owner: resolved.owners } : {}),\n        modules: resolved.modules,\n        ...(resolved.initData ? { initData: resolved.initData } : {}),\n        ...(resolved.eoa ? { eoa: resolved.eoa } : {}),\n        sessions: {\n            enabled: resolved.sessions.enabled,\n            environment: resolved.sessions.environment,\n            ...(resolved.sessions.module.source === 'explicit'\n                ? { module: resolved.sessions.module.address }\n                : {}),\n            ...(resolved.sessions.compatibilityFallback.source === 'explicit'\n                ? {\n                    compatibilityFallback: resolved.sessions.compatibilityFallback.address,\n                }\n                : {}),\n        },\n    };\n}\n","/**\n * Thrown by the HyperCore helpers — building an action or reading Hyperliquid's\n * public info endpoint. Kept distinct from `OrchestratorError` so a bad order\n * is catchable separately from a failed quote.\n */\nexport class HyperCoreError extends Error {\n}\nexport function isHyperCoreError(error) {\n    return error instanceof HyperCoreError;\n}\n/** The ticker is not in Hyperliquid's perp universe. */\nexport class UnknownPerpAssetError extends HyperCoreError {\n    asset;\n    constructor(asset) {\n        super(`No Hyperliquid perp market named \"${asset}\". Tickers are the coin alone (\\`BTC\\`, not \\`BTC-PERP\\`); list them with \\`getPerpMarkets()\\`.`);\n        this.asset = asset;\n    }\n}\n/**\n * The order is below Hyperliquid's minimum order value. Raised here rather than\n * left to the exchange because an intent that delivers collateral is refused\n * only after the funds have landed on HyperCore.\n */\nexport class PerpOrderTooSmallError extends HyperCoreError {\n    size;\n    notionalUsd;\n    minimumUsd;\n    constructor(asset, size, notionalUsd, minimumUsd) {\n        super(`A ${asset} order of ${size} is worth $${notionalUsd}, below Hyperliquid's $${minimumUsd} minimum order value. Ask for more: a size is floored to the asset's precision, so a request only just over the minimum can land under it.`);\n        this.size = size;\n        this.notionalUsd = notionalUsd;\n        this.minimumUsd = minimumUsd;\n    }\n}\n/** There is nothing to close: the account holds no position on that asset. */\nexport class NoOpenPerpPositionError extends HyperCoreError {\n    asset;\n    account;\n    constructor(asset, account) {\n        super(`${account} holds no open ${asset} position to close. Check with \\`getPerpPosition\\` before offering a close — a reduce-only order against nothing is rejected by the exchange.`);\n        this.asset = asset;\n        this.account = account;\n    }\n}\n/** Hyperliquid's info endpoint answered with a non-2xx status. */\nexport class HyperCoreInfoRequestError extends HyperCoreError {\n    status;\n    url;\n    constructor(url, status, body) {\n        super(`Hyperliquid info request to ${url} failed with status ${status}${body ? `: ${body.slice(0, 200)}` : ''}`);\n        this.status = status;\n        this.url = url;\n    }\n}\n","// Reads of Hyperliquid's public `info` endpoint — the market metadata an order\n// needs and cannot be derived: the asset INDEX an order carries, the size\n// precision it must round to, and the mark to price against.\n//\n// `prepareTransaction` does these reads itself when a transaction carries\n// `hyperCore.openPerp` or `hyperCore.closePerp`. What is exported here is for the\n// questions a caller asks BEFORE sending one: which markets exist, what leverage\n// one allows, whether there is a position to close at all.\nimport { HyperCoreInfoRequestError, UnknownPerpAssetError } from './errors.js';\n/** Hyperliquid's mainnet API. */\nconst HYPERLIQUID_API_URL = 'https://api.hyperliquid.xyz';\nasync function readInfo(body, options) {\n    const url = `${options?.apiUrl ?? HYPERLIQUID_API_URL}/info`;\n    const request = options?.fetch ?? globalThis.fetch;\n    const response = await request(url, {\n        method: 'POST',\n        headers: { 'content-type': 'application/json' },\n        body: JSON.stringify(body),\n    });\n    if (!response.ok) {\n        const text = await response.text().catch(() => '');\n        throw new HyperCoreInfoRequestError(url, response.status, text);\n    }\n    return (await response.json());\n}\n/**\n * List every tradeable Hyperliquid perpetual market.\n *\n * Delisted assets are left out, but the index of the ones returned is their\n * position in the full universe — Hyperliquid never renumbers it, and it is\n * what an order carries.\n *\n * @param options where to reach Hyperliquid's info endpoint\n * @returns one entry per tradeable perp market, with a live mark price\n * @example\n * const markets = await getPerpMarkets()\n * markets.map((market) => market.asset) // ['BTC', 'ETH', ...]\n * @see {@link getPerpMarket}\n */\nasync function getPerpMarkets(options) {\n    const [meta, contexts] = await readInfo({ type: 'metaAndAssetCtxs' }, options);\n    return meta.universe\n        .map((entry, assetIndex) => ({ entry, assetIndex }))\n        .filter(({ entry }) => !entry.isDelisted)\n        .map(({ entry, assetIndex }) => ({\n        asset: entry.name,\n        assetIndex,\n        szDecimals: entry.szDecimals,\n        maxLeverage: entry.maxLeverage,\n        markPx: contexts[assetIndex]?.markPx ?? '',\n    }));\n}\n/**\n * Read one Hyperliquid perpetual market by ticker.\n *\n * A transaction carrying `hyperCore.openPerp` does this read itself, so reach\n * for this when you need the market's own facts — its mark to quote a size\n * against, or its `maxLeverage` before offering one.\n *\n * @param asset ticker as Hyperliquid names it — the coin alone, e.g. `BTC`\n * @param options where to reach Hyperliquid's info endpoint\n * @returns the market, including its asset index, size precision, and mark\n * @throws {UnknownPerpAssetError} if no tradeable market carries that ticker\n * @example\n * const market = await getPerpMarket('BTC')\n * const maxNotional = Number(market.markPx) * market.maxLeverage\n * @see {@link getPerpMarkets}\n */\nasync function getPerpMarket(asset, options) {\n    const markets = await getPerpMarkets(options);\n    const market = markets.find((entry) => entry.asset === asset);\n    if (!market)\n        throw new UnknownPerpAssetError(asset);\n    return market;\n}\n/**\n * List an account's open Hyperliquid perpetual positions.\n *\n * @param account the account holding the positions — the smart account itself,\n *   since that is what the intent delivers collateral to\n * @param options where to reach Hyperliquid's info endpoint\n * @returns one entry per open position; empty when the account holds none\n * @see {@link getPerpPosition}\n */\nasync function getPerpPositions(account, options) {\n    const state = await readInfo({ type: 'clearinghouseState', user: account }, options);\n    return (state.assetPositions ?? []).flatMap(({ position }) => position?.coin && position.szi\n        ? [\n            {\n                asset: position.coin,\n                size: position.szi,\n                entryPx: position.entryPx ?? '0',\n                leverage: position.leverage?.value ?? 1,\n            },\n        ]\n        : []);\n}\n/**\n * Read an account's open position on one Hyperliquid perpetual market.\n *\n * A transaction carrying `hyperCore.closePerp` does this read itself and is\n * rejected when there is nothing to close, so this is the check to make before\n * offering a close at all.\n *\n * @param account the account holding the position\n * @param asset ticker as Hyperliquid names it, e.g. `BTC`\n * @param options where to reach Hyperliquid's info endpoint\n * @returns the position, or `null` when the account has none open on that asset\n * @example\n * const position = await getPerpPosition(account.getAddress('evm'), 'BTC')\n * if (position) {\n *   // offer a close\n * }\n * @see {@link getPerpPositions}\n */\nasync function getPerpPosition(account, asset, options) {\n    const positions = await getPerpPositions(account, options);\n    return positions.find((position) => position.asset === asset) ?? null;\n}\nexport { getPerpMarket, getPerpMarkets, getPerpPosition, getPerpPositions };\n","// Hyperliquid's order arithmetic, and nothing else. Pure: everything these need\n// is an argument, and `resolve.ts` is what reads it from Hyperliquid.\n//\n// What they own is the part a caller should never have to reconstruct — the\n// asset INDEX an order carries instead of a ticker, the tick and size grids a\n// price and size must land on, and a limit priced far enough through the book to\n// still cross when the intent delivers ~30s later.\nimport { HyperCoreError, PerpOrderTooSmallError } from './errors.js';\n/** How far through the mark a marketable limit is placed, when not given. */\nconst DEFAULT_SLIPPAGE_BPS = 50;\n/**\n * Hyperliquid's cap on a perp price's significant figures. Integer prices are\n * exempt from it, which we do not exploit — five figures is always accepted,\n * and at any price where the difference shows it is far inside the slippage.\n */\nconst MAX_PRICE_SIGNIFICANT_FIGURES = 5;\n/** A perp price may carry `6 - szDecimals` decimals. */\nconst PERP_PRICE_DECIMAL_BUDGET = 6;\n/** Hyperliquid refuses an order worth less than this. */\nconst MIN_ORDER_VALUE_USD = 10;\n/**\n * A marketable IOC that opens a position: it fills against the book at up to\n * `slippageBps` through the mark and cancels the rest, which is how a market\n * order is expressed on Hyperliquid.\n */\nfunction buildOpenPerpOrder(market, request) {\n    const mark = markPrice(market);\n    const size = request.size === undefined\n        ? request.notionalUsd / mark\n        : Number(request.size);\n    return orderAction({\n        market,\n        mark,\n        isBuy: request.direction === 'long',\n        size,\n        reduceOnly: false,\n        slippageBps: request.slippageBps,\n        ...(request.cloid ? { cloid: request.cloid } : {}),\n    });\n}\n/**\n * A reduce-only marketable IOC in the direction that flattens the position,\n * sized from the position itself.\n */\nfunction buildClosePerpOrder(market, position, request) {\n    const held = Number(position.size);\n    const open = Math.abs(held);\n    const size = request.size === undefined ? open : Number(request.size);\n    if (size > open) {\n        throw new HyperCoreError(`Cannot close ${size} ${request.asset} against an open position of ${open}. Hyperliquid rejects a reduce-only order larger than the position it reduces.`);\n    }\n    return orderAction({\n        market,\n        mark: markPrice(market),\n        // Flatten: sell a long, buy back a short.\n        isBuy: held < 0,\n        size,\n        reduceOnly: true,\n        slippageBps: request.slippageBps,\n        ...(request.cloid ? { cloid: request.cloid } : {}),\n    });\n}\nfunction orderAction(input) {\n    const { market, mark, isBuy, reduceOnly } = input;\n    const slippageBps = input.slippageBps ?? DEFAULT_SLIPPAGE_BPS;\n    if (!Number.isInteger(slippageBps) ||\n        slippageBps < 0 ||\n        slippageBps > 10_000) {\n        throw new HyperCoreError(`slippageBps must be a whole number of basis points between 0 and 10000, got ${input.slippageBps}.`);\n    }\n    if (!Number.isFinite(input.size)) {\n        throw new HyperCoreError(`Order size for ${market.asset} is not a number: ${input.size}.`);\n    }\n    const limit = mark * (isBuy ? 1 + slippageBps / 10_000 : 1 - slippageBps / 10_000);\n    const p = formatPerpPrice(limit, market.szDecimals, isBuy);\n    const s = formatPerpSize(input.size, market.szDecimals);\n    if (Number(s) <= 0) {\n        throw new HyperCoreError(`An order size of ${input.size} rounds to zero at ${market.asset}'s ${market.szDecimals} decimals of size precision.`);\n    }\n    // Reduce-only orders are exempt from the minimum on Hyperliquid's side, and\n    // enforcing it here would leave a dust position with no way to close it.\n    const notional = Number(s) * mark;\n    if (!reduceOnly && notional < MIN_ORDER_VALUE_USD) {\n        throw new PerpOrderTooSmallError(market.asset, s, Math.round(notional * 100) / 100, MIN_ORDER_VALUE_USD);\n    }\n    const order = {\n        a: market.assetIndex,\n        b: isBuy,\n        p,\n        s,\n        r: reduceOnly,\n        t: { limit: { tif: 'Ioc' } },\n        ...(input.cloid ? { c: input.cloid } : {}),\n    };\n    return { type: 'order', orders: [order], grouping: 'na' };\n}\nfunction markPrice(market) {\n    const mark = Number(market.markPx);\n    if (!Number.isFinite(mark) || mark <= 0) {\n        throw new HyperCoreError(`Hyperliquid reported no usable mark price for ${market.asset} (got ${JSON.stringify(market.markPx)}), so an order cannot be priced against it.`);\n    }\n    return mark;\n}\n/**\n * Round a price onto Hyperliquid's grid: at most 5 significant figures, and at\n * most `6 - szDecimals` decimals.\n *\n * Rounded in the direction that keeps the order marketable — up for a buy, down\n * for a sell — so the grid never eats the slippage it was given.\n */\nfunction formatPerpPrice(price, szDecimals, roundUp) {\n    const decimals = Math.max(0, PERP_PRICE_DECIMAL_BUDGET - szDecimals);\n    const significant = roundSignificant(price, MAX_PRICE_SIGNIFICANT_FIGURES, roundUp);\n    return trimDecimal(roundToGrid(significant, decimals, roundUp).toFixed(decimals));\n}\n/** Round a size down onto the asset's size grid — never up past what was asked. */\nfunction formatPerpSize(size, szDecimals) {\n    return trimDecimal(roundToGrid(size, szDecimals, false).toFixed(szDecimals));\n}\nfunction roundSignificant(value, digits, roundUp) {\n    if (value === 0)\n        return 0;\n    const magnitude = Math.floor(Math.log10(Math.abs(value)));\n    return roundToFactor(value, 10 ** (digits - 1 - magnitude), roundUp);\n}\nfunction roundToGrid(value, decimals, roundUp) {\n    return roundToFactor(value, 10 ** decimals, roundUp);\n}\nfunction roundToFactor(value, factor, roundUp) {\n    // Binary floats leave dust in the last ulp, and `ceil`/`floor` would turn it\n    // into a whole extra tick. 15 digits is the widest a double carries exactly,\n    // so it clears the dust without rounding away a digit the caller meant.\n    const scaled = Number((value * factor).toPrecision(15));\n    return (roundUp ? Math.ceil(scaled) : Math.floor(scaled)) / factor;\n}\n/**\n * Hyperliquid normalises a decimal before encoding it, so `\"1.50\"` and `\"1.5\"`\n * are one price with two spellings. Emitting the normalised one keeps the\n * string a caller reads in the action identical to the one that gets hashed\n * into the agent authorising it.\n */\nfunction trimDecimal(value) {\n    if (!value.includes('.'))\n        return value;\n    const trimmed = value.replace(/0+$/, '').replace(/\\.$/, '');\n    return trimmed === '' || trimmed === '-' ? '0' : trimmed;\n}\nexport { buildClosePerpOrder, buildOpenPerpOrder, formatPerpPrice, formatPerpSize, };\n","// Turns the declarative `hyperCore` on a transaction into the concrete action\n// the orchestrator quotes against.\n//\n// This runs inside `prepareTransaction`, before the quote, because that is the\n// last moment it can: the agent authorising the action is derived from the\n// action's own bytes, and the quote's `signData` carries a registration for that\n// agent. Nothing about the action — the price included — can be chosen after.\nimport { NoOpenPerpPositionError } from './errors.js';\nimport { getPerpMarket, getPerpPosition, } from './market.js';\nimport { buildClosePerpOrder, buildOpenPerpOrder } from './orders.js';\nexport async function resolveHyperCoreAction(input) {\n    const { options } = input;\n    if (!options)\n        return undefined;\n    if (options.action)\n        return options.action;\n    if (options.openPerp) {\n        const market = await getPerpMarket(options.openPerp.asset, input.hyperliquid);\n        return buildOpenPerpOrder(market, options.openPerp);\n    }\n    const request = options.closePerp;\n    const [market, position] = await Promise.all([\n        getPerpMarket(request.asset, input.hyperliquid),\n        getPerpPosition(input.account, request.asset, input.hyperliquid),\n    ]);\n    if (!position) {\n        throw new NoOpenPerpPositionError(request.asset, input.account);\n    }\n    return buildClosePerpOrder(market, position, request);\n}\n","import { hashTypedData, keccak256, stringToHex, } from 'viem';\nimport { resolveCalls } from '../../calls/resolve.js';\nimport { isHyperCoreWireId, toEvmChainReference } from '../../chains/caip2.js';\nimport { isSponsoredIntentInput, projectCompatibleIntentInput, } from '../../clients/orchestrator/normalized.js';\nimport { UnsupportedSigningRequestError } from '../../errors/execution.js';\nimport { defineValidator } from '../../modules/validators/definition.js';\nimport { ecdsaSignerId } from '../../modules/validators/signer-id.js';\nimport { signingTopology } from '../../signing/plan.js';\nimport { projectIntentAccount } from './account.js';\nimport { normalizeIntentQuote } from './normalize.js';\nimport { originChainId } from './origin-chain.js';\nimport { selectIntentQuote } from './quotes.js';\nimport { buildIntentRequest } from './request.js';\nimport { prepareIntentSessions } from './sessions.js';\nexport async function prepareIntent(context, input) {\n    const accountChain = selectAccountChain(input);\n    const runtime = await context.account.forChain(accountChain);\n    const calls = await resolveDestinationCalls(context, input, runtime);\n    const source = await resolveSourceCalls(context, input, runtime);\n    const sessions = await prepareIntentSessions({\n        intent: input,\n        runtime,\n        context,\n    });\n    const ownerSelection = input.signers?.kind === 'owner' ? input.signers : undefined;\n    const { request, normalized } = buildIntentRequest({\n        transaction: sessions\n            ? { ...input, signatureMode: sessions.signatureMode }\n            : input,\n        account: projectIntentAccount({\n            runtime,\n            setupOverride: input.accountSetupOverride,\n            ...(input.eip7702InitSignature\n                ? { eip7702InitSignature: input.eip7702InitSignature }\n                : {}),\n        }),\n        ...(sessions ? { mockSignatures: sessions.mockSignatures } : {}),\n        calls,\n        sourceCalls: mergeSourceCalls(sessions?.preClaimCalls, source.calls),\n        providedFunds: source.providedFunds,\n    });\n    const response = await context.quoteClient.createQuote(request, {\n        intentInput: projectCompatibleIntentInput(normalized),\n        sponsored: isSponsoredIntentInput(normalized),\n    });\n    const quote = normalizeIntentQuote(selectIntentQuote(response.routes));\n    const quotes = response.routes.map((candidate) => candidate.intentId === quote.intentId\n        ? quote\n        : normalizeIntentQuote(candidate));\n    return {\n        traceId: response.traceId,\n        input,\n        request,\n        normalized,\n        quote,\n        quotes,\n        signing: buildIntentSigningInput(runtime, quote, sessions?.byChain, ownerSelection?.validator, ownerSelection?.signerIds),\n        accountChain,\n        ...(sessions\n            ? {\n                resolvedSessions: sessions.byChain,\n                sessionEnvironment: runtime.construction.sessions.environment,\n            }\n            : {}),\n    };\n}\n// The chain whose runtime hosts the account: identity, address derivation, and\n// the RPC reads that follow. The destination serves when it is a real execution\n// chain, and otherwise a source chain does.\n//\n// `kind === 'evm'` alone is not that test. HyperCore is EVM-ADDRESSED — hex\n// recipients, EIP-712 — while being virtual: it has no RPC of its own and hosts\n// no accounts, so materializing a runtime on it asks viem for a transport that\n// cannot exist. That went unnoticed while HyperCore was chain 1337, because viem\n// ships a `Localhost` chain with that exact id and quietly supplied\n// `http://127.0.0.1:8545`; the venue ids have no viem chain, so the synthesised\n// one has empty `rpcUrls` and the call fails with `UrlRequiredError` (RHI-5510).\nfunction selectAccountChain(input) {\n    if (input.destination.kind === 'evm' &&\n        !isHyperCoreWireId(input.destination.id)) {\n        return input.destination;\n    }\n    const source = input.sourceChains?.at(-1);\n    if (!source) {\n        throw new Error(`An intent to ${input.destination.caip2} requires at least one EVM source chain: the destination hosts no account runtime`);\n    }\n    return source;\n}\nasync function resolveDestinationCalls(context, input, runtime) {\n    if (input.destination.kind === 'non-evm') {\n        if (input.calls.length > 0) {\n            throw new Error(`Destination calls are not supported for ${input.destination.caip2}`);\n        }\n        return [];\n    }\n    return resolveCalls(input.calls, {\n        account: runtime.identity.address,\n        chain: input.destination,\n        config: context.compatibilityConfig,\n    });\n}\nasync function resolveSourceCalls(context, input, runtime) {\n    const allowed = new Map((input.sourceChains ?? []).map((chain) => [chain.id, chain]));\n    if (input.destination.kind === 'evm') {\n        allowed.set(input.destination.id, input.destination);\n    }\n    const calls = {};\n    const providedFunds = {};\n    for (const [chainIdValue, sourceCalls] of Object.entries(input.sourceCalls ?? {})) {\n        const chainId = Number(chainIdValue);\n        const chain = allowed.get(chainId);\n        if (!chain)\n            throw new Error(`Invalid source calls chain ${chainId}`);\n        calls[chainId] = await resolveCalls(sourceCalls.map(({ call }) => call), {\n            account: runtime.identity.address,\n            chain,\n            config: context.compatibilityConfig,\n        });\n        for (const sourceCall of sourceCalls) {\n            for (const provided of sourceCall.provides ?? []) {\n                const balances = (providedFunds[chainId] ??= {});\n                balances[provided.token] =\n                    (balances[provided.token] ?? 0n) + provided.amount;\n            }\n        }\n    }\n    return { calls, providedFunds };\n}\n// Only read for EIP-712 requests, which produce a signing artifact. A\n// delegation is answered by the 7702 signer and has no artifact, so its entry\n// exists for exhaustiveness rather than because anything looks it up.\nconst PURPOSE_USAGE = {\n    originAuthorization: 'intent-origin',\n    destinationAuthorization: 'intent-destination',\n    targetExecutionAuthorization: 'intent-target',\n    delegationAuthorization: 'intent-origin',\n};\n/**\n * Classifies each quote signing request for local execution, preserving the\n * quoted order as the identity of every authorisation.\n */\nfunction classifyRequests(requests, sessions, binding) {\n    const signed = [];\n    return requests.map((request, index) => {\n        const purpose = request.purpose;\n        assertRequestIsOurs(request, index, binding);\n        switch (request.payload.kind) {\n            case 'eip712': {\n                const typedData = request.payload.typedData;\n                const chain = toEvmChainReference(originChainId(typedData));\n                const digest = hashTypedData(typedData);\n                const identity = signerIdentity(request);\n                const artifactId = `request-${index}`;\n                const session = sessions?.[chain.id];\n                const shape = purpose === 'originAuthorization' && session?.verifyExecutions\n                    ? 'session-claims'\n                    : 'hex';\n                // Reuse is decided by what is actually being authorised, never by role:\n                // the same account signing the same payload under the same authority\n                // produces the same bytes, and anything else is a distinct ceremony.\n                const match = signed.find((candidate) => candidate.digest === digest && candidate.identity === identity);\n                if (!match) {\n                    signed.push({ digest, identity, artifactId, shape });\n                }\n                return {\n                    kind: 'eip712',\n                    index,\n                    purpose,\n                    artifactId,\n                    signatureFormat: request.payload.signatureFormat,\n                    payload: {\n                        id: digest,\n                        chain,\n                        typedData,\n                        usage: PURPOSE_USAGE[purpose],\n                    },\n                    shape: match ? 'hex' : shape,\n                    ...(match\n                        ? {\n                            reuse: {\n                                artifactId: match.artifactId,\n                                selection: match.shape === 'session-claims'\n                                    ? 'pre-claim'\n                                    : 'whole',\n                            },\n                        }\n                        : {}),\n                    // Every slot the owners have to sign themselves, which is every\n                    // non-reused payload: a target execution authorization is as much\n                    // theirs as an origin one, and dropping it here would leave the\n                    // proof vector permanently short.\n                    exposedForIndependentSigning: !sessions && !match,\n                };\n            }\n            case 'eip7702':\n                return {\n                    kind: 'eip7702',\n                    index,\n                    purpose,\n                    chainId: request.payload.authorization.chainId,\n                    contract: request.payload.authorization.address,\n                };\n            case 'personalSign':\n                return {\n                    kind: 'personalSign',\n                    index,\n                    purpose,\n                    message: request.payload.message.value,\n                };\n            default:\n                return {\n                    kind: 'unsupported',\n                    index,\n                    purpose,\n                    payloadKind: request.payload.kind,\n                };\n        }\n    });\n}\nfunction signingRequestBinding(runtime) {\n    return {\n        address: runtime.identity.address,\n        ...(runtime.construction.eoa\n            ? { eoa: runtime.construction.eoa.address }\n            : {}),\n        // Only the EOA adapter passes the signer's bytes through untouched; every\n        // smart account wraps them in its validator envelope.\n        signsRawKey: runtime.identity.definition.kind === 'eoa',\n    };\n}\nfunction sameAddress(left, right) {\n    return left.toLowerCase() === right.toLowerCase();\n}\n/**\n * Refuses a signing request that is not this account's to answer.\n *\n * A quote can legitimately name another subject — a configured recipient that\n * adopts EIP-7702 gets its own delegation request — and signing it with our\n * key would produce a proof the orchestrator rejects at recovery, after the\n * user has already been prompted.\n */\nfunction assertRequestIsOurs(request, index, binding) {\n    const refuse = (reason) => {\n        throw new UnsupportedSigningRequestError({\n            index,\n            payloadKind: request.payload.kind,\n            reason,\n        });\n    };\n    if (request.payload.kind !== 'eip712' && request.payload.kind !== 'eip7702') {\n        return;\n    }\n    if (request.account.vm !== 'evm') {\n        refuse(`Signing request ${index} is for a ${request.account.vm} account, which this EVM account cannot sign for.`);\n        return;\n    }\n    if (!sameAddress(request.account.address, binding.address)) {\n        refuse(`Signing request ${index} names account ${request.account.address}, not ${binding.address}. This SDK only signs for its own account.`);\n    }\n    if (request.payload.kind === 'eip7702') {\n        if (request.authority.kind !== 'secp256k1' ||\n            (binding.eoa && !sameAddress(request.authority.address, binding.eoa))) {\n            refuse(`Signing request ${index} asks ${authorityLabel(request.authority)} for an EIP-7702 delegation; this account delegates with ${binding.eoa ?? 'no EOA'}.`);\n        }\n        return;\n    }\n    const wantsRawKey = request.payload.signatureFormat === 'secp256k1';\n    if (wantsRawKey !== binding.signsRawKey) {\n        refuse(`Signing request ${index} asks for a \\`${request.payload.signatureFormat}\\` signature, which this account does not produce.`);\n    }\n}\nfunction authorityLabel(authority) {\n    return authority.kind === 'swigRole'\n        ? `Swig role ${authority.roleId}`\n        : authority.address;\n}\n/**\n * Who has to produce the signature, and for which account. Two requests with\n * the same payload but different authorities are different authorisations.\n */\nfunction signerIdentity(request) {\n    const account = request.account.vm === 'evm'\n        ? `evm:${request.account.address.toLowerCase()}`\n        : `svm:${request.account.wallet}`;\n    const signer = request.authority;\n    const authority = signer.kind === 'swigRole'\n        ? `swigRole:${signer.roleId}:${(signer.authority.kind === 'secp256k1'\n            ? signer.authority.address\n            : signer.authority.publicKey).toLowerCase()}`\n        : `${signer.kind}:${signer.address.toLowerCase()}`;\n    return `${account}|${authority}|${request.payload.kind === 'eip712' ? request.payload.signatureFormat : ''}`;\n}\nconst EVM_SIGNABLE_PAYLOADS = new Set(['eip712', 'eip7702']);\n/**\n * Refuses a quote asking for a payload an EVM account runtime cannot produce —\n * a WebAuthn challenge, or the personal-sign spend a Swig origin needs.\n *\n * Checked before any account state is read, so an unsupported quote fails\n * immediately rather than after an RPC round trip, and long before the ordered\n * proof vector is half built.\n */\nexport function assertSupportedSigningRequests(requests) {\n    const index = requests.findIndex(({ payload }) => !EVM_SIGNABLE_PAYLOADS.has(payload.kind));\n    if (index === -1)\n        return;\n    throw new UnsupportedSigningRequestError({\n        index,\n        payloadKind: requests[index].payload.kind,\n    });\n}\nexport function buildIntentSigningInput(runtime, quote, sessions, ownerValidator, selectedSignerIds) {\n    assertSupportedSigningRequests(quote.signingRequests);\n    const requests = classifyRequests(quote.signingRequests, sessions, signingRequestBinding(runtime));\n    const sessionTopology = sessions\n        ? signingTopology(defineValidator(requireSession(sessions).session.owners, 'smart-session-validator'))\n        : undefined;\n    const selectedOwner = ownerValidator ?? runtime.construction.owner;\n    const topology = sessionTopology\n        ? sessionTopology\n        : selectedOwner\n            ? signingTopology(selectedOwner, selectedSignerIds)\n            : {\n                configuredTopology: {\n                    rootValidatorId: 'eoa',\n                    validators: [],\n                    threshold: 1,\n                },\n                effectiveSelection: {\n                    validatorIds: [],\n                    signerIds: runtime.construction.eoa\n                        ? [ecdsaSignerId(runtime.construction.eoa)]\n                        : [],\n                    threshold: 1,\n                },\n            };\n    const signable = requests.filter((request) => request.kind === 'eip712');\n    const first = signable[0];\n    if (!first)\n        throw new Error('Intent quote has no EIP-712 signing requests');\n    return {\n        // Standalone `signIntent(requests)` builds a synthetic quote with no\n        // intentId; fall back to the first payload hash so the signing-task\n        // namespace stays deterministic rather than relying on `stringToHex`\n        // coercing `undefined` to an empty string.\n        id: quote.intentId\n            ? keccak256(stringToHex(quote.intentId))\n            : first.payload.id,\n        preparedSignatureMode: sessions\n            ? Object.values(sessions).some(({ verifyExecutions }) => verifyExecutions)\n                ? 'session-with-execution-verification'\n                : 'session'\n            : 'default',\n        ...topology,\n        requests,\n        artifacts: signable.map((request) => ({\n            id: request.artifactId,\n            usage: request.payload.usage,\n            payloadId: request.payload.id,\n            cardinality: 'one',\n            shape: request.shape,\n            exposedForIndependentSigning: request.exposedForIndependentSigning,\n        })),\n    };\n}\nfunction requireSession(sessions) {\n    const session = Object.values(sessions)[0];\n    if (!session)\n        throw new Error('Intent session selection is empty');\n    return session;\n}\nfunction mergeSourceCalls(first, second) {\n    const result = { ...first };\n    for (const [chainId, calls] of Object.entries(second)) {\n        result[Number(chainId)] = [...(result[Number(chainId)] ?? []), ...calls];\n    }\n    return result;\n}\n","function isLazyCall(call) {\n    return 'resolve' in call && typeof call.resolve === 'function';\n}\nexport async function resolveCalls(calls, context) {\n    const resolved = [];\n    for (const call of calls) {\n        if (!isLazyCall(call)) {\n            resolved.push(call);\n            continue;\n        }\n        const value = await call.resolve(context);\n        resolved.push(...(Array.isArray(value) ? value : [value]));\n    }\n    return resolved;\n}\n","export class SigningPipelineError extends Error {\n    context;\n    constructor(message, context, options) {\n        super(message, options);\n        this.name = 'SigningPipelineError';\n        this.context = context;\n    }\n}\nexport function runSigningStep(input) {\n    try {\n        return input.operation();\n    }\n    catch (cause) {\n        if (cause instanceof SigningPipelineError)\n            throw cause;\n        throw new SigningPipelineError(`Signing artifact ${input.artifactId} failed during ${input.failureStage}`, {\n            planKind: input.plan.kind,\n            payloadKind: input.plan.payload.kind,\n            failureStage: input.failureStage,\n            stageId: input.stageId,\n            artifactId: input.artifactId,\n            usage: input.usage,\n        }, { cause });\n    }\n}\n","import { SigningPipelineError } from './error.js';\nexport function validateSigningPlan(plan) {\n    const stageIds = new Set();\n    const taskIds = new Set();\n    const artifactIds = new Set();\n    const artifactStages = new Map();\n    for (const stage of plan.stages) {\n        assertUnique(stageIds, stage.id, `Duplicate signing stage ${stage.id}`);\n        const declaredPriorOutputs = new Set();\n        for (const prior of stage.priorOutputs) {\n            const key = priorOutputKey(prior);\n            assertUnique(declaredPriorOutputs, key, `Duplicate prior output ${prior.stageId}:${prior.outputId}`);\n            if (artifactStages.get(prior.outputId) !== prior.stageId) {\n                fail(plan, `Prior output ${prior.stageId}:${prior.outputId} is unavailable`, stage.id);\n            }\n        }\n        const scheduled = new Set();\n        const stageTasks = new Set();\n        for (const task of stage.taskTemplates) {\n            assertUnique(taskIds, task.id, `Duplicate signing task ${task.id}`);\n            stageTasks.add(task.id);\n            if (task.payload.source === 'prior-output' &&\n                !declaredPriorOutputs.has(priorOutputKey(task.payload))) {\n                fail(plan, `Signing task ${task.id} uses an undeclared prior output`, stage.id);\n            }\n            if (task.payload.source === 'checkpoint-fact' &&\n                (stage.checkpoint.kind === 'none' ||\n                    task.payload.checkpointId !== stage.checkpoint.id)) {\n                fail(plan, `Signing task ${task.id} uses an undeclared checkpoint`, stage.id);\n            }\n            if (task.when &&\n                (stage.checkpoint.kind !== 'delegation-code' ||\n                    task.when.factId !== stage.checkpoint.id)) {\n                fail(plan, `Signing task ${task.id} uses an undeclared delegation fact`, stage.id);\n            }\n        }\n        for (const batch of stage.schedule) {\n            for (const taskId of batch.taskIds) {\n                if (!stageTasks.has(taskId)) {\n                    fail(plan, `Schedule references unknown task ${taskId}`, stage.id);\n                }\n                assertUnique(scheduled, taskId, `Signing task ${taskId} is scheduled more than once`);\n            }\n        }\n        if (scheduled.size !== stageTasks.size) {\n            fail(plan, `Stage ${stage.id} has unscheduled signing tasks`, stage.id);\n        }\n        for (const artifact of stage.artifacts) {\n            if (artifact.stageId !== stage.id) {\n                fail(plan, `Artifact ${artifact.id} belongs to another stage`, stage.id);\n            }\n            assertUnique(artifactIds, artifact.id, `Duplicate signing artifact ${artifact.id}`);\n            artifactStages.set(artifact.id, stage.id);\n            switch (artifact.input.kind) {\n                case 'task-results':\n                    for (const taskId of artifact.input.taskIds) {\n                        if (!stageTasks.has(taskId)) {\n                            fail(plan, `Artifact ${artifact.id} references a task outside its stage`, stage.id, artifact.id);\n                        }\n                    }\n                    break;\n                case 'reuse-artifact': {\n                    const reference = {\n                        stageId: artifact.input.stageId,\n                        outputId: artifact.input.artifactId,\n                        selection: artifact.input.selection,\n                    };\n                    if (!declaredPriorOutputs.has(priorOutputKey(reference))) {\n                        fail(plan, `Artifact ${artifact.id} uses an undeclared prior output`, stage.id, artifact.id);\n                    }\n                    break;\n                }\n                case 'session-claim-pair':\n                    for (const componentId of [\n                        artifact.input.preClaimArtifactId,\n                        artifact.input.notarizedClaimArtifactId,\n                    ]) {\n                        if (componentId === artifact.id ||\n                            artifactStages.get(componentId) !== stage.id) {\n                            fail(plan, `Session claim pair ${artifact.id} references an unavailable component`, stage.id, artifact.id);\n                        }\n                    }\n                    break;\n            }\n            if (artifact.validatorCodec.kind === 'smart-session-state' &&\n                (stage.checkpoint.kind !== 'session-enabled' ||\n                    stage.checkpoint.id !== artifact.validatorCodec.factId)) {\n                fail(plan, `Artifact ${artifact.id} uses an undeclared session-state fact`, stage.id, artifact.id);\n            }\n            if (artifact.validatorCodec.kind === 'smart-session-state') {\n                const { whenEnabled, whenDisabled } = artifact.validatorCodec;\n                if (whenEnabled.validator.address.toLowerCase() !==\n                    whenDisabled.validator.address.toLowerCase() ||\n                    whenEnabled.permissionId.toLowerCase() !==\n                        whenDisabled.permissionId.toLowerCase()) {\n                    fail(plan, `Artifact ${artifact.id} changes Smart Session identity by state`, stage.id, artifact.id);\n                }\n                if (whenEnabled.mode === 'enable-and-use' ||\n                    whenDisabled.mode !== 'enable-and-use' ||\n                    !whenDisabled.enableData) {\n                    fail(plan, `Artifact ${artifact.id} has an invalid Smart Session state route`, stage.id, artifact.id);\n                }\n            }\n            else if (artifact.validatorCodec.kind === 'smart-session' &&\n                artifact.validatorCodec.mode === 'enable-and-use' &&\n                !artifact.validatorCodec.enableData) {\n                fail(plan, `Artifact ${artifact.id} has no Smart Session enable data`, stage.id, artifact.id);\n            }\n            if (artifact.erc6492.kind !== 'none' && artifact.usage !== 'erc1271') {\n                fail(plan, `ERC-6492 is not permitted for ${artifact.usage}`, stage.id, artifact.id);\n            }\n            if (plan.kind === 'account-message' && artifact.erc7739.kind !== 'none') {\n                fail(plan, 'ERC-7739 is not a message-signing operation', stage.id, artifact.id);\n            }\n        }\n    }\n    const outputIds = new Set();\n    for (const output of plan.publicOutputs) {\n        assertUnique(outputIds, output.id, `Duplicate public output ${output.id}`);\n        if (output.source.kind === 'artifact' &&\n            !artifactIds.has(output.source.artifactId)) {\n            fail(plan, `Public output references unknown artifact ${output.source.artifactId}`);\n        }\n        if (output.source.kind === 'task-result' &&\n            !taskIds.has(output.source.taskId)) {\n            fail(plan, `Public output references unknown task ${output.source.taskId}`);\n        }\n    }\n}\nfunction priorOutputKey(input) {\n    return `${input.stageId}:${input.outputId}:${input.selection}`;\n}\nexport function materializeSigningStage(input) {\n    return {\n        stageId: input.stage.id,\n        facts: input.facts,\n        tasks: input.stage.taskTemplates\n            .filter((template) => taskIsRequired(template, input.facts))\n            .map((template) => materializeTask(template, input)),\n        schedule: input.stage.schedule\n            .map((batch) => ({\n            ...batch,\n            taskIds: batch.taskIds.filter((taskId) => {\n                const template = input.stage.taskTemplates.find(({ id }) => id === taskId);\n                return template && taskIsRequired(template, input.facts);\n            }),\n        }))\n            .filter(({ taskIds }) => taskIds.length > 0),\n    };\n}\nexport function createSingleStageSigningPlan(input) {\n    const taskTemplates = input.tasks.map((task) => ({\n        ...task,\n        ...(input.chain ? { chain: input.chain } : {}),\n        payload: { source: 'plan-payload', payloadId: input.payload.id },\n    }));\n    return {\n        version: 1,\n        kind: input.kind,\n        payload: input.payload,\n        configuredTopology: input.configuredTopology,\n        effectiveSelection: input.effectiveSelection,\n        stages: [\n            {\n                id: input.stageId,\n                checkpoint: input.checkpoint ?? {\n                    kind: 'none',\n                    id: `${input.stageId}-no-read`,\n                },\n                priorOutputs: [],\n                taskTemplates,\n                schedule: taskTemplates.length === 0\n                    ? []\n                    : [\n                        {\n                            id: `${input.stageId}-signers`,\n                            execution: 'parallel',\n                            taskIds: taskTemplates.map(({ id }) => id),\n                        },\n                    ],\n                artifacts: input.artifacts.map((artifact) => ({\n                    ...artifact,\n                    stageId: input.stageId,\n                    input: {\n                        kind: 'task-results',\n                        taskIds: taskTemplates.map(({ id }) => id),\n                    },\n                })),\n            },\n        ],\n        publicOutputs: input.artifacts.map((artifact) => ({\n            id: artifact.id,\n            source: { kind: 'artifact', artifactId: artifact.id },\n            exposedForIndependentSigning: false,\n        })),\n    };\n}\nexport function createValidatorSigningTasks(input) {\n    const selectedSignerIds = input.selectedSignerIds;\n    const factors = input.validator.kind === 'multi-factor'\n        ? input.validator.validators.map((validator) => ({\n            factorId: validator.id,\n            owners: validator.owners,\n        }))\n        : [{ factorId: undefined, owners: input.validator.owners }];\n    const tasks = factors.flatMap((factor) => factor.owners.flatMap((owner) => {\n        if (selectedSignerIds && !selectedSignerIds.includes(owner.signerId)) {\n            return [];\n        }\n        const signer = input.signerReferences[owner.signerId];\n        if (!signer)\n            throw new Error(`Signer reference ${owner.signerId} is missing`);\n        const webauthn = owner.kind === 'webauthn';\n        const quorum = input.validator.kind === 'quorum';\n        return [\n            {\n                id: `${input.taskPrefix}:${owner.id}`,\n                signer,\n                role: input.role ?? (factor.factorId ? 'factor' : 'owner'),\n                invocationKind: webauthn\n                    ? input.webauthnInvocation\n                    : quorum\n                        ? 'ecdsa-sign-hash'\n                        : input.ecdsaInvocation,\n                contribution: webauthn\n                    ? {\n                        kind: 'webauthn',\n                        ownerId: owner.id,\n                        publicKey: owner.account.publicKey,\n                        ...(factor.factorId ? { factorId: factor.factorId } : {}),\n                    }\n                    : {\n                        kind: 'ecdsa',\n                        ownerId: owner.id,\n                        encoding: 'raw-signer',\n                        ...(factor.factorId ? { factorId: factor.factorId } : {}),\n                    },\n            },\n        ];\n    }));\n    return input.validator.kind === 'multi-factor'\n        ? [...tasks].sort((left, right) => left.invocationKind.startsWith('ecdsa') ===\n            right.invocationKind.startsWith('ecdsa')\n            ? 0\n            : left.invocationKind.startsWith('ecdsa')\n                ? -1\n                : 1)\n        : tasks;\n}\nexport function signingTopology(validator, selectedSignerIds) {\n    const validators = validator.kind === 'multi-factor' ? validator.validators : [validator];\n    return {\n        configuredTopology: {\n            rootValidatorId: validator.id,\n            validators: validators.map((item) => ({\n                id: item.id,\n                ownerIds: item.owners.map(({ id }) => id),\n                threshold: item.threshold,\n            })),\n            threshold: validator.threshold,\n        },\n        effectiveSelection: {\n            validatorIds: validators.flatMap((item) => selectedSignerIds &&\n                !item.owners.some(({ signerId }) => selectedSignerIds.includes(signerId))\n                ? []\n                : [item.id]),\n            signerIds: selectedSignerIds ??\n                validators.flatMap((item) => item.owners.map(({ signerId }) => signerId)),\n            threshold: validator.threshold,\n        },\n    };\n}\nfunction taskIsRequired(template, facts) {\n    if (!template.when)\n        return true;\n    const fact = facts.find(({ id }) => id === template.when?.factId);\n    if (fact?.kind !== 'delegation-code') {\n        throw new Error(`Delegation fact ${template.when.factId} is missing`);\n    }\n    return (fact.code?.toLowerCase() !==\n        `0xef0100${template.when.contract.slice(2)}`.toLowerCase());\n}\nfunction materializeTask(template, input) {\n    const material = resolvePayloadMaterial(template, input);\n    const chain = template.chain;\n    switch (template.invocationKind) {\n        case 'ecdsa-sign-message':\n            requireMaterial(template, material, 'message');\n            return {\n                ...template,\n                invocation: {\n                    kind: 'ecdsa-sign-message',\n                    ...(chain ? { chain } : {}),\n                    message: material.message,\n                },\n            };\n        case 'ecdsa-sign-hash':\n            requireMaterial(template, material, 'message');\n            return {\n                ...template,\n                invocation: {\n                    kind: 'ecdsa-sign-hash',\n                    ...(chain ? { chain } : {}),\n                    hash: material.message.raw,\n                },\n            };\n        case 'ecdsa-sign-typed-data':\n            requireMaterial(template, material, 'typed-data');\n            return {\n                ...template,\n                invocation: {\n                    kind: 'ecdsa-sign-typed-data',\n                    ...(chain ? { chain } : {}),\n                    typedData: material.typedData,\n                },\n            };\n        case 'webauthn-sign-hash':\n            requireMaterial(template, material, 'message');\n            return {\n                ...template,\n                invocation: { kind: 'webauthn-sign-hash', hash: material.message.raw },\n            };\n        case 'webauthn-sign-typed-data':\n            requireMaterial(template, material, 'typed-data');\n            return {\n                ...template,\n                invocation: {\n                    kind: 'webauthn-sign-typed-data',\n                    typedData: material.typedData,\n                },\n            };\n        case 'sign-authorization':\n            requireMaterial(template, material, 'authorization');\n            if (!chain)\n                throw new Error(`Authorization task ${template.id} has no chain`);\n            return {\n                ...template,\n                invocation: {\n                    kind: 'sign-authorization',\n                    chain,\n                    authorization: material.authorization,\n                },\n            };\n    }\n}\nfunction resolvePayloadMaterial(template, input) {\n    const reference = template.payload;\n    if (reference.source === 'plan-payload') {\n        const material = input.payloads[reference.payloadId];\n        if (!material)\n            throw new Error(`No payload material for ${reference.payloadId}`);\n        return material;\n    }\n    if (reference.source === 'prior-output') {\n        const artifact = input.priorOutputs[`${reference.stageId}:${reference.outputId}`];\n        const selected = reference.selection === 'pre-claim' &&\n            typeof artifact === 'object' &&\n            'preClaimSig' in artifact\n            ? artifact.preClaimSig\n            : artifact;\n        if (typeof selected !== 'string') {\n            throw new Error(`Prior output ${reference.outputId} is not signable bytes`);\n        }\n        return { kind: 'message', message: { raw: selected } };\n    }\n    const fact = input.facts.find(({ id }) => id === reference.factId);\n    if (fact?.kind !== 'delegation-code' || !fact.code) {\n        throw new Error(`Checkpoint fact ${reference.factId} is not signable bytes`);\n    }\n    return { kind: 'message', message: { raw: fact.code } };\n}\nfunction requireMaterial(template, material, kind) {\n    if (material.kind !== kind) {\n        throw new Error(`Signing task ${template.id} requires ${kind}, received ${material.kind}`);\n    }\n}\nfunction assertUnique(values, value, message) {\n    if (values.has(value))\n        throw new Error(message);\n    values.add(value);\n}\nfunction fail(plan, message, stageId, artifactId) {\n    throw new SigningPipelineError(message, {\n        planKind: plan.kind,\n        payloadKind: plan.payload.kind,\n        failureStage: 'plan',\n        ...(stageId ? { stageId } : {}),\n        ...(artifactId ? { artifactId } : {}),\n    });\n}\n","// A `SingleChainOps` origin payload binds its chain in the EIP-712 domain, so\n// `domain.chainId` names it. A `MultiChainOps` payload is one signature over\n// every leg of a multi-leg bundle, and the contract verifies it with\n// `_hashTypedDataSansChainId` — the domain deliberately carries no chainId, and\n// each leg's chain lives in its own `ChainOps` leaf instead.\n//\n// The signature is identical on every leg, so any leaf is a valid context for\n// resolving a signer; the first is taken because the leaves are in signed order\n// and the choice has to be deterministic.\nfunction readChainId(value) {\n    if (typeof value !== 'bigint' &&\n        typeof value !== 'number' &&\n        typeof value !== 'string') {\n        return undefined;\n    }\n    const chainId = Number(value);\n    return Number.isFinite(chainId) ? chainId : undefined;\n}\nfunction domainChainId(typedData) {\n    const { chainId } = typedData.domain ?? {};\n    return chainId === null ? undefined : chainId;\n}\nfunction leafChainIds(typedData) {\n    const ops = typedData.message?.ops;\n    if (!Array.isArray(ops))\n        return [];\n    const chainIds = [];\n    for (const leaf of ops) {\n        const chainId = readChainId(leaf?.chainId);\n        if (chainId !== undefined)\n            chainIds.push(chainId);\n    }\n    return chainIds;\n}\n/**\n * The chain an origin payload is signed for.\n *\n * Throws rather than yielding `NaN` for a payload that names no chain at all:\n * the value flows into signer and session resolution, and on this path a\n * failure lands after the user has already approved the intent.\n */\nexport function originChainId(typedData) {\n    const fromDomain = domainChainId(typedData);\n    if (fromDomain !== undefined) {\n        const chainId = readChainId(fromDomain);\n        if (chainId === undefined) {\n            throw new Error(`Intent origin payload has an unreadable domain chainId: ${String(fromDomain)}`);\n        }\n        return chainId;\n    }\n    const [fromLeaf] = leafChainIds(typedData);\n    if (fromLeaf !== undefined)\n        return fromLeaf;\n    throw new Error(`Intent origin payload \"${String(typedData.primaryType)}\" names no chain: it carries neither a domain chainId nor a ChainOps leaf to read one from`);\n}\n/**\n * The chain whose account runtime signs an intent, read off the last origin\n * payload as the callers here have always done.\n *\n * A `MultiChainOps` quote carries exactly one origin entry however many legs it\n * covers, so first and last are the same payload and the choice only matters\n * for the per-leg shape.\n */\nexport function accountChainIdFromOrigins(origins) {\n    const last = origins.at(-1);\n    if (!last)\n        throw new Error('Intent quote has no origin payloads');\n    return originChainId(last);\n}\n/**\n * True when one signature over this payload has to validate on more than one\n * chain.\n *\n * An absent domain chainId is not the test on its own: `MultiChainOps` does not\n * require its leaves to be on DIFFERENT chains, and same-chain legs with\n * distinct nonces are a valid set — that is how a bundle splits its destination\n * ops across blocks. Such a payload is chainless in the domain yet every leg\n * runs on one chain, so a chain-bound wrapper still validates on all of them.\n *\n * Callers that wrap the digest with anything chain-specific must refuse only\n * the genuinely multi-chain case, where signing against the leg being resolved\n * gives a signature that fails on the rest — on chain, after the user has\n * approved.\n */\nexport function signatureSpansMultipleChains(typedData) {\n    if (domainChainId(typedData) !== undefined)\n        return false;\n    return new Set(leafChainIds(typedData)).size > 1;\n}\n","export function selectIntentQuote(quotes, intentId) {\n    const quote = intentId\n        ? quotes.find((candidate) => candidate.intentId === intentId)\n        : quotes[0];\n    if (!quote) {\n        throw new Error(intentId\n            ? `Quote ${intentId} is not in the prepared transaction`\n            : 'Orchestrator returned no quote');\n    }\n    return quote;\n}\n","import { concat, zeroHash } from 'viem';\nimport { getSmartSessionEmissaryAddress } from './module.js';\nimport { encodeSmartSessionSignature } from './signature.js';\nexport function buildSmartSessionMockSignature(input) {\n    const shape = input.shape ?? 'enable';\n    let enableData;\n    if (shape === 'enable') {\n        const chainCount = Number.isFinite(input.chainCount) && (input.chainCount ?? 0) > 0\n            ? Math.floor(input.chainCount)\n            : 1;\n        const primaryChainId = input.targetChainId ?? input.session.chain.id;\n        enableData = {\n            userSignature: `0x${'00'.repeat(65)}`,\n            hashesAndChainIds: Array.from({ length: chainCount }, (_, index) => ({\n                chainId: index === 0 ? BigInt(primaryChainId) : 0n,\n                sessionDigest: zeroHash,\n            })),\n            sessionToEnableIndex: 0,\n        };\n    }\n    const signers = {\n        kind: 'smart-session',\n        session: input.session,\n        verifyExecutions: shape !== 'erc1271',\n        ...(enableData ? { enableData } : {}),\n    };\n    return concat([\n        getSmartSessionEmissaryAddress(input.environment),\n        encodeSmartSessionSignature(signers, `0x${'00'.repeat(65)}`),\n    ]);\n}\n","import { encodeAbiParameters, encodePacked, maxUint256, size, zeroAddress, zeroHash, } from 'viem';\nimport { getPermissionId, getSessionData } from './digest.js';\nimport { fastLzCompress } from './fast-lz.js';\nconst SCOPE_MULTICHAIN = 0;\nconst RESET_PERIOD_ONE_WEEK = 6;\nexport const SMART_SESSION_MODE_USE = '0x00';\nexport const SMART_SESSION_MODE_ENABLE = '0x01';\nexport function encodeSmartSessionSignature(signers, validatorSignature) {\n    const permissionId = getPermissionId(signers.session);\n    if (!signers.verifyExecutions) {\n        return encodeSmartSessionContribution({\n            mode: 'notarized',\n            permissionId,\n            signature: validatorSignature,\n            ...(signers.claimPolicyData\n                ? { claimPolicyData: signers.claimPolicyData }\n                : {}),\n        });\n    }\n    if (!signers.enableData) {\n        return encodeSmartSessionContribution({\n            mode: 'use',\n            permissionId,\n            signature: validatorSignature,\n        });\n    }\n    return encodeSmartSessionContribution({\n        mode: 'enable-and-use',\n        permissionId,\n        signature: validatorSignature,\n        enableData: {\n            ...signers.enableData,\n            session: getSessionData(signers.session),\n        },\n    });\n}\nexport function encodeSmartSessionContribution(input) {\n    if (input.mode !== 'enable-and-use') {\n        if (input.mode === 'notarized') {\n            return encodePacked(['bytes1', 'bytes32', 'uint256', 'bytes', 'bytes'], [\n                SMART_SESSION_MODE_USE,\n                input.permissionId,\n                BigInt(64 + size(input.signature)),\n                input.signature,\n                input.claimPolicyData ?? '0x',\n            ]);\n        }\n        return encodePacked(['bytes1', 'bytes32', 'bytes'], [SMART_SESSION_MODE_USE, input.permissionId, input.signature]);\n    }\n    if (!input.enableData) {\n        throw new Error('Enable-and-use signatures require enable data');\n    }\n    const compressed = fastLzCompress(encodeSmartSessionEnablePayload({\n        permissionId: input.permissionId,\n        signature: input.signature,\n        enableData: input.enableData,\n    }));\n    return encodePacked(['bytes1', 'bytes'], [SMART_SESSION_MODE_ENABLE, compressed]);\n}\nexport function encodeSmartSessionEnablePayload(input) {\n    return encodeAbiParameters([\n        {\n            type: 'tuple',\n            name: 'enableData',\n            components: [\n                { type: 'bytes', name: 'allocatorSig' },\n                { type: 'bytes', name: 'userSig' },\n                { type: 'uint256', name: 'expires' },\n                {\n                    type: 'tuple',\n                    name: 'enableSession',\n                    components: [\n                        { type: 'uint8', name: 'chainDigestIndex' },\n                        {\n                            type: 'tuple[]',\n                            name: 'hashesAndChainIds',\n                            components: [\n                                { type: 'uint64', name: 'chainId' },\n                                { type: 'bytes32', name: 'sessionDigest' },\n                            ],\n                        },\n                        {\n                            type: 'tuple',\n                            name: 'session',\n                            components: [\n                                { type: 'address', name: 'sessionValidator' },\n                                { type: 'bytes', name: 'sessionValidatorInitData' },\n                                { type: 'bytes32', name: 'salt' },\n                                {\n                                    type: 'tuple[]',\n                                    name: 'actions',\n                                    components: [\n                                        { type: 'bytes4', name: 'actionTargetSelector' },\n                                        { type: 'address', name: 'actionTarget' },\n                                        {\n                                            type: 'tuple[]',\n                                            name: 'actionPolicies',\n                                            components: [\n                                                { type: 'address', name: 'policy' },\n                                                { type: 'bytes', name: 'initData' },\n                                            ],\n                                        },\n                                    ],\n                                },\n                                {\n                                    type: 'tuple[]',\n                                    name: 'claimPolicies',\n                                    components: [\n                                        { type: 'address', name: 'policy' },\n                                        { type: 'bytes', name: 'initData' },\n                                    ],\n                                },\n                                {\n                                    type: 'tuple',\n                                    name: 'erc7739Policies',\n                                    components: [\n                                        {\n                                            type: 'tuple[]',\n                                            name: 'allowedERC7739Content',\n                                            components: [\n                                                {\n                                                    type: 'bytes32',\n                                                    name: 'appDomainSeparator',\n                                                },\n                                                { type: 'string[]', name: 'contentNames' },\n                                            ],\n                                        },\n                                        {\n                                            type: 'tuple[]',\n                                            name: 'erc1271Policies',\n                                            components: [\n                                                { type: 'address', name: 'policy' },\n                                                { type: 'bytes', name: 'initData' },\n                                            ],\n                                        },\n                                    ],\n                                },\n                            ],\n                        },\n                    ],\n                },\n            ],\n        },\n        {\n            type: 'tuple',\n            name: 'config',\n            components: [\n                { type: 'uint8', name: 'scope' },\n                { type: 'uint8', name: 'resetPeriod' },\n                { type: 'address', name: 'allocator' },\n                { type: 'bytes32', name: 'permissionId' },\n            ],\n        },\n        { type: 'bytes' },\n    ], [\n        {\n            allocatorSig: zeroHash,\n            userSig: input.enableData.userSignature,\n            expires: maxUint256,\n            enableSession: {\n                chainDigestIndex: input.enableData.sessionToEnableIndex,\n                hashesAndChainIds: [...input.enableData.hashesAndChainIds],\n                session: input.enableData.session,\n            },\n        },\n        {\n            scope: SCOPE_MULTICHAIN,\n            resetPeriod: RESET_PERIOD_ONE_WEEK,\n            allocator: zeroAddress,\n            permissionId: input.permissionId,\n        },\n        input.signature,\n    ]);\n}\n","import { encodeAbiParameters, keccak256 } from 'viem';\nimport { encodePermit2ClaimPolicyInitData, PERMIT2_CLAIM_POLICY_ADDRESS, } from '../policies/claim/permit2.js';\nimport { resolvePermit2ClaimPolicy } from './policies/claim.js';\nexport function getPermissionIdFromData(session) {\n    return keccak256(encodeAbiParameters([\n        { type: 'address', name: 'sessionValidator' },\n        { type: 'bytes', name: 'sessionValidatorInitData' },\n        { type: 'bytes32', name: 'salt' },\n    ], [\n        session.sessionValidator,\n        session.sessionValidatorInitData,\n        session.salt,\n    ]));\n}\nexport function getSessionData(session) {\n    return {\n        sessionValidator: session.sessionValidator,\n        sessionValidatorInitData: session.sessionValidatorInitData,\n        salt: session.salt,\n        erc7739Policies: session.erc7739Policies,\n        actions: session.actions,\n        claimPolicies: session.claimPolicies.map((policy) => ({\n            policy: PERMIT2_CLAIM_POLICY_ADDRESS,\n            initData: encodePermit2ClaimPolicyInitData(resolvePermit2ClaimPolicy(policy)),\n        })),\n    };\n}\nexport function getPermissionId(session) {\n    return session.permissionId;\n}\n","import { concat, encodeAbiParameters, encodePacked, hashStruct, keccak256, maxUint256, toHex, } from 'viem';\nimport { ANY_ADDRESS, FIELD_ARBITER, FIELD_EXPIRY, FIELD_FILL_EXPIRY, FIELD_RECIPIENT, FIELD_RECIPIENT_IS_SPONSOR, FIELD_TOKEN_IN, FIELD_TOKEN_OUT, MODE_CHECK_STORAGE, } from './types.js';\n// EIP-712 type definitions for Permit2/Mandate struct encoding.\n// Note: the token-out struct is named 'Token' in the Solidity contract (matching the\n// signed Permit2 message types in execution/permit2.ts).\nconst PERMIT2_TYPES = {\n    TokenPermissions: [\n        { name: 'token', type: 'address' },\n        { name: 'amount', type: 'uint256' },\n    ],\n    Token: [\n        { name: 'token', type: 'address' },\n        { name: 'amount', type: 'uint256' },\n    ],\n    Ops: [\n        { name: 'to', type: 'address' },\n        { name: 'value', type: 'uint256' },\n        { name: 'data', type: 'bytes' },\n    ],\n    Op: [\n        { name: 'vt', type: 'bytes32' },\n        { name: 'ops', type: 'Ops[]' },\n    ],\n    Target: [\n        { name: 'recipient', type: 'address' },\n        { name: 'tokenOut', type: 'Token[]' },\n        { name: 'targetChain', type: 'uint256' },\n        { name: 'fillExpiry', type: 'uint256' },\n    ],\n    Mandate: [\n        { name: 'target', type: 'Target' },\n        { name: 'minGas', type: 'uint128' },\n        { name: 'originOps', type: 'Op' },\n        { name: 'destOps', type: 'Op' },\n        { name: 'q', type: 'bytes32' },\n    ],\n};\n// --- EIP-712 hash helpers ---\nfunction hashArray(hashes) {\n    return keccak256(hashes.length > 0 ? concat(hashes) : '0x');\n}\nfunction hashTokenPermissionsArray(permitted) {\n    return hashArray(permitted.map(({ token, amount }) => hashStruct({\n        primaryType: 'TokenPermissions',\n        types: PERMIT2_TYPES,\n        data: { token, amount },\n    })));\n}\nfunction hashTokenOutArray(tokenOut) {\n    return hashArray(tokenOut.map(({ token, amount }) => hashStruct({\n        primaryType: 'Token',\n        types: PERMIT2_TYPES,\n        data: { token, amount },\n    })));\n}\nfunction hashOpStruct(op) {\n    return hashStruct({\n        primaryType: 'Op',\n        types: PERMIT2_TYPES,\n        data: { vt: op.vt, ops: Array.from(op.ops) },\n    });\n}\nfunction hashMandateStruct(mandate) {\n    return hashStruct({\n        primaryType: 'Mandate',\n        types: PERMIT2_TYPES,\n        data: {\n            target: {\n                recipient: mandate.target.recipient,\n                tokenOut: Array.from(mandate.target.tokenOut),\n                targetChain: mandate.target.targetChain,\n                fillExpiry: mandate.target.fillExpiry,\n            },\n            minGas: mandate.minGas,\n            originOps: {\n                vt: mandate.originOps.vt,\n                ops: Array.from(mandate.originOps.ops),\n            },\n            destOps: { vt: mandate.destOps.vt, ops: Array.from(mandate.destOps.ops) },\n            q: mandate.q,\n        },\n    });\n}\n// --- Token array encoding helpers ---\n/** Encodes a token+amount pair as [token_as_uint256:32][amount:32] (64 bytes) */\nfunction encodeTokenEntry(token, amount) {\n    return encodeAbiParameters([{ type: 'address' }, { type: 'uint256' }], [token, amount]);\n}\n/**\n * Builds the policySpecificData calldata for a Permit2ClaimPolicy EIP-1271 check.\n *\n * Format (derived from Permit2ClaimPolicy.sol calldata layout):\n *   Header:  [spender:20][nonce:32][deadline:32]\n *   TokenIn: expanded [count:1][token:32][amount:32]... OR pre-computed hash [32]\n *   Mandate: if any target check enabled — expanded target + minGas:16 + ops hashes + q\n *            else — pre-computed mandateHash [32]\n *\n */\nexport function buildPermit2ClaimPolicyCalldata(policy, message) {\n    const tokenInEnabled = !!policy.tokensIn?.length;\n    const recipientEnabled = !!policy.recipients?.length;\n    const fillExpiryEnabled = !!policy.fillExpiryBounds?.length;\n    const tokenOutEnabled = !!policy.tokensOut?.length;\n    const recipientIsSponsorEnabled = !!policy.recipientIsSponsor;\n    // hasAnyTargetCheck mirrors the Solidity MASK_TARGET_CHECKS logic for our supported fields\n    const hasAnyTargetCheck = recipientEnabled ||\n        fillExpiryEnabled ||\n        tokenOutEnabled ||\n        recipientIsSponsorEnabled;\n    const parts = [];\n    // Header: [spender:20][nonce:32][deadline:32]  (spender == arbiter in Permit2 context)\n    parts.push(encodePacked(['address', 'uint256', 'uint256'], [message.spender, message.nonce, message.deadline]));\n    // TokenIn section\n    if (tokenInEnabled) {\n        // Expanded: [count:1][token_as_uint256:32][amount:32]...\n        if (message.permitted.length > 255)\n            throw new Error('permitted array exceeds max length of 255');\n        parts.push(toHex(message.permitted.length, { size: 1 }));\n        for (const { token, amount } of message.permitted) {\n            parts.push(encodeTokenEntry(token, amount));\n        }\n    }\n    else {\n        parts.push(hashTokenPermissionsArray(message.permitted));\n    }\n    // Mandate section\n    if (!hasAnyTargetCheck) {\n        // No mandate-level checks enabled — provide pre-computed mandateHash\n        parts.push(hashMandateStruct(message.mandate));\n    }\n    else {\n        // Expanded mandate: target fields + minGas + ops hashes + q\n        const target = message.mandate.target;\n        // Target: [recipient:20][targetChain:32][fillExpiry:32]\n        parts.push(encodePacked(['address', 'uint256', 'uint256'], [target.recipient, target.targetChain, target.fillExpiry]));\n        // TokenOut (inside target)\n        if (tokenOutEnabled) {\n            if (target.tokenOut.length > 255)\n                throw new Error('tokenOut array exceeds max length of 255');\n            parts.push(toHex(target.tokenOut.length, { size: 1 }));\n            for (const { token, amount } of target.tokenOut) {\n                parts.push(encodeTokenEntry(token, amount));\n            }\n        }\n        else {\n            parts.push(hashTokenOutArray(target.tokenOut));\n        }\n        // minGas: uint128 = 16 bytes\n        parts.push(toHex(message.mandate.minGas, { size: 16 }));\n        // originOpsHash and destOpsHash: always 32-byte hashes (we don't support ops checks)\n        parts.push(hashOpStruct(message.mandate.originOps));\n        parts.push(hashOpStruct(message.mandate.destOps));\n        // qualificationHash: q is already keccak256(qualifier.encodedVal)\n        parts.push(message.mandate.q);\n    }\n    return concat(parts);\n}\nexport const PERMIT2_CLAIM_POLICY_ADDRESS = '0x62E3588C6d861C9f986E82EC3757434EDF16ce91';\nexport function encodePermit2ClaimPolicyInitData(policy) {\n    let modeConfig = 0;\n    const setMode = (fieldId) => {\n        modeConfig |= MODE_CHECK_STORAGE << (fieldId * 2);\n    };\n    if (policy.arbiters?.length)\n        setMode(FIELD_ARBITER);\n    if (policy.expiryBounds)\n        setMode(FIELD_EXPIRY);\n    if (policy.tokensIn?.length)\n        setMode(FIELD_TOKEN_IN);\n    if (policy.recipients?.length)\n        setMode(FIELD_RECIPIENT);\n    if (policy.fillExpiryBounds?.length)\n        setMode(FIELD_FILL_EXPIRY);\n    if (policy.tokensOut?.length)\n        setMode(FIELD_TOKEN_OUT);\n    if (policy.recipientIsSponsor)\n        setMode(FIELD_RECIPIENT_IS_SPONSOR);\n    const parts = [toHex(modeConfig, { size: 4 })];\n    // Arbiter: [count: 1][address: 20] each\n    if (policy.arbiters?.length) {\n        if (policy.arbiters.length > 255)\n            throw new Error('arbiters array exceeds max length of 255');\n        parts.push(encodePacked(['uint8', ...policy.arbiters.map(() => 'address')], [policy.arbiters.length, ...policy.arbiters]));\n    }\n    // Expiry: [maxExpiry: 16][minExpiry: 16] packed into uint256\n    if (policy.expiryBounds) {\n        const mask128 = (1n << 128n) - 1n;\n        const min = (policy.expiryBounds.min ?? 0n) & mask128;\n        const max = (policy.expiryBounds.max ?? maxUint256) & mask128;\n        parts.push(toHex((min & mask128) | (max << 128n), { size: 32 }));\n    }\n    // TokenIn: [count: 1][chainId: 32][token: 20] each\n    if (policy.tokensIn?.length) {\n        if (policy.tokensIn.length > 255)\n            throw new Error('tokensIn array exceeds max length of 255');\n        parts.push(toHex(policy.tokensIn.length, { size: 1 }));\n        for (const { chainId, token } of policy.tokensIn) {\n            parts.push(encodePacked(['uint256', 'address'], [BigInt(chainId), token]));\n        }\n    }\n    // Recipient: [count: 1][chainId: 32][recipient: 20] each\n    if (policy.recipients?.length) {\n        if (policy.recipients.length > 255)\n            throw new Error('recipients array exceeds max length of 255');\n        parts.push(toHex(policy.recipients.length, { size: 1 }));\n        for (const { chainId, recipient } of policy.recipients) {\n            parts.push(encodePacked(['uint256', 'address'], [BigInt(chainId), recipient === 'any' ? ANY_ADDRESS : recipient]));\n        }\n    }\n    // FillExpiry: [count: 1][chainId: 32][max<<128|min packed into uint256] each\n    if (policy.fillExpiryBounds?.length) {\n        if (policy.fillExpiryBounds.length > 255)\n            throw new Error('fillExpiryBounds array exceeds max length of 255');\n        const mask128 = (1n << 128n) - 1n;\n        parts.push(toHex(policy.fillExpiryBounds.length, { size: 1 }));\n        for (const { chainId, min: fMin, max: fMax } of policy.fillExpiryBounds) {\n            const minVal = (fMin ?? 0n) & mask128;\n            const maxVal = (fMax ?? maxUint256) & mask128;\n            const packed = minVal | (maxVal << 128n);\n            parts.push(encodePacked(['uint256', 'uint256'], [BigInt(chainId), packed]));\n        }\n    }\n    // TokenOut: [count: 1][chainId: 32][token: 20] each\n    if (policy.tokensOut?.length) {\n        if (policy.tokensOut.length > 255)\n            throw new Error('tokensOut array exceeds max length of 255');\n        parts.push(toHex(policy.tokensOut.length, { size: 1 }));\n        for (const { chainId, token } of policy.tokensOut) {\n            parts.push(encodePacked(['uint256', 'address'], [BigInt(chainId), token]));\n        }\n    }\n    // RecipientIsSponsor has no data payload — mode bit alone enables it\n    return concat(parts);\n}\n","// Field IDs matching BaseDataTypes.sol\nexport const FIELD_ARBITER = 0;\nexport const FIELD_EXPIRY = 1;\nexport const FIELD_TOKEN_IN = 2;\nexport const FIELD_RECIPIENT = 3;\nexport const FIELD_FILL_EXPIRY = 4;\nexport const FIELD_TOKEN_OUT = 5;\nexport const FIELD_ORIGIN_OPS = 6;\nexport const FIELD_DEST_OPS = 7;\n// Field 8 is reserved in BaseDataTypes.sol\nexport const FIELD_RECIPIENT_IS_SPONSOR = 9;\n// Mode values\nexport const MODE_CHECK_STORAGE = 1;\n// Sentinel: allows any recipient address\nexport const ANY_ADDRESS = '0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF';\n","import { isAddressEqual } from 'viem';\nimport { FAR_FUTURE_MS } from '../../permissions.js';\nimport { getArbitersForSettlementLayers } from '../../policies/claim/arbiters.js';\nexport function expandCrossChainPermit(permit, environment) {\n    const sourceTokens = permit.from?.length\n        ? permit.from.map(({ chain, token }) => ({ chain, address: token }))\n        : undefined;\n    const destinationTokens = permit.to?.length\n        ? permit.to.map(({ chain, token }) => ({ chain, address: token }))\n        : undefined;\n    const recipientsList = (permit.to ?? [])\n        .filter(({ recipient }) => recipient !== undefined)\n        .map(({ chain, recipient }) => ({\n        chain,\n        address: recipient,\n    }));\n    const permitDeadline = permit.validAfter !== undefined || permit.validUntil !== undefined\n        ? { min: permit.validAfter, max: permit.validUntil }\n        : undefined;\n    const claim = {\n        type: 'permit2',\n        spenders: getArbitersForSettlementLayers(permit.settlementLayers, environment === 'development'),\n        sourceTokens,\n        destinationTokens,\n        recipients: recipientsList.length ? recipientsList : undefined,\n        recipientIsAccount: permit.recipientIsAccount,\n        permitDeadline,\n        fillDeadline: permit.fillDeadline,\n    };\n    const fallbackPolicies = [];\n    const limits = (permit.from ?? [])\n        .filter(({ maxAmount }) => maxAmount !== undefined)\n        .map(({ token, maxAmount }) => ({ token, amount: maxAmount }));\n    if (limits.length)\n        fallbackPolicies.push({ type: 'spending-limits', limits });\n    if (permitDeadline) {\n        fallbackPolicies.push({\n            type: 'time-frame',\n            validUntil: permit.validUntil === undefined\n                ? FAR_FUTURE_MS\n                : Number(permit.validUntil * 1000n),\n            validAfter: permit.validAfter === undefined ? 0 : Number(permit.validAfter * 1000n),\n        });\n    }\n    return { claim, fallbackPolicies };\n}\nexport function permit2ClaimPolicyMatchesMessage(policy, message) {\n    if (policy.spenders?.length &&\n        !policy.spenders.some((spender) => isAddressEqual(spender, message.spender))) {\n        return false;\n    }\n    if (policy.sourceTokens?.length) {\n        const allowed = new Set(policy.sourceTokens.map(({ address }) => address.toLowerCase()));\n        if (!message.permitted.every(({ token }) => allowed.has(token.toLowerCase()))) {\n            return false;\n        }\n    }\n    const targetChain = message.mandate.target.targetChain;\n    if (policy.destinationTokens?.length) {\n        const allowed = new Set(policy.destinationTokens\n            .filter(({ chain }) => BigInt(chain.id) === targetChain)\n            .map(({ address }) => address.toLowerCase()));\n        if (!message.mandate.target.tokenOut.every(({ token }) => allowed.has(token.toLowerCase()))) {\n            return false;\n        }\n    }\n    if (policy.recipients?.length) {\n        const recipients = policy.recipients.filter(({ chain }) => BigInt(chain.id) === targetChain);\n        if (recipients.length &&\n            !recipients.some(({ address }) => address === 'any' ||\n                isAddressEqual(address, message.mandate.target.recipient))) {\n            return false;\n        }\n    }\n    return true;\n}\nexport function selectPermit2ClaimPolicyForMessage(policies, message) {\n    if (policies.length <= 1)\n        return policies[0];\n    return (policies.find((policy) => permit2ClaimPolicyMatchesMessage(policy, message)) ?? policies[0]);\n}\nexport function resolvePermit2ClaimPolicy(policy) {\n    return {\n        type: 'permit2-claim',\n        arbiters: policy.spenders ? [...policy.spenders] : undefined,\n        tokensIn: policy.sourceTokens?.map(({ chain, address }) => ({\n            chainId: chain.id,\n            token: address,\n        })),\n        tokensOut: policy.destinationTokens?.map(({ chain, address }) => ({\n            chainId: chain.id,\n            token: address,\n        })),\n        recipients: policy.recipients?.map(({ chain, address }) => ({\n            chainId: chain.id,\n            recipient: address,\n        })),\n        recipientIsSponsor: policy.recipientIsAccount,\n        expiryBounds: policy.permitDeadline,\n        fillExpiryBounds: policy.fillDeadline?.map(({ chain, min, max }) => ({\n            chainId: chain.id,\n            min,\n            max,\n        })),\n    };\n}\n","import { isAddress, isHex, padHex, size, toFunctionSelector, } from 'viem';\nfunction isStaticAbiType(type) {\n    if (type === 'address' || type === 'bool')\n        return true;\n    if (/^u?int\\d*$/.test(type))\n        return true;\n    if (/^bytes\\d+$/.test(type)) {\n        const n = Number.parseInt(type.slice(5), 10);\n        return n >= 1 && n <= 32;\n    }\n    return false;\n}\n/** Split `T[k]` / `T[]` into element type and length (`''` when unbounded). */\nconst ARRAY_SUFFIX = /^(.*)\\[(\\d*)\\]$/;\nfunction withType(param, type) {\n    return { ...param, type };\n}\nfunction tupleComponents(param) {\n    return param.components ?? [];\n}\n/**\n * True when the param is encoded as a 32-byte offset pointer in the head rather\n * than inline. Mirrors the ABI spec: `bytes`, `string`, unbounded arrays, and\n * any tuple/fixed-array transitively containing one of those.\n */\nfunction isDynamicAbiParam(param) {\n    const { type } = param;\n    if (type === 'bytes' || type === 'string')\n        return true;\n    const array = ARRAY_SUFFIX.exec(type);\n    if (array) {\n        const [, elementType, length] = array;\n        if (length === '')\n            return true;\n        return isDynamicAbiParam(withType(param, elementType));\n    }\n    if (type === 'tuple')\n        return tupleComponents(param).some(isDynamicAbiParam);\n    return false;\n}\n/**\n * Bytes this param occupies in the calldata HEAD.\n *\n * Not always 32: a static tuple is flattened inline (one word per leaf) and a\n * fixed-size static array occupies `length` words. Computing offsets as\n * `paramIndex * 32` silently mis-addresses every param that follows one of\n * those — e.g. `f(uint256[3] a, address b)` would point at word 1 instead of\n * word 3 and compare against array data, producing a policy that passes or\n * fails for reasons unrelated to `b`.\n */\nfunction headSize(param) {\n    if (isDynamicAbiParam(param))\n        return 32;\n    const array = ARRAY_SUFFIX.exec(param.type);\n    if (array) {\n        const [, elementType, length] = array;\n        return Number.parseInt(length, 10) * headSize(withType(param, elementType));\n    }\n    if (param.type === 'tuple') {\n        return tupleComponents(param).reduce((sum, c) => sum + headSize(c), 0);\n    }\n    return 32;\n}\n/** Byte offset of `inputs[index]` within the calldata head (past the selector). */\nfunction headOffset(inputs, index) {\n    let offset = 0;\n    for (let i = 0; i < index; i++)\n        offset += headSize(inputs[i]);\n    return BigInt(offset);\n}\n/**\n * Calldata head offset of every named top-level parameter of `functionName`.\n *\n * Lets callers that build raw param rules (the swap venues) address arguments by\n * name instead of hardcoding byte offsets — the offsets then follow the ABI\n * automatically, and a signature change surfaces as a missing key rather than a\n * rule silently pointing at the wrong word.\n *\n * Only single-word static params are included; anything dynamic or multi-word\n * cannot be compared by a 32-byte reference value and is omitted.\n */\nexport function namedParamOffsets(abi, functionName) {\n    const entry = abi.find((item) => item.type === 'function' && item.name === functionName);\n    if (!entry) {\n        throw new Error(`Function \"${functionName}\" not found in ABI`);\n    }\n    const offsets = {};\n    entry.inputs.forEach((param, index) => {\n        if (param.name && isStaticAbiType(param.type)) {\n            offsets[param.name] = headOffset(entry.inputs, index);\n        }\n    });\n    return offsets;\n}\nfunction toReferenceValue(value, abiType) {\n    if (abiType === 'address') {\n        if (typeof value === 'string' && isAddress(value))\n            return value;\n        throw new Error(`Expected address value, got: ${typeof value}`);\n    }\n    if (abiType === 'bool') {\n        if (typeof value === 'boolean')\n            return value ? 1n : 0n;\n        throw new Error(`Expected boolean value, got: ${typeof value}`);\n    }\n    if (abiType.startsWith('uint') || abiType.startsWith('int')) {\n        if (typeof value === 'bigint')\n            return value;\n        if (typeof value === 'number')\n            return BigInt(value);\n        throw new Error(`Expected bigint value for ${abiType}, got: ${typeof value}`);\n    }\n    if (/^bytes\\d+$/.test(abiType)) {\n        const expectedSize = Number.parseInt(abiType.slice(5), 10);\n        if (typeof value === 'string' &&\n            isHex(value) &&\n            size(value) === expectedSize) {\n            // Solidity calldata encodes bytesN (N<32) left-aligned + right-padded\n            // inside its 32-byte word, whereas address/uint*/bool are right-aligned\n            // + left-padded. Downstream `encodeActionParamRule` unconditionally\n            // left-pads with `padHex`, which is correct for the right-aligned types\n            // but wrong for bytesN. Pre-encode here to the full 32-byte hex with\n            // the correct alignment so the policy's bytes32 == bytes32 comparison\n            // matches what's actually in calldata.\n            return padHex(value, { size: 32, dir: 'right' });\n        }\n        throw new Error(`Expected ${expectedSize}-byte hex string for ${abiType}`);\n    }\n    throw new Error(`Unsupported ABI type: ${abiType}`);\n}\n// Right-fold an array of leaves into a right-leaning OR chain:\n//   [a, b, c]  →  OR(a, OR(b, c))\n// Right-leaning is fine because ArgPolicy evaluates with short-circuit; any\n// shape that uses every leaf and respects post-order produces the same result.\nfunction orChain(leaves) {\n    let acc = leaves[leaves.length - 1];\n    for (let i = leaves.length - 2; i >= 0; i--) {\n        acc = { type: 'or', left: leaves[i], right: acc };\n    }\n    return acc;\n}\nfunction andChain(leaves) {\n    let acc = leaves[leaves.length - 1];\n    for (let i = leaves.length - 2; i >= 0; i--) {\n        acc = { type: 'and', left: leaves[i], right: acc };\n    }\n    return acc;\n}\n// On-chain ERC20SpendingLimitPolicy._isTokenTransferOrApprove matches by\n// 4-byte selector, accepting only these four. Selector-gating here keeps the\n// SDK's accepted set congruent with the contract's — a same-shaped function\n// like `mint(address,uint256)` would otherwise pass argument-type checks and\n// fail every call on-chain.\nconst ERC20_SPENDING_LIMIT_SELECTORS = new Set([\n    '0x095ea7b3', // approve(address,uint256)\n    '0x39509351', // increaseAllowance(address,uint256)\n    '0xa9059cbb', // transfer(address,uint256)\n    '0x23b872dd', // transferFrom(address,address,uint256)\n]);\n// Year 2100 in ms — well within uint128 after the encoder's ms→s conversion.\n// Used as the one-sided default for `validUntil` when only `validAfter` is set.\n// Exported so the cross-chain permit expansion (smart-sessions.ts) applies the\n// same always-passing upper bound instead of defaulting to 0 (already expired).\nexport const FAR_FUTURE_MS = 4_102_444_800_000;\nfunction resolvePermission(permission) {\n    const { abi, address, functions } = permission;\n    const actions = [];\n    for (const [fnName, fnConfig] of Object.entries(functions)) {\n        if (!fnConfig)\n            continue;\n        const config = fnConfig;\n        const abiEntries = abi.filter((entry) => entry.type === 'function' &&\n            entry.name === fnName);\n        if (abiEntries.length === 0) {\n            throw new Error(`Function \"${fnName}\" not found in the provided ABI.`);\n        }\n        if (abiEntries.length > 1) {\n            throw new Error(`Function \"${fnName}\" is overloaded (${abiEntries.length} variants). ` +\n                'Permission entries do not support overloaded functions. ' +\n                'Pre-filter the ABI to a single overload before passing it.');\n        }\n        const abiEntry = abiEntries[0];\n        const selector = toFunctionSelector(abiEntry);\n        if (Object.hasOwn(config, 'policies')) {\n            throw new Error(`Function \"${fnName}\": \\`policies\\` was removed from permission configs. ` +\n                'Use params, maxUses, validUntil/validAfter, valueLimit, or spendingLimit instead.');\n        }\n        const policies = [];\n        // --- Sugar field expansion -----------------------------------------------\n        if (config.maxUses !== undefined) {\n            policies.push({ type: 'usage-limit', limit: config.maxUses });\n        }\n        if (config.validUntil !== undefined || config.validAfter !== undefined) {\n            const validUntil = config.validUntil !== undefined\n                ? config.validUntil.getTime()\n                : FAR_FUTURE_MS;\n            const validAfter = config.validAfter !== undefined ? config.validAfter.getTime() : 0;\n            if (validUntil < validAfter) {\n                throw new Error(`Function \"${fnName}\": validUntil (${validUntil}) is before validAfter (${validAfter}).`);\n            }\n            policies.push({ type: 'time-frame', validUntil, validAfter });\n        }\n        if (config.valueLimit !== undefined) {\n            // Runtime backstop: payable-gating is enforced at the type level, but\n            // users can bypass with `as` casts. valueLimit on a non-payable function\n            // is harmless on-chain (msg.value is always 0, the cap always passes)\n            // but it leaks intent — throw rather than encode dead weight.\n            if (abiEntry.stateMutability !== 'payable') {\n                throw new Error(`Function \"${fnName}\" is not payable — \\`valueLimit\\` only constrains native ETH ` +\n                    'attached to the call, which is always zero for non-payable functions. ' +\n                    'Remove `valueLimit`.');\n            }\n            policies.push({ type: 'value-limit', limit: config.valueLimit });\n        }\n        if (config.spendingLimit !== undefined) {\n            // Runtime backstop: type-level gate restricts shape, but ERC20SpendingLimitPolicy\n            // dispatches by selector on-chain — a same-shaped function like\n            // mint(address,uint256) would encode successfully and fail every call.\n            if (!ERC20_SPENDING_LIMIT_SELECTORS.has(selector)) {\n                throw new Error(`Function \"${fnName}\" (selector ${selector}) is not an ERC-20 transfer/approve ` +\n                    'selector; `spendingLimit` only works on approve, increaseAllowance, ' +\n                    'transfer, or transferFrom. The on-chain policy dispatches by selector ' +\n                    'and would fail every call for other functions.');\n            }\n            policies.push({\n                type: 'spending-limits',\n                limits: [config.spendingLimit],\n            });\n        }\n        // --- End sugar field expansion -------------------------------------------\n        const rawParams = config.params ?? {};\n        const paramEntries = Object.entries(rawParams).filter(([, v]) => v !== undefined);\n        if (paramEntries.length > 0) {\n            const normalized = paramEntries.map(([paramName, rule]) => {\n                const paramIndex = abiEntry.inputs.findIndex((p) => p.name === paramName);\n                if (paramIndex === -1) {\n                    throw new Error(`Parameter \"${paramName}\" not found in function \"${fnName}\". ` +\n                        `Available: ${abiEntry.inputs.map((i) => i.name).join(', ')}`);\n                }\n                const param = abiEntry.inputs[paramIndex];\n                if (!isStaticAbiType(param.type)) {\n                    throw new Error(`Parameter \"${paramName}\" has dynamic type \"${param.type}\". ` +\n                        'Permission rules only support static types ' +\n                        '(address, bool, uint*, int*, bytes1–bytes32).');\n                }\n                const calldataOffset = headOffset(abiEntry.inputs, paramIndex);\n                if (rule.min !== undefined || rule.max !== undefined) {\n                    if (rule.min === undefined || rule.max === undefined) {\n                        throw new Error(`Parameter \"${paramName}\" needs both \"min\" and \"max\" — ` +\n                            'provide the other bound, or use a single ' +\n                            '{ condition, value } comparison.');\n                    }\n                    return {\n                        paramName,\n                        calldataOffset,\n                        abiType: param.type,\n                        min: rule.min,\n                        max: rule.max,\n                        usageLimit: rule.usageLimit,\n                    };\n                }\n                if (rule.anyOf !== undefined) {\n                    if (rule.anyOf.length === 0) {\n                        throw new Error(`Parameter \"${paramName}\" has empty anyOf — provide at least one value.`);\n                    }\n                    return {\n                        paramName,\n                        calldataOffset,\n                        abiType: param.type,\n                        anyOf: rule.anyOf,\n                    };\n                }\n                return {\n                    paramName,\n                    calldataOffset,\n                    abiType: param.type,\n                    condition: rule.condition,\n                    value: rule.value,\n                    usageLimit: rule.usageLimit,\n                };\n            });\n            // Both `anyOf` (OR chain) and `min`/`max` (AND of two rules on ONE param)\n            // need more than the flat one-rule-per-param shape UniActionPolicy offers.\n            const usesArgPolicy = normalized.some((n) => n.anyOf !== undefined || n.min !== undefined);\n            // UniActionPolicy/ArgPolicy reject `msg.value > valueLimitPerUse`, so a\n            // default of 0 would block any non-zero msg.value before the standalone\n            // value-limit policy (sugar) could allow it. Inherit the sugar's cap so\n            // the per-use gate matches user intent; value-limit still enforces the\n            // cumulative cap on top.\n            const embeddedValueLimit = config.valueLimitPerUse ?? config.valueLimit ?? 0n;\n            if (usesArgPolicy) {\n                // One sub-expression per param, then AND across params.\n                const perParam = normalized.map((n) => {\n                    if (n.anyOf !== undefined) {\n                        const leaves = n.anyOf.map((v) => ({\n                            type: 'rule',\n                            rule: {\n                                condition: 'equal',\n                                calldataOffset: n.calldataOffset,\n                                referenceValue: toReferenceValue(v, n.abiType),\n                            },\n                        }));\n                        return leaves.length === 1 ? leaves[0] : orChain(leaves);\n                    }\n                    if (n.min !== undefined) {\n                        // Inclusive bounds as AND(x >= min, x <= max). Deliberately NOT the\n                        // policy's own `inRange` condition: that packs two uint128 bounds\n                        // into one bytes32 `ref`, which this SDK has no verified encoding\n                        // for. Two comparisons are exactly equivalent and use primitives\n                        // already covered by tests.\n                        //\n                        // `usageLimit` rides on the lower-bound leaf only — putting it on\n                        // both would double-count every call against the cumulative cap.\n                        const minRef = toReferenceValue(n.min, n.abiType);\n                        const maxRef = toReferenceValue(n.max, n.abiType);\n                        if (typeof minRef === 'bigint' &&\n                            typeof maxRef === 'bigint' &&\n                            minRef > maxRef) {\n                            throw new Error(`Parameter \"${n.paramName}\" has min (${minRef}) greater than ` +\n                                `max (${maxRef}) — no value can satisfy this rule.`);\n                        }\n                        return andChain([\n                            {\n                                type: 'rule',\n                                rule: {\n                                    condition: 'greaterThanOrEqual',\n                                    calldataOffset: n.calldataOffset,\n                                    referenceValue: minRef,\n                                    ...(n.usageLimit !== undefined\n                                        ? { usageLimit: n.usageLimit }\n                                        : {}),\n                                },\n                            },\n                            {\n                                type: 'rule',\n                                rule: {\n                                    condition: 'lessThanOrEqual',\n                                    calldataOffset: n.calldataOffset,\n                                    referenceValue: maxRef,\n                                },\n                            },\n                        ]);\n                    }\n                    return {\n                        type: 'rule',\n                        rule: {\n                            condition: n.condition,\n                            calldataOffset: n.calldataOffset,\n                            referenceValue: toReferenceValue(n.value, n.abiType),\n                            ...(n.usageLimit !== undefined\n                                ? { usageLimit: n.usageLimit }\n                                : {}),\n                        },\n                    };\n                });\n                policies.push({\n                    type: 'arg-policy',\n                    valueLimitPerUse: embeddedValueLimit,\n                    expression: perParam.length === 1 ? perParam[0] : andChain(perParam),\n                });\n            }\n            else {\n                // Flat AND-of-rules — cheaper to init via UniActionPolicy.\n                const rules = normalized.map((n) => ({\n                    condition: n.condition,\n                    calldataOffset: n.calldataOffset,\n                    referenceValue: toReferenceValue(n.value, n.abiType),\n                    ...(n.usageLimit !== undefined ? { usageLimit: n.usageLimit } : {}),\n                }));\n                policies.push({\n                    type: 'universal-action',\n                    valueLimitPerUse: embeddedValueLimit,\n                    rules: rules,\n                });\n            }\n        }\n        else if (config.valueLimitPerUse !== undefined) {\n            policies.push({\n                type: 'value-limit',\n                limit: config.valueLimitPerUse,\n            });\n        }\n        actions.push({\n            target: address,\n            selector,\n            ...(policies.length > 0 ? { policies } : {}),\n        });\n    }\n    return actions;\n}\n// Error-path only: recover the function name behind a selector for the\n// duplicate-permission message.\nfunction findFunctionName(permission, selector) {\n    return Object.keys(permission.functions).find((name) => {\n        const entry = permission.abi.find((e) => e.type === 'function' &&\n            e.name === name);\n        return entry !== undefined && toFunctionSelector(entry) === selector;\n    });\n}\nfunction resolvePermissions(permissions) {\n    // On-chain, actions are keyed by keccak(target, selector): two permission\n    // entries for the same function on the same contract share one actionId,\n    // and the later entry's `initializeWithMultiplexer` silently overwrites the\n    // earlier one's policy config. Reject at build time instead of letting the\n    // collision surface as an opaque InvalidSignature() at execution.\n    const seen = new Set();\n    return permissions.flatMap((permission) => {\n        const actions = resolvePermission(permission);\n        for (const action of actions) {\n            const key = `${action.target.toLowerCase()}:${action.selector.toLowerCase()}`;\n            if (seen.has(key)) {\n                const fnName = findFunctionName(permission, action.selector);\n                throw new Error(`Duplicate permission for function \"${fnName}\" (selector ${action.selector}) ` +\n                    `on ${action.target}: permission entries for the same function on the same ` +\n                    \"contract share one on-chain action, so the later entry's policies would \" +\n                    'silently overwrite the earlier ones. Merge them into a single entry.');\n            }\n            seen.add(key);\n        }\n        return actions;\n    });\n}\nexport { resolvePermissions, resolvePermission };\n","/**\n * The arbiter contract keys that each settlement layer expands to. `ACROSS`\n * whitelists both arbiter impls so a session is permissioned for the 7579 and\n * multicall paths regardless of which one the orchestrator picks at intent time.\n *\n * `ECO` intentionally remains mapped to the legacy Standard ECO arbiters. The\n * solver-network ECO route uses `intentExecutorAdapter`, but the current claim\n * policy only inspects the outer origin mandate. Authorizing that generic\n * adapter would also authorize unrelated IntentExecutor-backed routes without\n * enforcing the encoded Eco destination, token, recipient, or deadline. Keep\n * solver-network ECO blocked by this built-in permission until a route-aware\n * policy is available.\n */\nconst SETTLEMENT_LAYER_CONTRACT_KEYS = {\n    SAME_CHAIN: ['samechainArbiter'],\n    ECO: ['ecoArbiter'],\n    ACROSS: ['across7579Arbiter', 'acrossMulticallArbiter'],\n};\n/**\n * Bundled arbiter allow-set — the deployed arbiter addresses per key, per\n * environment (the union across chains).\n *\n * v2: this is a small, signed-path **constant** bundled in the SDK rather than\n * read from `@rhinestone/shared-configs`. The arbiter is baked into the user's\n * Permit2 session signature, so it must stay **client-trusted** — never sourced\n * from the orchestrator you transact against. Rhinestone's arbiters are CREATE2\n * and near-uniform across chains, so this is a handful of addresses per key\n * (e.g. `ecoArbiter` has a mainnet and a testnet address). A new *chain* reuses\n * these; only a contract redeploy or a new settlement layer changes them.\n */\nconst ARBITER_ADDRESSES = {\n    prod: {\n        samechainArbiter: ['0x000000000006e2569CaF8Ff021810790e0A0D740'],\n        ecoArbiter: [\n            '0x2e7627CCfAe4eDb336eEb5a70f08415B0F1a2b8C',\n            '0xA212A6ACCC8db0e4cdf4394D0A851c70Fc27A8F0',\n        ],\n        across7579Arbiter: ['0x28a4D41776968c1201A807ec51fFB405362B8882'],\n        acrossMulticallArbiter: ['0xA162fabb9a0EeF2736485A587aAAB3d015e14224'],\n    },\n    dev: {\n        samechainArbiter: ['0x8fA7720Eee299223f25De8DC03C68A28541dCD10'],\n        ecoArbiter: [\n            '0x1BeBAfb3D05d84A5Bfd94800c88d1342f755d8AB',\n            '0x8A061029AE4c5Cf69b5368119B3b0C80B31F55fE',\n        ],\n        across7579Arbiter: ['0x1b19973F7a29E950ad4FaF8872745B6378005517'],\n        acrossMulticallArbiter: ['0x8343FBBA0526deC1c952A098057021027648bcf9'],\n    },\n};\n/**\n * Collects every distinct arbiter address for the given settlement layers. The\n * resulting whitelist is what the Permit2 claim policy enforces on-chain — a\n * session signed once with this whitelist is valid against any of those\n * arbiters.\n *\n * **\"Any\" means any of the *supported* settlement layers**, not any address on\n * earth. When `layers` is empty or undefined, this expands to the union of\n * every layer in {@link SETTLEMENT_LAYER_CONTRACT_KEYS}, so the on-chain arbiter\n * check stays meaningful (the worst case is still a Rhinestone-blessed arbiter).\n *\n * @param layers   Settlement layers the session is permitted to use.\n *                 Empty/undefined ⇒ all supported layers.\n * @param useDevContracts  Pull from the dev address book instead of mainnet.\n */\nexport function getArbitersForSettlementLayers(layers, useDevContracts) {\n    const effectiveLayers = !layers || layers.length === 0\n        ? Object.keys(SETTLEMENT_LAYER_CONTRACT_KEYS)\n        : layers;\n    const book = ARBITER_ADDRESSES[useDevContracts ? 'dev' : 'prod'];\n    const keys = effectiveLayers.flatMap((l) => SETTLEMENT_LAYER_CONTRACT_KEYS[l]);\n    const seen = new Set();\n    const addresses = [];\n    // The same logical arbiter often shares an address across chains, but a given\n    // key may have multiple addresses live (e.g. a mainnet + testnet deployment).\n    // Collect every unique address for the requested keys, deduped\n    // case-insensitively.\n    for (const key of keys) {\n        // `keys` are `SETTLEMENT_LAYER_CONTRACT_KEYS` values, so `book` always has\n        // an entry for each — no missing-key fallback needed.\n        for (const addr of book[key]) {\n            const norm = addr.toLowerCase();\n            if (seen.has(norm))\n                continue;\n            seen.add(norm);\n            addresses.push(addr);\n        }\n    }\n    return addresses.length ? addresses : undefined;\n}\n","/*\n * Adapted from Solady's LibZip FastLZ implementation:\n * https://github.com/Vectorized/solady/blob/main/js/solady.js\n * Copyright (c) 2022-2025 Solady.\n *\n * MIT License\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\nimport { bytesToHex, hexToBytes } from 'viem';\nconst HASH_TABLE_SIZE = 8192;\nconst MAX_DISTANCE = 8192;\nconst MAX_LITERAL_LENGTH = 32;\nconst MAX_MATCH_EXTENSION = 262;\nfunction readUint24(bytes, index) {\n    return bytes[index] | (bytes[index + 1] << 8) | (bytes[index + 2] << 16);\n}\nfunction hashUint24(value) {\n    // Keep Solady's number multiplication and signed shift semantics. Math.imul\n    // changes buckets for some inputs and therefore changes compressed bytes.\n    return ((2654435769 * value) >> 19) & (HASH_TABLE_SIZE - 1);\n}\nfunction writeLiterals(output, input, start, length) {\n    let cursor = start;\n    let remaining = length;\n    while (remaining >= MAX_LITERAL_LENGTH) {\n        output.push(MAX_LITERAL_LENGTH - 1);\n        for (let index = 0; index < MAX_LITERAL_LENGTH; index++) {\n            output.push(input[cursor++]);\n        }\n        remaining -= MAX_LITERAL_LENGTH;\n    }\n    if (remaining === 0)\n        return;\n    output.push(remaining - 1);\n    while (remaining-- > 0)\n        output.push(input[cursor++]);\n}\nfunction writeMatch(output, distance, extensionLength) {\n    const encodedDistance = distance - 1;\n    let remaining = extensionLength;\n    while (remaining > MAX_MATCH_EXTENSION) {\n        output.push(0xe0 + (encodedDistance >> 8), 253, encodedDistance & 0xff);\n        remaining -= MAX_MATCH_EXTENSION;\n    }\n    if (remaining < 7) {\n        output.push((remaining << 5) + (encodedDistance >> 8), encodedDistance & 0xff);\n        return;\n    }\n    output.push(0xe0 + (encodedDistance >> 8), remaining - 7, encodedDistance & 0xff);\n}\nexport function fastLzCompress(data) {\n    const input = hexToBytes(data);\n    const inputBoundary = input.length - 4;\n    const hashTable = new Uint32Array(HASH_TABLE_SIZE);\n    const output = [];\n    let anchor = 0;\n    let cursor = 2;\n    while (cursor < inputBoundary - 9) {\n        let reference = 0;\n        let distance = 0;\n        let matched = false;\n        while (cursor < inputBoundary - 9) {\n            const sequence = readUint24(input, cursor);\n            const hash = hashUint24(sequence);\n            reference = hashTable[hash] || 0;\n            hashTable[hash] = cursor;\n            distance = cursor - reference;\n            const candidate = distance < MAX_DISTANCE ? readUint24(input, reference) : 0x1000000;\n            cursor++;\n            if (sequence === candidate) {\n                matched = true;\n                break;\n            }\n        }\n        if (!matched || cursor >= inputBoundary - 9)\n            break;\n        cursor--;\n        if (cursor > anchor) {\n            writeLiterals(output, input, anchor, cursor - anchor);\n        }\n        const referenceStart = reference + 3;\n        const matchStart = cursor + 3;\n        const comparisonLength = inputBoundary - matchStart;\n        let extensionLength = 0;\n        while (extensionLength < comparisonLength) {\n            const matches = input[referenceStart + extensionLength] ===\n                input[matchStart + extensionLength];\n            extensionLength++;\n            if (!matches)\n                break;\n        }\n        cursor += extensionLength;\n        writeMatch(output, distance, extensionLength);\n        hashTable[hashUint24(readUint24(input, cursor))] = cursor++;\n        hashTable[hashUint24(readUint24(input, cursor))] = cursor++;\n        anchor = cursor;\n    }\n    writeLiterals(output, input, anchor, input.length - anchor);\n    return bytesToHex(Uint8Array.from(output));\n}\nexport function fastLzDecompress(data) {\n    const input = hexToBytes(data);\n    const output = [];\n    let cursor = 0;\n    while (cursor < input.length) {\n        const control = input[cursor];\n        const matchType = control >> 5;\n        if (matchType === 0) {\n            let literalLength = control + 1;\n            cursor++;\n            while (literalLength-- > 0)\n                output.push(input[cursor++]);\n            continue;\n        }\n        const shortMatch = matchType < 7;\n        const distance = 256 * (control & 31) + input[cursor + (shortMatch ? 1 : 2)];\n        let matchLength;\n        if (shortMatch) {\n            matchLength = matchType + 2;\n            cursor += 2;\n        }\n        else {\n            matchLength = input[cursor + 1] + 9;\n            cursor += 3;\n        }\n        let reference = output.length - distance - 1;\n        while (matchLength-- > 0)\n            output.push(output[reference++]);\n    }\n    return bytesToHex(Uint8Array.from(output));\n}\n","import { encodeAbiParameters, keccak256, toFunctionSelector, zeroHash, } from 'viem';\nimport { defineValidator } from '../definition.js';\nimport { compareHexValues } from '../ordering.js';\nimport { resolvePermissions } from '../permissions.js';\nimport { encodePermit2ClaimPolicyInitData, PERMIT2_CLAIM_POLICY_ADDRESS, } from '../policies/claim/permit2.js';\nimport { resolveValidator } from '../resolve.js';\nimport { resolveCrossChainPermission } from './cross-chain-permits.js';\nimport { getPermissionIdFromData } from './digest.js';\nimport { DEFAULT_POLICY_ADDRESSES, resolvePolicyAddresses, } from './policies/addresses.js';\nimport { expandCrossChainPermit, resolvePermit2ClaimPolicy, } from './policies/claim.js';\nimport { encodeSessionPolicy } from './policies/encode.js';\nimport { resolveSessionSigning } from './signing.js';\nimport { resolveSwapScope } from './swap/scope.js';\nexport const SMART_SESSIONS_FALLBACK_TARGET_FLAG = '0x0000000000000000000000000000000000000001';\nexport const SMART_SESSIONS_FALLBACK_TARGET_SELECTOR_FLAG = '0x00000001';\nexport const SMART_SESSIONS_FALLBACK_TARGET_SELECTOR_FLAG_PERMITTED_TO_CALL_SMARTSESSION = '0x00000002';\nexport const DUMMY_PRECLAIMOP_TARGET = '0x0000000000000000000000000000000000000420';\nexport const DUMMY_PRECLAIMOP_SELECTOR = '0x69123456';\nfunction usesEns(definition) {\n    return (definition.type === 'ens' ||\n        (definition.type === 'multi-factor' &&\n            definition.validators.some((validator) => validator.type === 'ens')));\n}\nexport function resolveSessionData(definition, options = {}) {\n    if (usesEns(definition.owners)) {\n        throw new Error('ENS owners are not supported for smart sessions');\n    }\n    const environment = options.environment ?? 'production';\n    const addresses = resolvePolicyAddresses(definition.policyAddresses);\n    const validator = resolveValidator(defineValidator(definition.owners, 'session-validator'));\n    const sudoAction = {\n        actionTargetSelector: SMART_SESSIONS_FALLBACK_TARGET_SELECTOR_FLAG,\n        actionTarget: SMART_SESSIONS_FALLBACK_TARGET_FLAG,\n        actionPolicies: [{ policy: addresses.sudo, initData: '0x' }],\n    };\n    // `swap` is sugar over permissions + actions: it compiles to one merged\n    // approve plus one scoped swap action per venue, then rides the same\n    // resolution path. Venue routers, selectors and calldata offsets stay inside\n    // swap-venues.ts so they never reach the public surface (RHI-6286).\n    const swapScope = definition.swap\n        ? resolveSwapScope(definition.swap, definition.chain.id, environment)\n        : undefined;\n    // Declaring `swap` IS the restriction — a swap-scoped session that still\n    // carried the wildcard fallback would let the session key call anything the\n    // global intent-execution whitelist allows, which is the opposite of what the\n    // caller asked for. `restrictToActions` stays as the explicit spelling for\n    // sessions scoped by hand.\n    const restricted = definition.restrictToActions === true || swapScope !== undefined;\n    const permissions = [\n        ...(definition.permissions ?? []),\n        ...(swapScope?.permissions ?? []),\n    ];\n    const userActions = permissions.length ? resolvePermissions(permissions) : [];\n    // Raw scoped actions (target + selector + policies) for calls that can't be\n    // addressed by the ABI-name `permissions` sugar — e.g. a fynd swap scoped by\n    // its raw selector with no ABI (RHI-6286).\n    const rawActions = [\n        ...(definition.actions ?? []),\n        ...(swapScope?.actions ?? []),\n    ];\n    // A restricted session drops the fallback action, which is also where a\n    // cross-chain permit's spending-limit / time-frame guardrails live — so a\n    // restricted session combined with a permit would keep claim signing but lose\n    // maxAmount/deadline enforcement. These are different authorization surfaces;\n    // reject the combination rather than silently drop the guardrails.\n    if (restricted &&\n        (definition.crossChainPermits?.length || definition.claimPolicies?.length)) {\n        throw new Error('restrictToActions is incompatible with crossChainPermits/claimPolicies: ' +\n            'dropping the fallback also drops the permit guardrails (spending/time ' +\n            'limits). Use a restricted scoped-action session or a permit session, ' +\n            'not both.');\n    }\n    // Guard raw actions from reintroducing the wildcard: reject one without\n    // target+selector (would map to the fallback flags), or one that targets the\n    // fallback sentinel outright — either would re-add the wildcard action that\n    // restrictToActions drops.\n    for (const a of rawActions) {\n        if (!('target' in a) || !('selector' in a)) {\n            throw new Error('definition.actions entries must be scoped (target + selector); a ' +\n                'fallback-shaped action would map to the wildcard fallback target');\n        }\n        if (a.target.toLowerCase() ===\n            SMART_SESSIONS_FALLBACK_TARGET_FLAG.toLowerCase()) {\n            throw new Error('definition.actions must not target the fallback sentinel ' +\n                `(${SMART_SESSIONS_FALLBACK_TARGET_FLAG}) — it reintroduces the wildcard action`);\n        }\n    }\n    const expandedPermits = (definition.crossChainPermits ?? []).map((input) => expandCrossChainPermit(resolveCrossChainPermission(input), environment));\n    const permitFallbackPolicies = expandedPermits.flatMap(({ fallbackPolicies }) => fallbackPolicies);\n    // The wildcard intent-execution fallback. Dropped for a restricted session so\n    // the explicit permissions are the ONLY authorized ops — a non-listed selector\n    // then reverts instead of escaping via the global intent-execution target\n    // whitelist (RHI-6286).\n    const fallbackAction = {\n        policies: [{ type: 'intent-execution' }, ...permitFallbackPolicies],\n    };\n    const injectedActions = [\n        // Native-wrap `deposit()` is only permitted when the caller supplies the\n        // chain's wrapped-native token (e.g. via `RhinestoneSDK.createSession`,\n        // which resolves it from `/chains`). Dropped for a restricted session so it\n        // can't add an unrequested sudo action beyond the caller's permissions.\n        ...(options.wrappedNativeToken && !restricted\n            ? [\n                {\n                    target: options.wrappedNativeToken,\n                    selector: toFunctionSelector({\n                        type: 'function',\n                        name: 'deposit',\n                        inputs: [],\n                        outputs: [],\n                        stateMutability: 'payable',\n                    }),\n                },\n            ]\n            : []),\n        ...(restricted ? [] : [fallbackAction]),\n        {\n            target: DUMMY_PRECLAIMOP_TARGET,\n            selector: DUMMY_PRECLAIMOP_SELECTOR,\n            // The real pre-claim op carries no value, so cap it for a restricted\n            // session rather than granting sudo, which would let this injected action\n            // send native value to the dummy target.\n            //\n            // 1 wei, NOT 0: `ValueLimitPolicy.initializeWithMultiplexer` does\n            // `require(valueLimit != 0)`, so a zero limit reverts while the policy is\n            // being installed. That made every restricted session impossible to\n            // enable — the revert surfaces as `InvalidSignature()` from the emissary,\n            // which reads as a signature problem rather than a policy-init one.\n            // 1 wei is the smallest limit that installs, and the op carries no value.\n            policies: restricted\n                ? [{ type: 'value-limit', limit: 1n }]\n                : [{ type: 'sudo' }],\n        },\n    ];\n    if (restricted && !userActions.length && !rawActions.length) {\n        throw new Error('restrictToActions drops the fallback, so the session must supply at ' +\n            'least one permission or action — none were given');\n    }\n    // Raw actions bypass resolvePermissions' duplicate guard, so a raw action that\n    // collides with an ABI permission (or another raw action) on the same\n    // (target, selector) would map to the same on-chain action id and silently\n    // overwrite policy config — reject it instead.\n    const scoped = [...userActions, ...rawActions].filter((a) => 'target' in a && 'selector' in a);\n    const seen = new Set();\n    for (const a of scoped) {\n        const key = `${a.target.toLowerCase()}:${a.selector.toLowerCase()}`;\n        if (seen.has(key)) {\n            throw new Error(`Duplicate scoped action for (${a.target}, ${a.selector}) — permissions ` +\n                'and actions share one on-chain action id; merge them into a single entry');\n        }\n        seen.add(key);\n    }\n    // Only the permission-derived actions: a raw action is passed through in the\n    // order it was given, on both majors, so reordering one would invent a\n    // difference rather than remove one.\n    const v1CompatibleActions = definition.saltMode === 'v1'\n        ? userActions.map((action) => ({\n            ...action,\n            policies: v1PolicyOrder(action.policies),\n        }))\n        : userActions;\n    const actions = userActions.length || rawActions.length || permitFallbackPolicies.length\n        ? [...v1CompatibleActions, ...rawActions, ...injectedActions].map((action) => ({\n            actionTargetSelector: 'selector' in action\n                ? action.selector\n                : SMART_SESSIONS_FALLBACK_TARGET_SELECTOR_FLAG,\n            actionTarget: 'target' in action\n                ? action.target\n                : SMART_SESSIONS_FALLBACK_TARGET_FLAG,\n            actionPolicies: action.policies?.map((policy) => encodeSessionPolicy(policy, environment, addresses)) ?? [{ policy: addresses.sudo, initData: '0x' }],\n        }))\n        : [sudoAction];\n    // 1.x salts a swap-scoped session over its PRODUCTION venues even when built\n    // for dev, so the salt — and the permissionId with it — does not move between\n    // environments. Reproducing one means reproducing that, and the cheapest\n    // faithful way is to resolve the same definition again at production and salt\n    // over those actions. The session itself keeps its dev venues; only the salt\n    // changes. Terminates: the recursive call resolves at production, where this\n    // is skipped.\n    const v1SaltActions = definition.saltMode === 'v1' &&\n        environment === 'development' &&\n        definition.swap !== undefined\n        ? resolveSessionData(definition, {\n            ...options,\n            environment: 'production',\n        }).actions\n        : undefined;\n    const claimPolicies = [\n        ...(definition.claimPolicies ?? []),\n        ...expandedPermits.map(({ claim }) => claim),\n    ].map((policy) => ({\n        policy: PERMIT2_CLAIM_POLICY_ADDRESS,\n        initData: encodePermit2ClaimPolicyInitData(resolvePermit2ClaimPolicy(policy)),\n    }));\n    // A restricted session must not leave an open ERC-1271 signing surface: with\n    // signing defaulting to unrestricted, a session key limited to swap/approve\n    // could still sign e.g. a Permit2 approval off-chain and move funds. Default it\n    // to `disabled` when restricting; the caller can still opt into a signing policy.\n    const erc7739Policies = resolveSessionSigning({\n        signing: definition.signing ?? (restricted ? { mode: 'disabled' } : undefined),\n        environment,\n        addresses,\n    });\n    return {\n        sessionValidator: validator.address,\n        sessionValidatorInitData: validator.initData,\n        salt: sessionSalt(definition.saltMode, restricted, {\n            actions: v1SaltActions ?? actions,\n            erc7739Policies,\n            claimPolicies,\n        }),\n        erc7739Policies,\n        actions,\n        claimPolicies,\n    };\n}\nconst POLICY_COMPONENTS = [\n    { name: 'policy', type: 'address' },\n    { name: 'initData', type: 'bytes' },\n];\n/**\n * Pick the salt for a session, defaulting to the historical `zeroHash`.\n *\n * Unrestricted sessions are always `zeroHash`: there is only one shape of them,\n * so two for the same signer are the same session and sharing a permissionId is\n * correct. Restricted ones can differ, which is what makes a salt necessary.\n */\nfunction sessionSalt(mode, restricted, session) {\n    if (!restricted || mode === undefined || mode === 'none') {\n        return zeroHash;\n    }\n    return mode === 'v1'\n        ? v1RestrictedSalt(session.actions)\n        : strictSessionSalt(session);\n}\n/**\n * The order 1.x puts an action's policies in.\n *\n * 1.x builds an approve action as `[arg policy, spending limits]`; here the\n * `spendingLimit` sugar expands before `params` compiles, so the pair comes\n * out reversed. Policies are hashed in their array order, so a 1.x session\n * only reproduces here if the order does too — the digests agree without a cap\n * and diverge with one, which is what makes this worth doing rather than\n * documenting.\n *\n * Stable in the sense that matters: the params policy moves to the front and\n * everything else keeps its order relative to the rest, though its index\n * shifts.\n */\nconst PARAMS_POLICY_TYPES = new Set(['arg-policy', 'universal-action']);\nfunction v1PolicyOrder(policies) {\n    if (!policies)\n        return policies;\n    const fromParams = policies.filter((policy) => PARAMS_POLICY_TYPES.has(policy.type));\n    if (fromParams.length === 0 || fromParams.length === policies.length) {\n        return policies;\n    }\n    return [\n        ...fromParams,\n        ...policies.filter((policy) => !PARAMS_POLICY_TYPES.has(policy.type)),\n    ];\n}\n/**\n * The 1.x derivation: the actions alone, in the order they were built.\n *\n * Reproduced rather than improved. It exists so a session built on 1.x can be\n * rebuilt here byte for byte — sorting or widening it would defeat that.\n */\nfunction v1RestrictedSalt(actions) {\n    return keccak256(encodeAbiParameters([\n        {\n            name: 'actions',\n            type: 'tuple[]',\n            components: [\n                { name: 'actionTargetSelector', type: 'bytes4' },\n                { name: 'actionTarget', type: 'address' },\n                {\n                    name: 'actionPolicies',\n                    type: 'tuple[]',\n                    components: POLICY_COMPONENTS,\n                },\n            ],\n        },\n    ], [\n        actions.map((action) => ({\n            actionTargetSelector: action.actionTargetSelector,\n            actionTarget: action.actionTarget,\n            actionPolicies: action.actionPolicies.map((policy) => ({\n                ...policy,\n            })),\n        })),\n    ]));\n}\n/**\n * Bind a restricted session's permissionId to everything it authorises.\n *\n * The permissionId derives from the validator, its init data and this salt —\n * not from the permissions. With a constant salt every session for the same\n * signer shares one permissionId, and `enable` on-chain ADDS to each list\n * rather than replacing it (`ConfigLibV2.enable`). So enabling a restricted\n * session beside an existing one for that signer unions the two: the earlier\n * session's permissions stay authorised and the restriction silently buys\n * nothing.\n *\n * Every field `_enablePolicies` writes under the permissionId has to be in\n * here, or that field alone can still collide — actions, the ERC-1271 policies\n * and 7739 content behind them, and the claim policies.\n *\n * Actions are sorted by (target, selector) so the salt is a function of the\n * authorised SET: on-chain they are keyed by action id, so listing the same\n * ones in a different order is the same authorisation and must not change the\n * permissionId.\n *\n * Unrestricted sessions keep `zeroHash`, which is what their stored signatures\n * already cover.\n */\nfunction strictSessionSalt(session) {\n    const actions = [...session.actions]\n        // By value, never host collation: `localeCompare` orders `0xaa…` after\n        // `0xb1…` on Danish-family locales, which would make the salt — and so the\n        // permissionId — depend on where it was derived.\n        .sort((a, b) => compareHexValues(a.actionTarget, b.actionTarget) ||\n        compareHexValues(a.actionTargetSelector, b.actionTargetSelector))\n        .map((action) => ({\n        actionTargetSelector: action.actionTargetSelector,\n        actionTarget: action.actionTarget,\n        actionPolicies: action.actionPolicies.map((policy) => ({ ...policy })),\n    }));\n    return keccak256(encodeAbiParameters([\n        {\n            name: 'actions',\n            type: 'tuple[]',\n            components: [\n                { name: 'actionTargetSelector', type: 'bytes4' },\n                { name: 'actionTarget', type: 'address' },\n                {\n                    name: 'actionPolicies',\n                    type: 'tuple[]',\n                    components: POLICY_COMPONENTS,\n                },\n            ],\n        },\n        {\n            name: 'erc1271Policies',\n            type: 'tuple[]',\n            components: POLICY_COMPONENTS,\n        },\n        {\n            name: 'allowedERC7739Content',\n            type: 'tuple[]',\n            components: [\n                { name: 'appDomainSeparator', type: 'bytes32' },\n                { name: 'contentNames', type: 'string[]' },\n            ],\n        },\n        {\n            name: 'claimPolicies',\n            type: 'tuple[]',\n            components: POLICY_COMPONENTS,\n        },\n    ], [\n        actions,\n        session.erc7739Policies.erc1271Policies.map((policy) => ({\n            ...policy,\n        })),\n        session.erc7739Policies.allowedERC7739Content.map((content) => ({\n            appDomainSeparator: content.appDomainSeparator,\n            contentNames: [...content.contentNames],\n        })),\n        session.claimPolicies.map((policy) => ({ ...policy })),\n    ]));\n}\nexport function toSession(definition, options = {}) {\n    const environment = options.environment ?? 'production';\n    const data = resolveSessionData(definition, {\n        environment,\n        ...(options.wrappedNativeToken\n            ? { wrappedNativeToken: options.wrappedNativeToken }\n            : {}),\n    });\n    const expandedClaims = (definition.crossChainPermits ?? []).map((input) => expandCrossChainPermit(resolveCrossChainPermission(input), environment)\n        .claim);\n    return {\n        chain: definition.chain,\n        owners: definition.owners,\n        // Drives `verifyExecutions`, which selects the signature mode: false lets an\n        // already-enabled session sign in pure ERC-1271 mode, and that mode never\n        // reaches the emissary's `verifyExecution` — so the action policies are\n        // never consulted. `swap` compiles to actions, so it MUST count here, or a\n        // swap-only session would silently stop being action-checked the moment it\n        // is enabled.\n        hasExplicitPermissions: Boolean(definition.permissions?.length ||\n            definition.actions?.length ||\n            definition.swap),\n        permissionId: getPermissionIdFromData(data),\n        sessionValidator: data.sessionValidator,\n        sessionValidatorInitData: data.sessionValidatorInitData,\n        salt: data.salt,\n        erc7739Policies: data.erc7739Policies,\n        actions: data.actions,\n        claimPolicies: [...(definition.claimPolicies ?? []), ...expandedClaims],\n        ...(definition.swap ? { swap: definition.swap } : {}),\n    };\n}\nexport { DEFAULT_POLICY_ADDRESSES };\n","function seconds(input) {\n    return BigInt(Math.floor(input.getTime() / 1000));\n}\nfunction normalizeLegs(legs) {\n    if (legs === undefined)\n        return undefined;\n    const values = Array.isArray(legs) ? legs : [legs];\n    return values.length === 0 ? undefined : values;\n}\n// Token fields are per-chain ERC-20 addresses (v2 no longer accepts symbols),\n// so legs pass through directly; only the `Date` bounds are converted.\nexport function resolveCrossChainPermission(input) {\n    const from = normalizeLegs(input.from)?.map((leg) => ({\n        chain: leg.chain,\n        token: leg.token,\n        ...(leg.maxAmount === undefined ? {} : { maxAmount: leg.maxAmount }),\n    }));\n    const to = normalizeLegs(input.to)?.map((leg) => ({\n        chain: leg.chain,\n        token: leg.token,\n        ...(leg.recipient === undefined ? {} : { recipient: leg.recipient }),\n    }));\n    const validUntil = input.validUntil ? seconds(input.validUntil) : undefined;\n    const validAfter = input.validAfter ? seconds(input.validAfter) : undefined;\n    if (validUntil !== undefined &&\n        validAfter !== undefined &&\n        validAfter > validUntil) {\n        throw new Error(`crossChainPermits: validAfter (${validAfter}) is greater than validUntil (${validUntil})`);\n    }\n    return {\n        ...(from ? { from } : {}),\n        ...(to ? { to } : {}),\n        ...(validUntil === undefined ? {} : { validUntil }),\n        ...(validAfter === undefined ? {} : { validAfter }),\n        ...(input.fillDeadline\n            ? {\n                fillDeadline: input.fillDeadline.map(({ chain, min, max }) => ({\n                    chain,\n                    ...(min ? { min: seconds(min) } : {}),\n                    ...(max ? { max: seconds(max) } : {}),\n                })),\n            }\n            : {}),\n        recipientIsAccount: !input.allowRecipientNotAccount,\n        ...(input.settlementLayers\n            ? { settlementLayers: input.settlementLayers }\n            : {}),\n    };\n}\nexport function toCrossChainPermissionInput(permit) {\n    const date = (value) => new Date(Number(value) * 1000);\n    return {\n        ...(permit.from ? { from: permit.from } : {}),\n        ...(permit.to ? { to: permit.to } : {}),\n        ...(permit.validUntil === undefined\n            ? {}\n            : { validUntil: date(permit.validUntil) }),\n        ...(permit.validAfter === undefined\n            ? {}\n            : { validAfter: date(permit.validAfter) }),\n        ...(permit.fillDeadline\n            ? {\n                fillDeadline: permit.fillDeadline.map(({ chain, min, max }) => ({\n                    chain,\n                    ...(min === undefined ? {} : { min: date(min) }),\n                    ...(max === undefined ? {} : { max: date(max) }),\n                })),\n            }\n            : {}),\n        ...(permit.recipientIsAccount === undefined\n            ? {}\n            : { allowRecipientNotAccount: !permit.recipientIsAccount }),\n        ...(permit.settlementLayers\n            ? { settlementLayers: permit.settlementLayers }\n            : {}),\n    };\n}\n","export const SPENDING_LIMITS_POLICY_ADDRESS = '0x000000000033212E272655D8a22402Db819477A6';\nexport const TIME_FRAME_POLICY_ADDRESS = '0x0000000000D30f611fA3bf652ac6879428586930';\nexport const SUDO_POLICY_ADDRESS = '0x0000000000FEEc8D74e3143fBaBbca515358d869';\nexport const UNIVERSAL_ACTION_POLICY_ADDRESS = '0x0000000000714Cf48FcF88A0bFBa70d313415032';\nexport const ARG_POLICY_ADDRESS = '0x0000000000167edE64D8751daACDdC0312565a73';\nexport const USAGE_LIMIT_POLICY_ADDRESS = '0x00000000001d4479FA2A947026204d0283ceDe4B';\nexport const VALUE_LIMIT_POLICY_ADDRESS = '0x000000000021dC45451291BCDfc9f0B46d6f0278';\nexport const INTENT_EXECUTION_POLICY_ADDRESS = '0xe9eA54d063975cDee9e06b7636d5563d95a7A23C';\nexport const INTENT_EXECUTION_POLICY_ADDRESS_DEV = '0xa09b47de6e510cbdc18b97e9239bedcb44fb4901';\nexport const DEFAULT_POLICY_ADDRESSES = Object.freeze({\n    sudo: SUDO_POLICY_ADDRESS,\n    universalAction: UNIVERSAL_ACTION_POLICY_ADDRESS,\n    argPolicy: ARG_POLICY_ADDRESS,\n    spendingLimits: SPENDING_LIMITS_POLICY_ADDRESS,\n    timeFrame: TIME_FRAME_POLICY_ADDRESS,\n    usageLimit: USAGE_LIMIT_POLICY_ADDRESS,\n    valueLimit: VALUE_LIMIT_POLICY_ADDRESS,\n});\nexport function resolvePolicyAddresses(overrides) {\n    return {\n        sudo: overrides?.sudo ?? DEFAULT_POLICY_ADDRESSES.sudo,\n        universalAction: overrides?.universalAction ?? DEFAULT_POLICY_ADDRESSES.universalAction,\n        argPolicy: overrides?.argPolicy ?? DEFAULT_POLICY_ADDRESSES.argPolicy,\n        spendingLimits: overrides?.spendingLimits ?? DEFAULT_POLICY_ADDRESSES.spendingLimits,\n        timeFrame: overrides?.timeFrame ?? DEFAULT_POLICY_ADDRESSES.timeFrame,\n        usageLimit: overrides?.usageLimit ?? DEFAULT_POLICY_ADDRESSES.usageLimit,\n        valueLimit: overrides?.valueLimit ?? DEFAULT_POLICY_ADDRESSES.valueLimit,\n    };\n}\n","import { encodeAbiParameters, encodePacked, isHex, padHex, toHex, zeroHash, } from 'viem';\nimport { DEFAULT_POLICY_ADDRESSES, INTENT_EXECUTION_POLICY_ADDRESS, INTENT_EXECUTION_POLICY_ADDRESS_DEV, } from './addresses.js';\nconst conditionIds = {\n    equal: 0,\n    greaterThan: 1,\n    lessThan: 2,\n    greaterThanOrEqual: 3,\n    lessThanOrEqual: 4,\n    notEqual: 5,\n    inRange: 6,\n};\nfunction encodeRule(rule) {\n    return {\n        condition: conditionIds[rule.condition],\n        offset: rule.calldataOffset,\n        isLimited: rule.usageLimit !== undefined,\n        ref: isHex(rule.referenceValue)\n            ? padHex(rule.referenceValue)\n            : toHex(rule.referenceValue, { size: 32 }),\n        usage: { limit: rule.usageLimit ?? 0n, used: 0n },\n    };\n}\nfunction compileExpression(expression) {\n    const rules = [];\n    const nodes = [];\n    const walk = (node) => {\n        if (node.type === 'rule') {\n            const ruleIndex = rules.push(encodeRule(node.rule)) - 1;\n            const nodeIndex = nodes.length;\n            nodes.push(BigInt(ruleIndex) << 2n);\n            return nodeIndex;\n        }\n        if (node.type === 'not') {\n            const child = walk(node.child);\n            const nodeIndex = nodes.length;\n            nodes.push(1n | (BigInt(child) << 10n));\n            return nodeIndex;\n        }\n        const left = walk(node.left);\n        const right = walk(node.right);\n        const nodeIndex = nodes.length;\n        nodes.push((node.type === 'and' ? 2n : 3n) |\n            (BigInt(left) << 10n) |\n            (BigInt(right) << 18n));\n        return nodeIndex;\n    };\n    const rootNodeIndex = walk(expression);\n    if (rules.length > 128) {\n        throw new Error(`ArgPolicy expression has ${rules.length} rules, max is 128`);\n    }\n    if (nodes.length > 256) {\n        throw new Error(`ArgPolicy expression has ${nodes.length} nodes, max is 256`);\n    }\n    return { rules, packedNodes: nodes, rootNodeIndex };\n}\nexport function encodeSessionPolicy(policy, environment, addresses = DEFAULT_POLICY_ADDRESSES) {\n    switch (policy.type) {\n        case 'sudo':\n            return { policy: addresses.sudo, initData: '0x' };\n        case 'intent-execution':\n            return {\n                policy: environment === 'development'\n                    ? INTENT_EXECUTION_POLICY_ADDRESS_DEV\n                    : INTENT_EXECUTION_POLICY_ADDRESS,\n                initData: '0x',\n            };\n        case 'universal-action': {\n            const rules = Array.from({ length: 16 }, () => ({\n                condition: 0,\n                offset: 0n,\n                isLimited: false,\n                ref: zeroHash,\n                usage: { limit: 0n, used: 0n },\n            }));\n            if (policy.rules.length > rules.length) {\n                throw new Error('Universal action policy supports at most 16 rules');\n            }\n            policy.rules.forEach((rule, index) => {\n                rules[index] = encodeRule(rule);\n            });\n            return {\n                policy: addresses.universalAction,\n                initData: encodeAbiParameters([\n                    {\n                        name: 'ActionConfig',\n                        type: 'tuple',\n                        components: [\n                            { name: 'valueLimitPerUse', type: 'uint256' },\n                            {\n                                name: 'paramRules',\n                                type: 'tuple',\n                                components: [\n                                    { name: 'length', type: 'uint256' },\n                                    {\n                                        name: 'rules',\n                                        type: 'tuple[16]',\n                                        components: [\n                                            { name: 'condition', type: 'uint8' },\n                                            { name: 'offset', type: 'uint64' },\n                                            { name: 'isLimited', type: 'bool' },\n                                            { name: 'ref', type: 'bytes32' },\n                                            {\n                                                name: 'usage',\n                                                type: 'tuple',\n                                                components: [\n                                                    { name: 'limit', type: 'uint256' },\n                                                    { name: 'used', type: 'uint256' },\n                                                ],\n                                            },\n                                        ],\n                                    },\n                                ],\n                            },\n                        ],\n                    },\n                ], [\n                    {\n                        valueLimitPerUse: policy.valueLimitPerUse ?? 0n,\n                        paramRules: { length: BigInt(policy.rules.length), rules },\n                    },\n                ]),\n            };\n        }\n        case 'arg-policy': {\n            const compiled = compileExpression(policy.expression);\n            return {\n                policy: addresses.argPolicy,\n                initData: encodeAbiParameters([\n                    {\n                        name: 'ActionConfig',\n                        type: 'tuple',\n                        components: [\n                            { name: 'valueLimitPerUse', type: 'uint256' },\n                            {\n                                name: 'paramRules',\n                                type: 'tuple',\n                                components: [\n                                    { name: 'rootNodeIndex', type: 'uint8' },\n                                    {\n                                        name: 'rules',\n                                        type: 'tuple[]',\n                                        components: [\n                                            { name: 'condition', type: 'uint8' },\n                                            { name: 'offset', type: 'uint64' },\n                                            { name: 'isLimited', type: 'bool' },\n                                            { name: 'ref', type: 'bytes32' },\n                                            {\n                                                name: 'usage',\n                                                type: 'tuple',\n                                                components: [\n                                                    { name: 'limit', type: 'uint256' },\n                                                    { name: 'used', type: 'uint256' },\n                                                ],\n                                            },\n                                        ],\n                                    },\n                                    { name: 'packedNodes', type: 'uint256[]' },\n                                ],\n                            },\n                        ],\n                    },\n                ], [\n                    {\n                        valueLimitPerUse: policy.valueLimitPerUse ?? 0n,\n                        paramRules: compiled,\n                    },\n                ]),\n            };\n        }\n        case 'spending-limits':\n            return {\n                policy: addresses.spendingLimits,\n                initData: encodeAbiParameters([{ type: 'address[]' }, { type: 'uint256[]' }], [\n                    policy.limits.map(({ token }) => token),\n                    policy.limits.map(({ amount }) => amount),\n                ]),\n            };\n        case 'time-frame':\n            return {\n                policy: addresses.timeFrame,\n                initData: encodePacked(['uint48', 'uint48'], [\n                    Math.floor(policy.validUntil / 1000),\n                    Math.floor(policy.validAfter / 1000),\n                ]),\n            };\n        case 'usage-limit':\n            return {\n                policy: addresses.usageLimit,\n                initData: encodePacked(['uint128'], [policy.limit]),\n            };\n        case 'value-limit':\n            return {\n                policy: addresses.valueLimit,\n                initData: encodeAbiParameters([{ type: 'uint256' }], [policy.limit]),\n            };\n    }\n}\n","import { domainSeparator, zeroHash } from 'viem';\nimport { FAR_FUTURE_MS } from '../permissions.js';\nimport { encodeErc7739ContentType } from './erc7739.js';\nimport { encodeSessionPolicy } from './policies/encode.js';\nconst UINT48_MAX = 2 ** 48 - 1;\nconst DOMAIN_FIELDS = new Set([\n    'name',\n    'version',\n    'chainId',\n    'verifyingContract',\n    'salt',\n]);\nconst IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/u;\nexport function resolveSessionSigning(input) {\n    const signing = input.signing ?? { mode: 'unrestricted' };\n    if (signing.mode === 'disabled') {\n        if ('validAfter' in signing || 'validUntil' in signing) {\n            throw new Error('Disabled session signing cannot have a validity window');\n        }\n        return { allowedERC7739Content: [], erc1271Policies: [] };\n    }\n    const allowedERC7739Content = signing.mode === 'unrestricted'\n        ? [{ appDomainSeparator: zeroHash, contentNames: [''] }]\n        : resolveAllowedContents(signing.allowedContents);\n    return {\n        allowedERC7739Content,\n        erc1271Policies: [\n            resolveSigningPolicy({\n                validAfter: signing.validAfter,\n                validUntil: signing.validUntil,\n                environment: input.environment,\n                addresses: input.addresses,\n            }),\n        ],\n    };\n}\nfunction resolveAllowedContents(contents) {\n    if (contents.length === 0) {\n        throw new Error('Scoped session signing requires at least one allowed content');\n    }\n    const byDomain = new Map();\n    const seen = new Set();\n    for (const content of contents) {\n        validateContent(content);\n        const appDomainSeparator = domainSeparator({ domain: content.domain });\n        const contentName = encodeErc7739ContentType({\n            primaryType: content.primaryType,\n            types: content.types,\n        });\n        const duplicateKey = `${appDomainSeparator}:${contentName}`;\n        if (seen.has(duplicateKey)) {\n            throw new Error(`Duplicate scoped signing content for ${content.primaryType} under domain ${appDomainSeparator}`);\n        }\n        seen.add(duplicateKey);\n        const group = byDomain.get(appDomainSeparator);\n        if (group)\n            group.contentNames.push(contentName);\n        else {\n            byDomain.set(appDomainSeparator, {\n                appDomainSeparator,\n                contentNames: [contentName],\n            });\n        }\n    }\n    return [...byDomain.values()];\n}\nfunction validateContent(content) {\n    for (const field of Object.keys(content.domain)) {\n        if (!DOMAIN_FIELDS.has(field)) {\n            throw new Error(`Unsupported EIP-712 domain field \"${field}\"`);\n        }\n    }\n    if (content.primaryType === 'EIP712Domain') {\n        throw new Error('EIP712Domain cannot be a scoped signing primary type');\n    }\n    if (!content.types[content.primaryType]) {\n        throw new Error(`Scoped signing primary type \"${content.primaryType}\" is missing from types`);\n    }\n    validateTypeDependencies(content.primaryType, content.types);\n}\nfunction validateTypeDependencies(primaryType, types) {\n    const visited = new Set();\n    const visit = (type) => {\n        const match = type.match(/^([A-Za-z_][A-Za-z0-9_]*)(\\[(?:[1-9][0-9]*)?\\])*$/u);\n        if (!match) {\n            throw new Error(`Scoped signing type \"${type}\" is not a valid EIP-712 type`);\n        }\n        const typeName = match[1];\n        if (typeName === 'uint' || typeName === 'int') {\n            throw new Error(`Scoped signing type \"${typeName}\" is not a valid EIP-712 type`);\n        }\n        if (isPrimitiveType(typeName) || visited.has(typeName))\n            return;\n        const fields = types[typeName];\n        if (!fields) {\n            throw new Error(`Scoped signing type \"${typeName}\" is missing from types`);\n        }\n        visited.add(typeName);\n        const fieldNames = new Set();\n        for (const field of fields) {\n            if (!IDENTIFIER.test(field.name)) {\n                throw new Error(`Scoped signing field name \"${field.name}\" in ${typeName} is invalid`);\n            }\n            if (fieldNames.has(field.name)) {\n                throw new Error(`Scoped signing type \"${typeName}\" has duplicate field \"${field.name}\"`);\n            }\n            fieldNames.add(field.name);\n            visit(field.type);\n        }\n    };\n    visit(primaryType);\n}\nfunction isPrimitiveType(type) {\n    return (type === 'address' ||\n        type === 'bool' ||\n        type === 'string' ||\n        type === 'bytes' ||\n        /^bytes([1-9]|[12][0-9]|3[0-2])$/u.test(type) ||\n        /^(u?int)(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)$/u.test(type));\n}\nfunction resolveSigningPolicy(input) {\n    if (input.validAfter === undefined && input.validUntil === undefined) {\n        return encodeSessionPolicy({ type: 'sudo' }, input.environment, input.addresses);\n    }\n    const validAfter = dateSeconds(input.validAfter ?? new Date(0), 'validAfter');\n    const validUntil = dateSeconds(input.validUntil ?? new Date(FAR_FUTURE_MS), 'validUntil');\n    if (validUntil < validAfter) {\n        throw new Error('Session signing validUntil is before validAfter');\n    }\n    return encodeSessionPolicy({\n        type: 'time-frame',\n        validAfter: validAfter * 1000,\n        validUntil: validUntil * 1000,\n    }, input.environment, input.addresses);\n}\nfunction dateSeconds(date, field) {\n    const milliseconds = date.getTime();\n    if (!Number.isFinite(milliseconds)) {\n        throw new Error(`Session signing ${field} must be a valid Date`);\n    }\n    const seconds = Math.floor(milliseconds / 1000);\n    if (seconds < 0 || seconds > UINT48_MAX) {\n        throw new Error(`Session signing ${field} is outside the uint48 range`);\n    }\n    return seconds;\n}\n","export function encodeErc7739ContentType(input) {\n    const { primaryType, types } = input;\n    const dependencies = new Set();\n    const collect = (type) => {\n        const typeName = type.match(/^\\w*/)?.[0];\n        if (!typeName || dependencies.has(typeName) || !types[typeName])\n            return;\n        dependencies.add(typeName);\n        for (const field of types[typeName])\n            collect(field.type);\n    };\n    collect(primaryType);\n    dependencies.delete(primaryType);\n    return [primaryType, ...[...dependencies].sort()]\n        .map((type) => `${type}(${types[type].map((field) => `${field.type} ${field.name}`).join(',')})`)\n        .join('');\n}\n","import { toFunctionSelector } from 'viem';\nimport { namedParamOffsets } from '../../permissions.js';\nimport { cumulativeCap, pin, sellPinsGoInAlternatives, swapAction, } from './rules.js';\n/**\n * fynd — Rhinestone's self-hosted Tycho aggregator.\n *\n * Unlike 0x there is no allowance-holder indirection: the TychoRouter is both\n * the swap target and the ERC-20 approval spender, and every field we care about\n * is a named static argument in the calldata head. That means nothing here is a\n * magic offset — the rules are addressed by ABI parameter name.\n */\n/** Chains with a deployed, whitelisted TychoRouter. */\nexport const FYND_CHAIN_IDS = [1, 56, 130, 137, 8453, 9745, 42161];\n/**\n * TychoRouter per chain — the contract fynd's encoded fills target.\n *\n * Mirrors `fynd.routers` in the orchestrator's quoters.jsonnet. A chain is\n * listed only when the router is whitelisted in `IntentExecutionPolicy`, since a\n * quoter enabled without a whitelisted target produces quotes that revert.\n */\nexport const FYND_ROUTERS = {\n    1: '0xda892c989d07a18b5dd3f392d949f00df15c5736',\n    56: '0x99748cbd931cb367dad265c5b2b4bd306d448e99',\n    130: '0x764bc67b1036b00bc91221e988261f971a1c7ce4',\n    137: '0x7cb3e87095f6cf95982dc6f57445171a6d3b511c',\n    8453: '0x2d3524b9b5dae34b646614eebb1e038d403e4cac',\n    9745: '0x8f9b3b0451efff0ae8100428aee35fa3cbc0b769',\n    42161: '0xc1f838a5382bbb5729a0801c8ba73dfc861c4d34',\n};\n/**\n * TychoRouter `singleSwap`, the entrypoint fynd's encoded quotes call.\n *\n * Only the argument TYPES determine the selector and the head layout, and those\n * are pinned by {@link FYND_SWAP_SELECTOR}'s assertion in the test suite. The\n * NAMES of the first five are corroborated by observed fynd calldata; the\n * trailing tuple's component names are our own labels and carry no guarantee —\n * we never address them, since a tuple containing `bytes` is dynamic and sits\n * behind a pointer.\n */\nexport const tychoRouterAbi = [\n    {\n        type: 'function',\n        name: 'singleSwap',\n        stateMutability: 'payable',\n        inputs: [\n            { name: 'amountIn', type: 'uint256' },\n            { name: 'tokenIn', type: 'address' },\n            { name: 'tokenOut', type: 'address' },\n            { name: 'minAmountOut', type: 'uint256' },\n            { name: 'receiver', type: 'address' },\n            {\n                name: 'permit',\n                type: 'tuple',\n                components: [\n                    { name: 'nonce', type: 'uint16' },\n                    { name: 'token', type: 'address' },\n                    { name: 'amount', type: 'uint256' },\n                    { name: 'deadline', type: 'uint256' },\n                    { name: 'signature', type: 'bytes' },\n                ],\n            },\n            { name: 'swap', type: 'bytes' },\n        ],\n        outputs: [{ name: 'amountOut', type: 'uint256' }],\n    },\n];\nexport const FYND_SWAP_SELECTOR = toFunctionSelector(tychoRouterAbi[0]);\n/** Head offsets derived from the ABI — never hardcoded. */\nconst OFFSETS = namedParamOffsets(tychoRouterAbi, 'singleSwap');\n/**\n * Scope a session to fynd swaps.\n *\n * Needs no addresses: the router is a per-chain deployment the SDK knows, and\n * because it is also the approval spender there is no separate allowance target\n * to reason about.\n */\nexport function fynd(options = {}) {\n    return {\n        id: 'fynd',\n        ...(options.maxSpend !== undefined ? { maxSpend: options.maxSpend } : {}),\n    };\n}\nexport function scopeFynd(ctx) {\n    const router = FYND_ROUTERS[ctx.chainId];\n    if (router === undefined) {\n        throw new Error(`fynd is not available on chain ${ctx.chainId}. ` +\n            `Supported: ${FYND_CHAIN_IDS.join(', ')}.`);\n    }\n    const multiSell = sellPinsGoInAlternatives(ctx);\n    const rules = [\n        // One token keeps its pin here, which is what preserves the historical\n        // rule order, policy type and digest.\n        ...(multiSell ? [] : [pin(OFFSETS.tokenIn, ctx.sellTokens[0])]),\n        pin(OFFSETS.tokenOut, ctx.buyToken),\n        pin(OFFSETS.receiver, ctx.recipient),\n    ];\n    if (ctx.cap !== undefined) {\n        rules.push(cumulativeCap(OFFSETS.amountIn, ctx.cap));\n    }\n    // Several tokens become an OR over the one word that differs between them.\n    const sellAlternatives = multiSell\n        ? ctx.sellTokens.map((token) => [pin(OFFSETS.tokenIn, token)])\n        : [];\n    return {\n        approveSpenders: [router],\n        actions: [swapAction(router, FYND_SWAP_SELECTOR, rules, sellAlternatives)],\n    };\n}\n","/**\n * Shared rule builders for swap-venue scoping.\n *\n * Venue modules describe *what* to pin; these turn that into policy rules with\n * the security-relevant details (cumulative accumulation, zero native value)\n * decided in exactly one place.\n */\n/**\n * Pin a calldata word to an exact numeric value.\n *\n * Used for ABI *shape* words — array pointers, lengths, element offsets. Pinning\n * those is what makes pinning anything inside a dynamic tail sound: without\n * them a caller can re-lay-out the encoding so a fixed offset lands on a\n * different word, and the rule silently validates the wrong bytes.\n */\nexport function pinValue(calldataOffset, referenceValue) {\n    return { condition: 'equal', calldataOffset, referenceValue };\n}\n/** Pin a calldata word to an exact 32-byte value. */\nexport function pinWord(calldataOffset, referenceValue) {\n    return { condition: 'equal', calldataOffset, referenceValue };\n}\n/** Pin a calldata word to an exact address. */\nexport function pin(calldataOffset, referenceValue) {\n    return { condition: 'equal', calldataOffset, referenceValue };\n}\n/**\n * Cap a swap's own sell amount, cumulatively across every call.\n *\n * `usageLimit` is what makes this cumulative: it sets `isLimited` + `usage.limit`\n * on-chain, so the policy accumulates the observed value and reverts once the\n * running total would exceed the cap.\n *\n * A bare comparison would be per-call, which is not enough. A reusable session\n * could then run N swaps of `cap` each, and any allowance that already existed\n * before the session was created is spent without the approve's spending-limit\n * ever observing it.\n */\nexport function cumulativeCap(calldataOffset, cap) {\n    return {\n        condition: 'lessThanOrEqual',\n        calldataOffset,\n        referenceValue: cap,\n        usageLimit: cap,\n    };\n}\n/**\n * Wrap rules into the action's policy.\n *\n * `valueLimitPerUse: 0n` because the approve cap only bounds ERC-20 pulls —\n * without it, a payable swap selector could still carry arbitrary native value\n * through the router.\n */\n/** Every rule must hold, as a right-folded AND over the expression tree. */\nfunction allOf(rules) {\n    return rules\n        .map((rule) => ({ type: 'rule', rule }))\n        .reduceRight((right, left) => ({ type: 'and', left, right }));\n}\n/**\n * Wrap rules into the action's policy.\n *\n * `valueLimitPerUse: 0n` because the approve cap only bounds ERC-20 pulls —\n * without it, a payable swap selector could still carry arbitrary native value\n * through the router.\n *\n * UniversalActionPolicy while the rules fit its fixed 16-slot array, which is\n * every venue except a fully-pinned wrapped route — those pin the shape words,\n * both call targets, the approve and the nested exec, and run past 16. ArgPolicy\n * takes a dynamic rule list, so it carries the overflow rather than forcing a\n * pin to be dropped. Preferring the simpler policy keeps the common case on the\n * contract it has always used.\n */\nconst UNIVERSAL_ACTION_MAX_RULES = 16;\nexport function swapAction(target, selector, rules, \n/**\n * Mutually exclusive rule sets, at least one of which must hold — used when\n * several venues authorise the SAME call but pin its tail to different\n * aggregators. One on-chain action id cannot carry two policies, and dropping\n * the pins to share it would authorise a tail neither venue named, so the\n * alternatives become an OR instead.\n */\nalternatives = []) {\n    const usable = alternatives.filter((set) => set.length > 0);\n    const policy = usable.length > 0\n        ? {\n            type: 'arg-policy',\n            valueLimitPerUse: 0n,\n            expression: {\n                type: 'and',\n                left: allOf(rules),\n                right: usable\n                    .map(allOf)\n                    .reduce((left, right) => ({ type: 'or', left, right })),\n            },\n        }\n        : rules.length <= UNIVERSAL_ACTION_MAX_RULES\n            ? {\n                type: 'universal-action',\n                valueLimitPerUse: 0n,\n                rules: rules,\n            }\n            : { type: 'arg-policy', valueLimitPerUse: 0n, expression: allOf(rules) };\n    return { target, selector, policies: [policy] };\n}\n/**\n * Whether the sell-token pins belong in the action's OR branches rather than\n * its shared rules.\n *\n * Only when there is more than one. With a single token the pin stays where it\n * has always been, which keeps the rule list, the chosen policy type and\n * therefore the session digest byte-identical to what callers have already\n * signed. Moving it unconditionally would be a HashMismatch for every existing\n * swap session.\n */\nexport function sellPinsGoInAlternatives(ctx) {\n    return ctx.sellTokens.length > 1;\n}\n","import { toFunctionSelector } from 'viem';\nimport { namedParamOffsets } from '../../permissions.js';\nimport { FYND_CHAIN_IDS, FYND_ROUTERS } from './fynd.js';\nimport { cumulativeCap, pin, pinValue, pinWord, sellPinsGoInAlternatives, swapAction, } from './rules.js';\nimport { ZEROX_ALLOWANCE_HOLDER, ZEROX_CHAIN_IDS } from './zero-ex.js';\n/**\n * The Rhinestone Swapper — the route the orchestrator actually uses for\n * same-chain smart-account swaps, and the right layer to scope a session at.\n *\n * Scoping an aggregator directly (see `zero-ex.ts`, `fynd.ts`) describes a call\n * the account does not make on this route: the orchestrator wraps whichever\n * quoter wins behind its own Swapper, so a session scoped to 0x's\n * AllowanceHolder rejects its own intended swap with `InvalidSignature()`.\n * Verified live on Plasma — the account's sell token moves to the Swapper, and\n * the aggregator never appears in the account's ops.\n *\n * Scoping here is also strictly better:\n *   - aggregator-agnostic, so whichever quoter wins is irrelevant\n *   - no 0x Settler rotation problem, because this contract is ours\n *   - one approve target per chain (the proxy) instead of one per venue\n *   - the fields we care about are typed head args on a contract we control,\n *     with the aggregator route demoted to an opaque `calls[]` tail\n *\n * What the Swapper guarantees (verified in compact-utils/src/swapper):\n * at most `amountIn` of `tokenIn` is pulled, once, from `msg.sender`; the\n * recipient's measured balance delta must be >= `minAmountOut` or it reverts;\n * every refund and sweep goes to `msg.sender`. The account cannot be drained\n * beyond the pulled amount: the tail runs as the Swapper, which holds no\n * allowance from the account, and `SwapperLib.runRoute` forbids the tail from\n * calling the proxy that does.\n *\n * Be precise about what that bounds, though. A capped `amountIn` bounds how\n * much can LEAVE; it does not ensure anything comes back. `minAmountOut` is a\n * caller-supplied argument this scoping does not pin, and the contract accepts\n * zero — so with an unconstrained route a compromised key can spend up to the\n * cap and receive nothing. Naming a venue closes that by pinning the\n * route, leaving the pulled input nowhere to go but a real aggregator.\n */\n/**\n * Both entrypoints share a head layout, which is what lets one venue cover\n * both: `tokenIn`@0, sell amount@32, `tokenOut`@64, `recipient`@160. The sell\n * amount is `amountIn` for exact-in and `amountInMax` for exact-out — in both\n * cases the ceiling on what leaves the account, which is exactly what to cap.\n */\nexport const swapperAbi = [\n    {\n        type: 'function',\n        name: 'swapExactIn',\n        stateMutability: 'payable',\n        inputs: [\n            { name: 'tokenIn', type: 'address' },\n            { name: 'amountIn', type: 'uint256' },\n            { name: 'tokenOut', type: 'address' },\n            { name: 'minAmountOut', type: 'uint256' },\n            { name: 'quotedAmountOut', type: 'uint256' },\n            { name: 'recipient', type: 'address' },\n            { name: 'orderRef', type: 'uint256' },\n            {\n                name: 'calls',\n                type: 'tuple[]',\n                components: [\n                    { name: 'target', type: 'address' },\n                    { name: 'value', type: 'uint256' },\n                    { name: 'data', type: 'bytes' },\n                ],\n            },\n        ],\n        outputs: [{ name: 'amountOut', type: 'uint256' }],\n    },\n    {\n        type: 'function',\n        name: 'swapExactOut',\n        stateMutability: 'payable',\n        inputs: [\n            { name: 'tokenIn', type: 'address' },\n            { name: 'amountInMax', type: 'uint256' },\n            { name: 'tokenOut', type: 'address' },\n            { name: 'amountOut', type: 'uint256' },\n            { name: 'quotedAmountIn', type: 'uint256' },\n            { name: 'recipient', type: 'address' },\n            { name: 'orderRef', type: 'uint256' },\n            {\n                name: 'calls',\n                type: 'tuple[]',\n                components: [\n                    { name: 'target', type: 'address' },\n                    { name: 'value', type: 'uint256' },\n                    { name: 'data', type: 'bytes' },\n                ],\n            },\n        ],\n        outputs: [{ name: 'amountSpent', type: 'uint256' }],\n    },\n];\nexport const SWAP_EXACT_IN_SELECTOR = toFunctionSelector(swapperAbi[0]);\nexport const SWAP_EXACT_OUT_SELECTOR = toFunctionSelector(swapperAbi[1]);\nconst EXACT_IN = namedParamOffsets(swapperAbi, 'swapExactIn');\nconst EXACT_OUT = namedParamOffsets(swapperAbi, 'swapExactOut');\n/**\n * Deployed via CREATE2, so one address covers every chain. The proxy is\n * `new`'d in the Swapper's constructor and the binding is immutable both ways,\n * so a Swapper redeploy also changes the proxy — verify both together.\n *\n * Confirmed on Plasma: `Swapper.PROXY()` returns the proxy below.\n */\nconst SWAPPER_PRODUCTION = '0x40CE38e0cbB8ec54a601256E4FacfED5679bccD0';\nconst PROXY_PRODUCTION = '0x5afCe415B4370E5EfD8B9BE784d21C331bEAb965';\nconst SWAPPER_DEVELOPMENT = '0x8206052a213AA7cafB18ec7898e8D1D421C02100';\nconst PROXY_DEVELOPMENT = '0x21416a06e81fe115a5c8bf554b2b01383bd9b9f3';\nexport function swapperAddresses(environment) {\n    return environment === 'development'\n        ? { swapper: SWAPPER_DEVELOPMENT, proxy: PROXY_DEVELOPMENT }\n        : { swapper: SWAPPER_PRODUCTION, proxy: PROXY_PRODUCTION };\n}\n/**\n * Byte offsets of the `calls[]` ABI *shape* words, measured in the Swapper's\n * calldata past the selector. Identical for `swapExactIn` and `swapExactOut`\n * because both have the same eight-word head.\n *\n * Pinning a target inside a dynamic array is only sound if the layout is also\n * pinned: a compromised session key controls the encoding and could otherwise\n * relocate elements so a fixed offset reads an innocuous word. Pinning the array\n * pointer, the length, and each element pointer fixes every position, making the\n * target offsets exact.\n *\n * Derived from live Plasma calldata and reproduced by\n * `zeroExRouteRules` in the test suite:\n *   @224 array pointer  = 256   (tail begins right after the head)\n *   @256 length         = 2     (approve + aggregator call)\n *   @288 elem[0] pointer= 64    (element table is 2 words)\n *   @320 elem[1] pointer= 288   (64 + elem[0] size: 4 words + a 68-byte approve)\n *   @352 calls[0].target        (the sell-token approve)\n *   @576 calls[1].target        (the aggregator)\n *\n * `calls[1].data` — the variable-length aggregator blob — is LAST in the\n * encoding, so its length shifts nothing that is pinned. That is what makes\n * these offsets stable across quotes rather than coincidental.\n */\nconst CALLS_POINTER_OFFSET = 224n;\nconst CALLS_LENGTH_OFFSET = 256n;\nconst CALLS_ELEM0_POINTER_OFFSET = 288n;\nconst CALLS_ELEM1_POINTER_OFFSET = 320n;\nconst CALLS_ELEM0_TARGET_OFFSET = 352n;\nconst CALLS_ELEM1_TARGET_OFFSET = 576n;\nconst CALLS_ELEM0_VALUE_OFFSET = 384n;\nconst CALLS_ELEM1_VALUE_OFFSET = 608n;\nconst NESTED_EXEC_TOKEN_OFFSET = 740n;\n/**\n * The nested fynd call: `swap(amountIn, tokenIn, tokenOut, minOut, receiver)`.\n * Verified against production calldata — the receiver is the Swapper itself,\n * which collects the output and forwards it to the scope's recipient, so that\n * is what gets pinned rather than the end recipient.\n */\nconst NESTED_FYND_TOKEN_IN_OFFSET = 740n;\nconst NESTED_FYND_TOKEN_OUT_OFFSET = 772n;\nconst NESTED_FYND_RECEIVER_OFFSET = 836n;\nconst CALLS_ELEM1_DATA_POINTER_OFFSET = 640n;\n/** Head words of the `AllowanceHolder.exec` nested in `calls[1].data`. */\nconst NESTED_EXEC_OPERATOR_OFFSET = 708n;\nconst NESTED_EXEC_TARGET_OFFSET = 804n;\nconst CALLS_ELEM1_DATA_POINTER = 96n;\nconst CALLS_ELEM0_DATA_POINTER_OFFSET = 416n;\nconst CALLS_ELEM0_DATA_LENGTH_OFFSET = 448n;\n/**\n * The word straddling `calls[0].data`'s selector and the high bytes of its\n * first argument. Pinning the spender alone leaves the selector free, so the\n * same word layout also satisfies `transfer(aggregator, amount)` — which sends\n * the pulled input to the aggregator instead of approving it, and with\n * `minAmountOut` free to be zero the Swapper does not object.\n */\nconst CALLS_ELEM0_DATA_HEAD_OFFSET = 480n;\nconst ERC20_APPROVE_SELECTOR = '095ea7b3';\n/** `approve` selector followed by the leading 28 bytes of the spender word. */\nfunction approveHeadWord(spender) {\n    return `0x${ERC20_APPROVE_SELECTOR}${'00'.repeat(12)}${spender\n        .slice(2, 34)\n        .toLowerCase()}`;\n}\n/** The `spender` argument of `calls[0]`'s `approve`, past its 4-byte selector. */\nconst CALLS_ELEM0_SPENDER_OFFSET = 484n;\nconst CALLS_ELEM0_DATA_POINTER = 96n;\n/** `approve(address,uint256)` — selector + two words. */\nconst APPROVE_CALLDATA_LENGTH = 68n;\nconst CALLS_POINTER = 256n;\nconst CALLS_LENGTH = 2n;\nconst CALLS_ELEM0_POINTER = 64n;\nconst CALLS_ELEM1_POINTER = 288n;\n/**\n * Pin the two-call `approve + aggregator` route inside the Swapper's `calls[]`.\n *\n * Without this the tail is unconstrained: the Swapper only requires that the\n * recipient nets `minAmountOut`, and `minAmountOut` may be zero, so a\n * compromised key could hand the pulled input to any address and satisfy the\n * contract. Constraining every call target to a real aggregator removes the\n * place those funds could go.\n *\n * Fails closed. A route that deviates from this shape — a different call count,\n * an added permit or approval reset — reverts rather than slipping through, so\n * the cost of the pin is availability, not safety.\n */\nfunction routeRules(sellToken, aggregator, settler, \n/** Set for the fynd route: pins the nested swap's tokens and receiver. */\nfyndNested) {\n    const nestedFynd = fyndNested\n        ? [\n            // Pinning calls[1].target to the Tycho router still leaves the swap it\n            // performs free to name any tokens and any receiver — so the output\n            // could land anywhere while the outer Swapper pins still hold.\n            pinValue(CALLS_ELEM1_DATA_POINTER_OFFSET, CALLS_ELEM1_DATA_POINTER),\n            pin(NESTED_FYND_TOKEN_IN_OFFSET, sellToken),\n            pin(NESTED_FYND_TOKEN_OUT_OFFSET, fyndNested.buyToken),\n            pin(NESTED_FYND_RECEIVER_OFFSET, fyndNested.swapper),\n        ]\n        : [];\n    const nested = settler\n        ? [\n            // Pinning calls[1]'s target to the AllowanceHolder still leaves the\n            // exec it forwards free to name any operator and target, which is where\n            // the pulled input would go. Pin those too when the Settler is known.\n            pinValue(CALLS_ELEM1_VALUE_OFFSET, 0n),\n            pinValue(CALLS_ELEM1_DATA_POINTER_OFFSET, CALLS_ELEM1_DATA_POINTER),\n            pin(NESTED_EXEC_OPERATOR_OFFSET, settler),\n            pin(NESTED_EXEC_TOKEN_OFFSET, sellToken),\n            pin(NESTED_EXEC_TARGET_OFFSET, settler),\n        ]\n        : [];\n    return [\n        ...nested,\n        ...nestedFynd,\n        pinValue(CALLS_POINTER_OFFSET, CALLS_POINTER),\n        pinValue(CALLS_LENGTH_OFFSET, CALLS_LENGTH),\n        pinValue(CALLS_ELEM0_POINTER_OFFSET, CALLS_ELEM0_POINTER),\n        pinValue(CALLS_ELEM1_POINTER_OFFSET, CALLS_ELEM1_POINTER),\n        pin(CALLS_ELEM0_TARGET_OFFSET, sellToken),\n        pin(CALLS_ELEM1_TARGET_OFFSET, aggregator),\n        // Pinning calls[0]'s target alone still lets it be any call to the sell\n        // token — `transfer(attacker, amountIn)` as easily as an approve. Fixing\n        // its length and the address it names leaves the aggregator as the only\n        // party the pulled input can reach.\n        pinValue(CALLS_ELEM0_VALUE_OFFSET, 0n),\n        pinValue(CALLS_ELEM0_DATA_POINTER_OFFSET, CALLS_ELEM0_DATA_POINTER),\n        pinValue(CALLS_ELEM0_DATA_LENGTH_OFFSET, APPROVE_CALLDATA_LENGTH),\n        pinWord(CALLS_ELEM0_DATA_HEAD_OFFSET, approveHeadWord(aggregator)),\n        pin(CALLS_ELEM0_SPENDER_OFFSET, aggregator),\n    ];\n}\n/**\n * Route swaps through the Rhinestone Swapper — the default, and the only venue\n * that matches what the orchestrator emits for same-chain smart-account swaps.\n *\n * Takes no addresses and no aggregator: which quoter fills the swap is the\n * orchestrator's decision, and this scoping holds whichever one wins.\n */\nexport function rhinestoneSwap(options = {}) {\n    return {\n        id: 'rhinestone',\n        ...(options.maxSpend !== undefined ? { maxSpend: options.maxSpend } : {}),\n    };\n}\nexport function scopeRhinestone(venue, ctx) {\n    const { swapper, proxy } = swapperAddresses(ctx.environment);\n    if (venue.route === 'zeroEx' && !ZEROX_CHAIN_IDS.includes(ctx.chainId)) {\n        throw new Error(`0x is not available on chain ${ctx.chainId}. ` +\n            `Supported: ${ZEROX_CHAIN_IDS.join(', ')}.`);\n    }\n    if (venue.route === 'fynd' && !FYND_CHAIN_IDS.includes(ctx.chainId)) {\n        throw new Error(`fynd is not available on chain ${ctx.chainId}. ` +\n            `Supported: ${FYND_CHAIN_IDS.join(', ')}.`);\n    }\n    // An empty list authorises nothing, the same as `swap.via: []`, and it is\n    // worse than useless here: with several sell tokens the tokenIn pin has\n    // already moved out of the shared rules and into the branches, so an empty\n    // cross product leaves the sell token UNPINNED and the session able to sell\n    // anything the proxy is approved for.\n    if (venue.routes !== undefined && venue.routes.length === 0) {\n        throw new Error('rhinestoneSwap routes must list at least one aggregator — an empty ' +\n            'list would authorise nothing. Omit `routes` to leave the tail open.');\n    }\n    const multiSell = sellPinsGoInAlternatives(ctx);\n    /** Route pins for one (sell token, aggregator) pair. */\n    const routeRulesFor = (sellToken, route) => routeRules(sellToken, route === 'zeroEx'\n        ? ZEROX_ALLOWANCE_HOLDER\n        : FYND_ROUTERS[ctx.chainId], route === 'zeroEx' ? venue.settler : undefined, route === 'fynd' ? { buyToken: ctx.buyToken, swapper } : undefined);\n    const rulesFor = (offsets, sellAmountParam) => {\n        const rules = [\n            // With one token the pin stays here, which is what keeps the rule order,\n            // the chosen policy type and the digest identical to what callers have\n            // already signed. With several it moves into the OR below, because the\n            // wrapped route mentions the sell token at more than one offset and a\n            // branch has to agree with itself.\n            ...(multiSell ? [] : [pin(offsets.tokenIn, ctx.sellTokens[0])]),\n            pin(offsets.tokenOut, ctx.buyToken),\n            pin(offsets.recipient, ctx.recipient),\n        ];\n        if (ctx.cap !== undefined) {\n            rules.push(cumulativeCap(offsets[sellAmountParam], ctx.cap));\n        }\n        // Narrowed on `venue.route` itself rather than on `routeAggregator`, so\n        // the type follows the check instead of being asserted past it.\n        if (!multiSell && venue.routes === undefined && venue.route !== undefined) {\n            rules.push(...routeRulesFor(ctx.sellTokens[0], venue.route));\n        }\n        return rules;\n    };\n    /**\n     * The OR branches. Each must be self-consistent: every offset that names the\n     * sell token has to name the SAME one, so a branch is a (token, route) pair\n     * rather than a token pin and a route pin chosen independently.\n     *\n     * Single token, several routes -> today's per-route alternatives, unchanged.\n     * Several tokens -> the cross product, which is what lets one session serve\n     * an account that may receive any of a set of tokens.\n     */\n    const alternativesFor = (offsets) => {\n        const routes = venue.routes !== undefined\n            ? [...venue.routes]\n            : [venue.route === undefined ? undefined : venue.route];\n        if (!multiSell) {\n            // Unchanged: no branches at all unless several routes were named.\n            return venue.routes === undefined\n                ? []\n                : routes.flatMap((route) => route === undefined\n                    ? []\n                    : [routeRulesFor(ctx.sellTokens[0], route)]);\n        }\n        return ctx.sellTokens.flatMap((token) => routes.map((route) => [\n            pin(offsets.tokenIn, token),\n            ...(route === undefined ? [] : routeRulesFor(token, route)),\n        ]));\n    };\n    // The invariant behind moving the pin: whenever it leaves the shared rules,\n    // the branches must put it back. Checked rather than assumed — an empty\n    // alternatives list silently unpins the sell token, and the resulting scope\n    // looks well-formed.\n    const assertSellTokenPinned = (alternatives) => {\n        if (multiSell && alternatives.length === 0) {\n            throw new Error('internal: several sell tokens but no alternatives to pin them in — ' +\n                'the sell token would be unconstrained');\n        }\n        return alternatives;\n    };\n    return {\n        // The account approves the proxy, never the Swapper and never a router —\n        // one fixed spender per chain, whichever aggregator ends up filling.\n        approveSpenders: [proxy],\n        actions: [\n            swapAction(swapper, SWAP_EXACT_IN_SELECTOR, rulesFor(EXACT_IN, 'amountIn'), assertSellTokenPinned(alternativesFor(EXACT_IN))),\n            swapAction(swapper, SWAP_EXACT_OUT_SELECTOR, rulesFor(EXACT_OUT, 'amountInMax'), assertSellTokenPinned(alternativesFor(EXACT_OUT))),\n        ],\n    };\n}\n","import { toFunctionSelector } from 'viem';\nimport { namedParamOffsets } from '../../permissions.js';\nimport { cumulativeCap, pin, pinValue, sellPinsGoInAlternatives, swapAction, } from './rules.js';\n/**\n * 0x — Swap API v2, AllowanceHolder flow.\n *\n * Two calls per swap:\n *   1. `approve(AllowanceHolder, amount)` on the sell token\n *   2. `AllowanceHolder.exec(operator, token, amount, target, data)` — pulls the\n *      approved sell token and forwards `data` to the Settler.\n *\n * The split matters for scoping. `token` and `amount` are consumed by the\n * AllowanceHolder itself, so pinning them is meaningful no matter what `target`\n * is. `operator` and `target` decide who receives the pulled funds, and nothing\n * on-chain requires them to be a Settler — leave them free and a compromised\n * session key names its own contract.\n */\n/** Permanent across chains — 0x never rotates this. Verified deployed on Plasma. */\nexport const ZEROX_ALLOWANCE_HOLDER = '0x0000000000001fF3684f28c67538d4D072C22734';\n/** Chains where 0x is an enabled quoter with a whitelisted Settler. */\nexport const ZEROX_CHAIN_IDS = [\n    1, 10, 56, 130, 137, 143, 146, 999, 4663, 8453, 9745, 42161, 43114, 57073,\n];\nexport const allowanceHolderAbi = [\n    {\n        type: 'function',\n        name: 'exec',\n        stateMutability: 'payable',\n        inputs: [\n            { name: 'operator', type: 'address' },\n            { name: 'token', type: 'address' },\n            { name: 'amount', type: 'uint256' },\n            { name: 'target', type: 'address' },\n            { name: 'data', type: 'bytes' },\n        ],\n        outputs: [{ name: 'result', type: 'bytes' }],\n    },\n];\nexport const ALLOWANCE_HOLDER_EXEC_SELECTOR = toFunctionSelector(allowanceHolderAbi[0]);\n/** exec's own head offsets, derived from the ABI. */\nconst EXEC = namedParamOffsets(allowanceHolderAbi, 'exec');\n/**\n * Offsets of the Settler's slippage fields, measured in EXEC's calldata.\n *\n * These cannot come from an ABI: they live inside `exec.data`, which is opaque\n * `bytes` as far as exec's own signature is concerned. They are stable anyway\n * because the Settler's\n * `execute((recipient, buyToken, minAmountOut) slippage, bytes[] actions, bytes32)`\n * places the fixed-size slippage struct BEFORE the variable-length `actions`.\n *\n * Derivation: exec's `data` content begins at 192 (five head words + the length\n * word), +4 for the inner selector = 196 for `recipient`, +32 = 228 for\n * `buyToken`. Re-derive against a live 0x exec if 0x revs the Settler ABI.\n */\n/**\n * `exec`'s `data` head word, and the canonical tail it must point at.\n *\n * The Settler offsets below are derived from `data` starting at 192, which only\n * holds while this pointer says 160. Unpinned, a session key can aim `data`\n * elsewhere and leave matching decoy words at 196/228 for the policy to read\n * while the Settler decodes a different recipient. `rhinestone.ts` pins the\n * equivalent `calls[]` shape words for the same reason.\n */\nconst EXEC_DATA_POINTER_OFFSET = 128n;\nconst EXEC_DATA_POINTER = 160n;\nconst SETTLER_RECIPIENT_OFFSET = 196n;\nconst SETTLER_BUY_TOKEN_OFFSET = 228n;\n/**\n * 0x's Settler registry — an ERC-721 whose token owner IS the current Settler\n * for that feature slot. Slot 2 is the taker-submitted Settler used by ordinary\n * swaps.\n *\n * 0x redeploys the Settler every few weeks and moves the token, so there is no\n * safe constant to bundle: any address baked into a release is correct only\n * until the next rotation. Resolve with {@link resolveZeroExSettler} and pin the\n * result, or use `anySettler` to trade the pin for longevity.\n */\nexport const ZEROX_SETTLER_REGISTRY = '0x00000000000004533Fe15556B1E086BB1A72cEae';\nexport const ZEROX_SETTLER_FEATURE_ID = 2n;\nexport const zeroExSettlerRegistryAbi = [\n    {\n        type: 'function',\n        name: 'ownerOf',\n        stateMutability: 'view',\n        inputs: [{ name: 'tokenId', type: 'uint256' }],\n        outputs: [{ name: '', type: 'address' }],\n    },\n];\n/**\n * Read 0x's current Settler for this chain from the on-chain registry.\n *\n * Pin the result at session-enable time; do NOT re-resolve per swap. A session\n * that looked the address up at use time would follow 0x's registry wherever it\n * points, so a compromise of 0x's upgrade multisig could redirect every live\n * session's approved funds. Pinned, the worst case of a rotation is that the\n * session stops working until it is re-enabled.\n *\n * @param client - Any viem public client for the target chain.\n */\nexport async function resolveZeroExSettler(client) {\n    return client.readContract({\n        address: ZEROX_SETTLER_REGISTRY,\n        abi: zeroExSettlerRegistryAbi,\n        functionName: 'ownerOf',\n        args: [ZEROX_SETTLER_FEATURE_ID],\n    });\n}\n/**\n * Scope a session to 0x swaps, in whichever shape the orchestrator produces.\n *\n * Authorises BOTH the direct `AllowanceHolder.exec` call and the\n * Swapper-wrapped one, and there is no way to narrow that. Whether a swap is\n * wrapped is decided by `ENABLE_SWAPPER`, the account type, and whether the\n * Swapper resolves on the chain — state that is read when the intent executes,\n * not when the session is signed. Authorising one shape is how a session ends\n * up rejecting the swap it was created for.\n *\n * Takes either a pinned `settler` or `anySettler` + `maxSpend`. There is\n * deliberately no zero-argument form: a bundled Settler constant would be stale\n * within weeks of the release that shipped it.\n */\nexport function zeroEx(options) {\n    return {\n        id: '0x',\n        ...(options.settler !== undefined ? { settler: options.settler } : {}),\n        ...(options.anySettler ? { anySettler: true } : {}),\n        ...(options.maxSpend !== undefined ? { maxSpend: options.maxSpend } : {}),\n    };\n}\nexport function scopeZeroEx(venue, ctx) {\n    // The union type rejects this at compile time, but a plain-JS caller or an\n    // `as any` reaches here with neither, and the rules below would then pin only\n    // the sell token — an unbounded AllowanceHolder path.\n    if (venue.settler === undefined && !venue.anySettler) {\n        throw new Error('zeroEx() requires either a pinned settler or anySettler + maxSpend: ' +\n            'with neither, nothing bounds the operator, target or amount');\n    }\n    if (venue.anySettler && ctx.cap === undefined) {\n        throw new Error('zeroEx({ anySettler: true }) requires maxSpend: with the Settler ' +\n            'unpinned it is the only bound on what a compromised session key can pull');\n    }\n    // Pinned from the scope, never from venue options — the sell token is a\n    // scope-level guarantee and must not depend on the caller restating it.\n    const multiSell = sellPinsGoInAlternatives(ctx);\n    const rules = [\n        // One token keeps its pin here, preserving the historical digest.\n        ...(multiSell ? [] : [pin(EXEC.token, ctx.sellTokens[0])]),\n    ];\n    if (venue.settler !== undefined) {\n        rules.push(pin(EXEC.operator, venue.settler));\n        rules.push(pin(EXEC.target, venue.settler));\n        // Before any offset inside `exec.data` can be trusted.\n        rules.push(pinValue(EXEC_DATA_POINTER_OFFSET, EXEC_DATA_POINTER));\n        rules.push(pin(SETTLER_BUY_TOKEN_OFFSET, ctx.buyToken));\n        rules.push(pin(SETTLER_RECIPIENT_OFFSET, ctx.recipient));\n    }\n    if (ctx.cap !== undefined) {\n        rules.push(cumulativeCap(EXEC.amount, ctx.cap));\n    }\n    const sellAlternatives = multiSell\n        ? ctx.sellTokens.map((token) => [pin(EXEC.token, token)])\n        : [];\n    return {\n        approveSpenders: [ZEROX_ALLOWANCE_HOLDER],\n        actions: [\n            swapAction(ZEROX_ALLOWANCE_HOLDER, ALLOWANCE_HOLDER_EXEC_SELECTOR, rules, sellAlternatives),\n        ],\n    };\n}\n","import { scopeFynd } from './fynd.js';\nimport { rhinestoneSwap, scopeRhinestone } from './rhinestone.js';\nimport { scopeZeroEx } from './zero-ex.js';\nconst erc20ApproveAbi = [\n    {\n        type: 'function',\n        name: 'approve',\n        stateMutability: 'nonpayable',\n        inputs: [\n            { name: 'spender', type: 'address' },\n            { name: 'amount', type: 'uint256' },\n        ],\n        outputs: [{ name: '', type: 'bool' }],\n    },\n];\n/**\n * The approve permission for ONE sell token, covering every venue's spender.\n *\n * One per token, not one per venue: every venue pulls the same token, so a\n * single action with a spender allowlist is cheaper to install and keeps the\n * spending limit a shared counter rather than a budget per venue. Several sell\n * tokens mean several of these — the permission's `address` IS the token, so it\n * cannot be merged further.\n */\nfunction approvePermission(sellToken, maxTotal, scopings) {\n    const spenders = [\n        ...new Set(scopings.flatMap((s) => s.approveSpenders.map((a) => a.toLowerCase()))),\n    ].map((s) => s);\n    return {\n        abi: erc20ApproveAbi,\n        address: sellToken,\n        functions: {\n            approve: {\n                ...(maxTotal !== undefined\n                    ? {\n                        spendingLimit: {\n                            token: sellToken,\n                            amount: maxTotal,\n                        },\n                    }\n                    : {}),\n                params: {\n                    spender: spenders.length === 1\n                        ? { condition: 'equal', value: spenders[0] }\n                        : { anyOf: spenders },\n                },\n            },\n        },\n    };\n}\n/**\n * Compile a `swap` scope into one merged approve permission plus one scoped\n * action per venue.\n */\nexport function resolveSwapScope(scope, chainId, environment = 'production') {\n    // Default to the Swapper: it is the route the orchestrator emits for\n    // same-chain smart-account swaps, so a caller who just says \"let this key\n    // swap A for B\" gets a scope that actually matches the resulting ops.\n    const via = scope.via ?? [rhinestoneSwap()];\n    if (via.length === 0) {\n        throw new Error('swap.via must list at least one venue — an empty list would authorise nothing');\n    }\n    // One shape from here down. `token` and `tokens` are the same thing to\n    // everything downstream except rule placement, which `sellPinsGoInAlternatives`\n    // decides from the length.\n    //\n    // Both present is refused rather than resolved. The type makes it impossible\n    // for a TypeScript caller, but a deserialized scope can carry both, and\n    // preferring either one silently widens or narrows what the session may\n    // spend. Neither present is refused for the same reason: it would otherwise\n    // reach the checks below as `[undefined]`.\n    const { token, tokens } = scope.sell;\n    if (token !== undefined && tokens !== undefined) {\n        throw new Error('swap.sell names both token and tokens — they are mutually exclusive, so ' +\n            'which tokens the session may spend is ambiguous. Pass one.');\n    }\n    if (token === undefined && tokens === undefined) {\n        throw new Error('swap.sell must name a token or a non-empty tokens list');\n    }\n    const sellTokens = tokens ?? [token];\n    if (sellTokens.length === 0) {\n        throw new Error('swap.sell.tokens must name at least one token — an empty list would authorise nothing');\n    }\n    const duplicate = sellTokens\n        .map((t) => t.toLowerCase())\n        .find((t, i, all) => all.indexOf(t) !== i);\n    if (duplicate) {\n        throw new Error(`swap.sell.tokens repeats ${duplicate}`);\n    }\n    const sameAsBuy = sellTokens.find((t) => t.toLowerCase() === scope.buy.token.toLowerCase());\n    if (sameAsBuy) {\n        throw new Error(`swap.sell and swap.buy.token are the same address (${sameAsBuy})`);\n    }\n    const ctxFor = (venue) => ({\n        chainId,\n        environment,\n        sellTokens,\n        buyToken: scope.buy.token,\n        recipient: scope.to,\n        // A venue-level cap wins over the scope-level one: `anySettler` demands its\n        // own `maxSpend` precisely because that venue needs a tighter bound than the\n        // session as a whole might carry.\n        cap: venue.maxSpend ?? scope.sell.maxTotal,\n    });\n    // Every aggregator venue is reachable two ways and the orchestrator picks:\n    // it wraps a route in the Swapper only when the Swapper can capture surplus,\n    // which depends on the direction AND the winning quoter, and that eligibility\n    // is orchestrator-side config that changes without the session knowing. So\n    // each venue authorises its direct call AND the wrapped one; authorising a\n    // single shape is how a session rejects the swap it was created for.\n    //\n    // The wrapped shape pins which aggregator may sit in the Swapper's `calls[]`.\n    // Two venues pinning DIFFERENT aggregators cannot share one Swapper action —\n    // so with more than one aggregator authorised the tail is left unpinned,\n    // which is the honest reading: either aggregator may fill it. The swap stays\n    // bound by the Swapper's own top-level tokenIn/tokenOut/recipient pins and\n    // the sell cap either way.\n    const routes = new Set(via.flatMap((venue) => venue.id === 'fynd'\n        ? ['fynd']\n        : venue.id === '0x'\n            ? ['zeroEx']\n            : []));\n    // A bare `rhinestoneSwap()` authorises any aggregator in the tail, so pinning\n    // it for the others would both contradict that venue and collide with it on\n    // the same Swapper action.\n    // A caller-written Swapper venue carries no route by construction — the\n    // routed shape is internal — so naming one authorises any aggregator.\n    const anyAggregatorAllowed = via.some((venue) => venue.id === 'rhinestone');\n    const sharedRoute = routes.size === 1 && !anyAggregatorAllowed ? [...routes][0] : undefined;\n    // More than one aggregator authorised: pin the tail to ANY ONE of them rather\n    // than to none. Sharing the Swapper action by dropping its route pins would\n    // authorise a tail neither venue named, which is broader than the scope.\n    const sharedRoutes = routes.size > 1 && !anyAggregatorAllowed ? [...routes] : undefined;\n    // The Settler the 0x venue already carries, so the wrapped half can pin the\n    // nested exec instead of dropping the one address that makes it bindable.\n    const zeroExSettler = via.flatMap((venue) => venue.id === '0x' && venue.settler !== undefined ? [venue.settler] : [])[0];\n    const wrappedVenue = () => {\n        const settler = zeroExSettler !== undefined ? { settler: zeroExSettler } : {};\n        if (sharedRoutes)\n            return { id: 'rhinestone', routes: sharedRoutes, ...settler };\n        if (sharedRoute) {\n            return {\n                id: 'rhinestone',\n                route: sharedRoute,\n                ...(sharedRoute === 'zeroEx' ? settler : {}),\n            };\n        }\n        return { id: 'rhinestone' };\n    };\n    const scopings = via.map((venue) => {\n        const ctx = ctxFor(venue);\n        if (venue.id === 'rhinestone')\n            return scopeRhinestone(venue, ctx);\n        const parts = [\n            venue.id === 'fynd' ? scopeFynd(ctx) : scopeZeroEx(venue, ctx),\n            scopeRhinestone(wrappedVenue(), ctx),\n        ];\n        return {\n            approveSpenders: parts.flatMap((p) => [...p.approveSpenders]),\n            actions: parts.flatMap((p) => [...p.actions]),\n        };\n    });\n    return {\n        // One permission per sell token: distinct addresses are distinct on-chain\n        // action ids, so they carry their own policies without conflicting. A single\n        // merged permission cannot express two tokens — its `address` IS the token.\n        permissions: sellTokens.map((token) => approvePermission(token, scope.sell.maxTotal, scopings)),\n        actions: dedupeActions(scopings.flatMap((s) => [...s.actions])),\n    };\n}\n/**\n * Collapse actions that different venues both authorise.\n *\n * Every aggregator venue covers the Swapper-wrapped shape as well as its direct\n * one, so listing two of them yields the same (target, selector) twice. Those map to one on-chain action id, and the resolver rejects\n * duplicates — reasonably, since two entries would silently overwrite each\n * other's policies. Identical entries are safe to collapse; genuinely\n * conflicting ones still throw, because picking a winner would silently\n * loosen or tighten a rule the caller wrote.\n */\nfunction dedupeActions(actions) {\n    const byKey = new Map();\n    for (const action of actions) {\n        const key = `${action.target.toLowerCase()}|${action.selector.toLowerCase()}`;\n        const existing = byKey.get(key);\n        if (!existing) {\n            byKey.set(key, action);\n            continue;\n        }\n        if (JSON.stringify(existing, replaceBigInt) !==\n            JSON.stringify(action, replaceBigInt)) {\n            throw new Error(`Conflicting swap actions for ${action.target} ${action.selector}: ` +\n                'two venues authorise the same call with different policies. Give ' +\n                'them the same cap, or list only one.');\n        }\n    }\n    return [...byKey.values()];\n}\nfunction replaceBigInt(_key, value) {\n    return typeof value === 'bigint' ? value.toString() : value;\n}\n","import { isHyperCoreWireId } from '../../chains/caip2.js';\nimport { buildSmartSessionMockSignature } from '../../modules/validators/smart-sessions/mock-signature.js';\nimport { DUMMY_PRECLAIMOP_SELECTOR, DUMMY_PRECLAIMOP_TARGET, } from '../../modules/validators/smart-sessions/resolve.js';\nexport async function prepareIntentSessions(input) {\n    const selection = input.intent.signers;\n    if (!selection || selection.kind !== 'smart-session')\n        return undefined;\n    const chains = sessionChains(input.intent);\n    const resolvedEntries = await Promise.all(chains.map(async (chain) => {\n        const selected = selection.byChain[chain.id];\n        if (!selected) {\n            throw new Error(`No session configured for chain ${chain.id}`);\n        }\n        const checkpointId = `intent-session:${chain.id}:${selected.session.permissionId}`;\n        const facts = await input.context.checkpoints.read({\n            kind: 'session-enabled',\n            id: checkpointId,\n            chain,\n            account: input.runtime.identity.address,\n            permissionId: selected.session.permissionId,\n        });\n        const enabled = facts.find((fact) => fact.kind === 'session-enabled' && fact.id === checkpointId);\n        if (enabled?.kind !== 'session-enabled') {\n            throw new Error(`Session state for chain ${chain.id} is missing`);\n        }\n        const verifyExecutions = !enabled.enabled || selected.session.hasExplicitPermissions;\n        return [\n            chain.id,\n            {\n                kind: 'smart-session',\n                session: selected.session,\n                ...(enabled.enabled || !selected.enableData\n                    ? {}\n                    : { enableData: selected.enableData }),\n                verifyExecutions,\n            },\n        ];\n    }));\n    const byChain = Object.fromEntries(resolvedEntries);\n    const mockSignatures = Object.fromEntries(resolvedEntries.map(([chainId, resolved]) => [\n        String(chainId),\n        buildSmartSessionMockSignature({\n            session: resolved.session,\n            environment: input.runtime.construction.sessions.environment,\n            chainCount: input.intent.sourceChains?.length ?? 1,\n            targetChainId: chainId,\n            shape: !resolved.verifyExecutions\n                ? 'erc1271'\n                : resolved.enableData\n                    ? 'enable'\n                    : 'use',\n        }),\n    ]));\n    const preClaimCalls = Object.fromEntries((input.intent.sourceChains ?? []).flatMap((chain) => {\n        const resolved = byChain[chain.id];\n        return resolved?.verifyExecutions && resolved.enableData\n            ? [\n                [\n                    chain.id,\n                    [\n                        {\n                            target: DUMMY_PRECLAIMOP_TARGET,\n                            value: 0n,\n                            data: DUMMY_PRECLAIMOP_SELECTOR,\n                        },\n                    ],\n                ],\n            ]\n            : [];\n    }));\n    return {\n        signatureMode: resolvedEntries.some(([, value]) => value.verifyExecutions)\n            ? 5\n            : 1,\n        byChain,\n        mockSignatures,\n        preClaimCalls,\n    };\n}\n// Chains a smart-session intent needs an enabled session on: every source, plus\n// the destination when the user's own account executes there.\n//\n// A HyperCore venue is excluded for the same reason it cannot host the account\n// runtime: it is EVM-ADDRESSED but virtual, so there is no account there to enable\n// a session on, and requiring one would demand a session on chain 1337001/1337002\n// that can never exist. Delivery is solver-mediated anyway — the orchestrator\n// builds the `depositFor` credit and the recipient never executes — so there is no\n// destination-side authorization for a session to grant (RHI-5510).\nfunction sessionChains(intent) {\n    const chains = new Map((intent.sourceChains ?? []).map((chain) => [chain.id, chain]));\n    if (intent.destination.kind === 'evm' &&\n        !isHyperCoreWireId(intent.destination.id)) {\n        chains.set(intent.destination.id, intent.destination);\n    }\n    return [...chains.values()];\n}\n","export function toPublicTransactionStatus(status) {\n    return {\n        traceId: status.traceId,\n        purpose: status.purpose,\n        status: status.status,\n        ...(status.accounts ? { accounts: [...status.accounts] } : {}),\n        operations: [...status.operations],\n        ...(status.refunds ? { refunds: [...status.refunds] } : {}),\n        ...(status.details ? { details: status.details } : {}),\n    };\n}\nexport function toOrchestratorSplitRequest(input) {\n    return {\n        chainId: input.chain.id,\n        tokens: input.tokens,\n        ...(input.settlementLayers\n            ? { settlementLayers: input.settlementLayers }\n            : {}),\n    };\n}\nexport function toPublicSplitResult(result) {\n    return {\n        traceId: result.traceId,\n        intents: result.intents.map((intent) => ({ ...intent })),\n    };\n}\n","import { SignerNotSupportedError } from '../errors/execution.js';\nimport { defineValidator } from '../modules/validators/definition.js';\nimport { ecdsaSignerId, webauthnSignerId, } from '../modules/validators/signer-id.js';\nimport { SOCIAL_RECOVERY_VALIDATOR_ADDRESS } from '../modules/validators/social-recovery.js';\n/**\n * Adapts a signer selection for the intent and ERC-1271 flows.\n *\n * Rejects guardians: the social recovery validator reverts on\n * `isValidSignatureWithSender` and only validates UserOperations, so a\n * guardian signature could never be verified on these paths. Use\n * {@link adaptUserOperationSignerSelection} for the UserOperation flow.\n */\nexport function adaptSignerSelection(account, signers) {\n    if (signers.type === 'guardians') {\n        throw new SignerNotSupportedError();\n    }\n    return adaptAnySignerSelection(account, signers);\n}\n/**\n * Adapts a signer selection for the UserOperation flow, where guardians are\n * the one supported non-owner signer.\n */\nexport function adaptUserOperationSignerSelection(account, signers) {\n    return adaptAnySignerSelection(account, signers);\n}\nfunction adaptAnySignerSelection(account, signers) {\n    if (signers.type === 'session') {\n        return adaptSessionSelection(signers);\n    }\n    if (signers.type === 'guardians') {\n        return adaptGuardianSelection(signers);\n    }\n    return adaptOwnerSelection(account, signers);\n}\n/**\n * Adapts a guardian selection onto the social recovery validator.\n *\n * The module shares the ownable validator's threshold-ECDSA shape, so it\n * resolves as an ECDSA validator pinned to the recovery module address. The\n * threshold is the number of supplied guardians: the validator reads exactly\n * `threshold` signatures onchain and sorts the recovered signers itself, so\n * every guardian passed here must sign and their order is irrelevant.\n */\nfunction adaptGuardianSelection(signers) {\n    if (signers.guardians.length === 0) {\n        throw new Error('Guardian signer selection requires at least one guardian');\n    }\n    return {\n        kind: 'owner',\n        validator: defineValidator({\n            type: 'ecdsa',\n            accounts: signers.guardians,\n            threshold: signers.guardians.length,\n            module: SOCIAL_RECOVERY_VALIDATOR_ADDRESS,\n        }, 'recovery-validator'),\n        signerIds: signers.guardians.map(ecdsaSignerId),\n    };\n}\nfunction adaptOwnerSelection(account, signers) {\n    switch (signers.kind) {\n        case 'ecdsa': {\n            const signerIds = signers.accounts.map(ecdsaSignerId);\n            return {\n                kind: 'owner',\n                validator: account.owners\n                    ? replaceValidatorAccounts(account.owners, signers.accounts)\n                    : defineValidator({ type: 'ecdsa', accounts: signers.accounts }),\n                signerIds,\n            };\n        }\n        case 'quorum': {\n            const signerIds = signers.accounts.map(ecdsaSignerId);\n            if (!account.owners || account.owners.kind !== 'quorum') {\n                throw new Error('Quorum signer selection requires configured quorum owners');\n            }\n            return {\n                kind: 'owner',\n                validator: replaceValidatorAccounts(account.owners, signers.accounts),\n                signerIds,\n            };\n        }\n        case 'passkey': {\n            const signerIds = signers.accounts.map(webauthnSignerId);\n            return {\n                kind: 'owner',\n                validator: defineValidator({\n                    type: 'passkey',\n                    accounts: signers.accounts,\n                    ...(signers.module ? { module: signers.module } : {}),\n                }),\n                signerIds,\n            };\n        }\n        case 'multi-factor': {\n            const validator = defineValidator({\n                type: 'multi-factor',\n                validators: signers.validators.map((factor) => factor.type === 'passkey'\n                    ? { type: 'passkey', accounts: factor.accounts }\n                    : { type: 'ecdsa', accounts: factor.accounts }),\n                ...(signers.module ? { module: signers.module } : {}),\n            });\n            if (validator.kind !== 'multi-factor') {\n                throw new Error('Multi-factor signer selection did not resolve');\n            }\n            return {\n                kind: 'owner',\n                validator: {\n                    ...validator,\n                    validators: validator.validators.map((factor, index) => ({\n                        ...factor,\n                        publicId: signers.validators[index]?.id ?? factor.publicId,\n                    })),\n                },\n                signerIds: signers.validators.flatMap((factor) => factor.type === 'passkey'\n                    ? factor.accounts.map(webauthnSignerId)\n                    : factor.accounts.map(ecdsaSignerId)),\n            };\n        }\n    }\n}\nfunction replaceValidatorAccounts(configured, selectedAccounts) {\n    const accounts = new Map(selectedAccounts.map((account) => [\n        account.type === 'webAuthn'\n            ? webauthnSignerId(account)\n            : ecdsaSignerId(account),\n        account,\n    ]));\n    if (configured.kind === 'multi-factor') {\n        return {\n            ...configured,\n            validators: configured.validators.map((validator) => replaceAtomicValidatorAccounts(validator, accounts)),\n        };\n    }\n    return replaceAtomicValidatorAccounts(configured, accounts);\n}\nfunction replaceAtomicValidatorAccounts(configured, accounts) {\n    return {\n        ...configured,\n        owners: configured.owners.map((owner) => replaceOwnerAccount(owner, accounts.get(owner.signerId))),\n    };\n}\nfunction replaceOwnerAccount(owner, account) {\n    if (!account)\n        return owner;\n    return owner.kind === 'webauthn' && account.type === 'webAuthn'\n        ? { ...owner, account }\n        : owner.kind !== 'webauthn' && account.type !== 'webAuthn'\n            ? { ...owner, account }\n            : owner;\n}\nfunction adaptSessionSelection(signers) {\n    if ('sessions' in signers) {\n        return {\n            kind: 'smart-session',\n            byChain: Object.fromEntries(Object.entries(signers.sessions).map(([chainId, selection]) => [\n                Number(chainId),\n                selection,\n            ])),\n        };\n    }\n    return {\n        kind: 'smart-session',\n        byChain: {\n            [signers.session.chain.id]: {\n                session: signers.session,\n                ...(signers.enableData ? { enableData: signers.enableData } : {}),\n            },\n        },\n    };\n}\n","import { isAddressEqual, } from 'viem';\nimport { createAccountConstruction } from '../accounts/construction.js';\nimport { FactoryArgsNotAvailableError } from '../accounts/error.js';\nimport { createAccountAdapter } from '../accounts/registry.js';\nimport { resolveCalls } from '../calls/resolve.js';\nimport { chainIdFromCaip2, formatCaip2, toEvmChainReference, } from '../chains/caip2.js';\nimport { getChainById } from '../chains/catalog.js';\nimport { createBundlerClient } from '../clients/bundler/client.js';\nimport { createConfiguredOrchestratorClient } from '../clients/orchestrator/client.js';\nimport { createPaymasterClient } from '../clients/paymaster/client.js';\nimport { createRpcPort } from '../clients/rpc/client.js';\nimport { accountMaterial, createStaticAccountRuntime, } from '../config/account-runtime.js';\nimport { UnsupportedAccountCapabilityError } from '../errors/capability.js';\nimport { getIntentExecutorModule } from '../modules/intent-executor.js';\nimport { readInstalledModules, readModuleInstallations, readOwners, } from '../modules/read-core.js';\nimport { defineValidator } from '../modules/validators/definition.js';\nimport { K1_DEFAULT_VALIDATOR_ADDRESS } from '../modules/validators/k1.js';\nimport { resolveValidator } from '../modules/validators/resolve.js';\nimport { ecdsaSignerId } from '../modules/validators/signer-id.js';\nimport { getSessionDetails as buildSessionDetails, SESSION_LOCK_TAG, } from '../modules/validators/smart-sessions/authorization.js';\nimport { getSmartSessionEmissaryAddress } from '../modules/validators/smart-sessions/module.js';\nimport { readSessionEnabled, readSessionNonce, } from '../modules/validators/smart-sessions/state.js';\nimport { createAccountSigningContext, getAccountSignatureRoute, getSigningValidatorCodec, getSigningValidatorFactors, } from '../signing/context.js';\nimport { createNexusEip7702InitTypedData, signAuthorizationList, signNexusEip7702Init, signRequestedDelegations as signRequestedDelegationList, } from '../signing/eip7702.js';\nimport { createValidatorSigningTasks, signingTopology } from '../signing/plan.js';\nimport { resolveSessionEnableChain, signSessionEnablement, } from '../signing/session-enable.js';\nimport { createSignerInvocationPort } from '../signing/signers/registry.js';\nimport { resolveAccountTypedDataSigning } from '../signing/typed-data.js';\nimport { projectIntentAccount } from '../transactions/intents/account.js';\nimport { accountChainIdFromOrigins } from '../transactions/intents/origin-chain.js';\nimport { buildIntentSigningInput, prepareIntent, } from '../transactions/intents/prepare.js';\nimport { requestSetId } from '../transactions/intents/proofs.js';\nimport { sendIntent } from '../transactions/intents/send.js';\nimport { prepareIntentSessions } from '../transactions/intents/sessions.js';\nimport { assembleIntent, signIntent, signIntentAsOwner, } from '../transactions/intents/sign-transaction.js';\nimport { prepareSolanaIntent, reconstructSolanaIntent, signSolanaIntent, submitSolanaIntent, } from '../transactions/intents/solana.js';\nimport { prepareSolanaDeployment, submitSolanaDeployment, } from '../transactions/intents/solana-deployment.js';\nimport { splitIntents } from '../transactions/intents/split.js';\nimport { getIntentStatus, waitForIntentStatus, } from '../transactions/intents/status.js';\nimport { submitIntent } from '../transactions/intents/submit.js';\nimport { prepareUserOperation } from '../transactions/user-operations/prepare.js';\nimport { reconstructPreparedUserOperation, reconstructSignedUserOperation, } from '../transactions/user-operations/reconstruct.js';\nimport { sendUserOperation } from '../transactions/user-operations/send.js';\nimport { signUserOperation } from '../transactions/user-operations/sign.js';\nimport { getUserOperationStatus, waitForUserOperationStatus, } from '../transactions/user-operations/status.js';\nimport { submitUserOperation } from '../transactions/user-operations/submit.js';\nimport { signRuntimeMessage, signRuntimeTypedData } from './direct-signing.js';\nimport { getAppFeeBalances } from './queries/app-fees.js';\nimport { getPortfolio } from './queries/portfolio.js';\nimport { createSession } from './queries/session.js';\nconst sessionEnabledAbi = [\n    {\n        type: 'function',\n        name: 'isPermissionEnabled',\n        stateMutability: 'view',\n        inputs: [\n            { name: 'account', type: 'address' },\n            { name: 'permissionId', type: 'bytes32' },\n        ],\n        outputs: [{ name: 'enabled', type: 'bool' }],\n    },\n];\nexport function createCoreComposition(config, dependencies, resolveAccountDependencies = () => dependencies) {\n    const project = {\n        getIntentStatus: (intentId, options) => getIntentStatus({ statusClient: dependencies.orchestrator }, intentId, options),\n        splitIntents: (input) => splitIntents(dependencies.orchestrator, input),\n        getAppFeeBalances: () => getAppFeeBalances(dependencies.orchestrator),\n        createSession: (definition) => createSession({\n            orchestrator: dependencies.orchestrator,\n            environment: config.environment,\n            definition,\n        }),\n        solana: solanaWorkflows(dependencies),\n        waitForIntentStatus: (intentId) => waitForIntentStatus({\n            statusClient: dependencies.orchestrator,\n            clock: dependencies.clock,\n        }, intentId),\n    };\n    return {\n        config,\n        project,\n        createAccount: (context) => createAccountComposition(context, resolveAccountDependencies(context)),\n    };\n}\nexport function createConfiguredCoreComposition(config) {\n    return createCoreComposition(config, createConfiguredDependencies(config), (context) => createConfiguredDependencies(context.sdk));\n}\nfunction createConfiguredDependencies(config) {\n    const rpc = createRpcPort(config.provider);\n    return {\n        orchestrator: createConfiguredOrchestratorClient(config),\n        rpc,\n        bundler: createBundlerClient({\n            endpoint: config.bundler,\n            provider: config.provider,\n        }),\n        ...(config.paymaster\n            ? { paymaster: createPaymasterClient({ endpoint: config.paymaster }) }\n            : {}),\n        clock: {\n            now: Date.now,\n            sleep: (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds)),\n            timeout: (promise, milliseconds, error) => new Promise((resolve, reject) => {\n                const timer = setTimeout(() => reject(error()), milliseconds);\n                promise.then((value) => {\n                    clearTimeout(timer);\n                    resolve(value);\n                }, (reason) => {\n                    clearTimeout(timer);\n                    reject(reason);\n                });\n            }),\n        },\n    };\n}\nfunction solanaWorkflows(dependencies) {\n    const context = {\n        quoteClient: dependencies.orchestrator,\n        submissionClient: dependencies.orchestrator,\n        now: dependencies.clock.now,\n    };\n    return {\n        prepareSolanaIntent: (input) => prepareSolanaIntent(context, input),\n        reconstructSolanaIntent,\n        signSolanaIntent: (input) => signSolanaIntent({ ...input, now: dependencies.clock.now }),\n        submitSolanaIntent: (input) => submitSolanaIntent(context, input),\n        prepareSolanaDeployment: (input) => prepareSolanaDeployment(context, input),\n        submitSolanaDeployment: (prepared) => submitSolanaDeployment(context, prepared),\n    };\n}\nfunction createAccountComposition(initialContext, dependencies) {\n    const workflows = {\n        getEligibleEvmSourceChains: async (destination) => {\n            const catalog = await dependencies.orchestrator.getChainCatalog();\n            const isHyperCore = destination.caip2.startsWith('hypercore:');\n            const destinationId = chainIdFromCaip2(destination.caip2);\n            const destinationInfo = destinationId === undefined\n                ? undefined\n                : catalog.getChainInfo(destinationId);\n            if (!isHyperCore && !destinationInfo) {\n                throw new UnsupportedAccountCapabilityError(`Destination chain ${destination.caip2} is missing from the orchestrator chain catalog.`, { destination: destination.caip2 });\n            }\n            const testnet = isHyperCore ? false : destinationInfo?.testnet;\n            return catalog\n                .getSupportedChainIds()\n                .filter((chainId) => formatCaip2(chainId).startsWith('eip155:') &&\n                catalog.isTestnet(chainId) === testnet)\n                .map(toEvmChainReference);\n        },\n        getAddress: (context, chain) => createStaticAccountRuntime(context.account, chain, false).identity\n            .address,\n        resolveSolanaEvmDestination: async (context, input) => {\n            const runtime = await createAccountRuntimePort(context.account, dependencies).forChain(input.chain);\n            // Projected first: a 7702 account missing its init signature fails\n            // before any call resolver runs.\n            const account = projectIntentAccount({\n                runtime,\n                ...(input.eip7702InitSignature\n                    ? { eip7702InitSignature: input.eip7702InitSignature }\n                    : {}),\n            });\n            const calls = await resolveCalls(input.calls, {\n                account: runtime.identity.address,\n                chain: input.chain,\n                config: context.compatibilityConfig,\n            });\n            return { calls, account };\n        },\n        signMessage: async (context, input) => {\n            const account = createAccountRuntimePort(context.account, dependencies);\n            const session = input.signers?.kind === 'smart-session'\n                ? directSession(input.signers, input.chain)\n                : undefined;\n            return signRuntimeMessage({\n                ...input,\n                runtime: await account.forChain(input.chain),\n                signerInvoker: signerInvoker(context.account, dependencies, session\n                    ? defineValidator(session.session.owners, 'smart-session-validator')\n                    : input.signers?.kind === 'owner'\n                        ? input.signers.validator\n                        : undefined),\n                checkpoints: checkpointPort(context.account, dependencies),\n                ...(input.signers?.kind === 'owner'\n                    ? { selection: input.signers }\n                    : {}),\n                ...(session ? { session } : {}),\n            });\n        },\n        signTypedData: async (context, input) => {\n            const account = createAccountRuntimePort(context.account, dependencies);\n            const session = input.signers?.kind === 'smart-session'\n                ? directSession(input.signers, input.chain)\n                : undefined;\n            return signRuntimeTypedData({\n                ...input,\n                runtime: await account.forChain(input.chain),\n                signerInvoker: signerInvoker(context.account, dependencies, session\n                    ? defineValidator(session.session.owners, 'smart-session-validator')\n                    : input.signers?.kind === 'owner'\n                        ? input.signers.validator\n                        : undefined),\n                checkpoints: checkpointPort(context.account, dependencies),\n                ...(input.signers?.kind === 'owner'\n                    ? { selection: input.signers }\n                    : {}),\n                ...(session ? { session } : {}),\n            });\n        },\n        signEip7702InitData: (context) => signEip7702InitData(context.account, dependencies),\n        signAuthorizations: (context, input) => signEip7702Authorizations(context.account, input, dependencies),\n        prepareIntent: (context, input) => prepareIntent(intentContext(context, dependencies), input),\n        ...solanaWorkflows(dependencies),\n        signIntent: async (context, input) => {\n            const ownerSelection = input.input.signers?.kind === 'owner' ? input.input.signers : undefined;\n            const intent = await signIntent(intentContext(context, dependencies, ownerSelection?.validator), input);\n            return { intent, transcript: intent.transcript };\n        },\n        signIntentAsOwner: (context, input, selection) => {\n            const ownerSelection = input.input.signers?.kind === 'owner' ? input.input.signers : undefined;\n            return signIntentAsOwner(intentContext(context, dependencies, ownerSelection?.validator), input, selection);\n        },\n        assembleIntent: (context, input, signatures, options) => assembleIntent(intentContext(context, dependencies), input, signatures, options),\n        submitIntent: (context, input) => submitIntent(intentContext(context, dependencies), input),\n        sendIntent: (context, input) => sendIntent(intentContext(context, dependencies), input),\n        waitForIntentStatus: (context, intentId) => waitForIntentStatus(intentContext(context, dependencies), intentId),\n        prepareUserOperation: (context, input) => prepareUserOperation(userOperationContext(context, dependencies, input.signers), input),\n        signUserOperation: (context, input) => signUserOperation(userOperationContext(context, dependencies, input.input.signers), input),\n        submitUserOperation: (context, input) => submitUserOperation(userOperationContext(context, dependencies), input),\n        sendUserOperation: (context, input) => sendUserOperation(userOperationContext(context, dependencies, input.signers), input),\n        getUserOperationStatus: (context, input) => getUserOperationStatus(userOperationContext(context, dependencies), input),\n        waitForUserOperationStatus: (context, input) => waitForUserOperationStatus(userOperationContext(context, dependencies), input),\n        reconstructPreparedUserOperation: (context, input) => reconstructPreparedUserOperation(userOperationContext(context, dependencies, input.signers), input),\n        reconstructSignedUserOperation: (context, input) => reconstructSignedUserOperation(userOperationContext(context, dependencies, input.signers), input),\n        getPortfolio: (context, onTestnets = false) => getPortfolio({\n            account: createAccountRuntimePort(context.account, dependencies),\n            client: dependencies.orchestrator,\n            onTestnets,\n        }),\n        getInitData: (context) => accountInitData(context.account),\n        isDeployed: (context, chain) => isAccountDeployed(context.account, chain, dependencies),\n        deploy: (context, chain, options) => deployAccount(context, chain, options, dependencies),\n        setup: (context, chain) => setupAccount(context, chain, dependencies),\n        getTransactionMessages: (prepared) => intentMessages(prepared),\n        reconstructPreparedIntent: (context, input) => reconstructPreparedIntent(context, input, dependencies),\n        signIntentFromRequests: (context, input) => signIntentFromRequests(context, input, dependencies),\n        signRequestedDelegations: (context, prepared) => signRequestedDelegations(context, prepared, dependencies),\n        getOwners: (context, chain) => readOwners({\n            rpc: dependencies.rpc.forChain(chain),\n            chain,\n            accountKind: context.account.account.kind,\n            account: createStaticAccountRuntime(context.account, chain, false)\n                .identity.address,\n            ...(context.account.owners?.kind === 'ecdsa'\n                ? {\n                    ownerValidator: resolveValidator(context.account.owners).address,\n                }\n                : {}),\n            ...(hcaFactory(context.account)\n                ? { hcaFactory: hcaFactory(context.account) }\n                : {}),\n        }),\n        getValidators: (context, chain) => readInstalledModules({\n            rpc: dependencies.rpc.forChain(chain),\n            chain,\n            accountKind: context.account.account.kind,\n            account: createStaticAccountRuntime(context.account, chain, false)\n                .identity.address,\n            kind: 'validator',\n        }),\n        getExecutors: (context, chain) => readInstalledModules({\n            rpc: dependencies.rpc.forChain(chain),\n            chain,\n            accountKind: context.account.account.kind,\n            account: createStaticAccountRuntime(context.account, chain, false)\n                .identity.address,\n            kind: 'executor',\n        }),\n        getSessionDetails: (context, sessions) => accountSessionDetails(context.account, sessions, dependencies),\n        isSessionEnabled: (context, session) => accountSessionEnabled(context.account, session, dependencies),\n        signEnableSession: (context, details) => signAccountEnableSession(context, details, dependencies),\n    };\n    return { context: initialContext, workflows };\n}\nasync function signEip7702InitData(account, dependencies) {\n    const chain = referenceChain();\n    const runtime = createStaticAccountRuntime(account, chain, false);\n    const adoption = runtime.adapter.getEip7702AdoptionPlan?.(runtime.construction);\n    if (!adoption || !account.eoa) {\n        throw new Error('EIP-7702 initialization is unavailable for this account');\n    }\n    return signNexusEip7702Init({\n        planInput: {\n            typedData: createNexusEip7702InitTypedData(adoption),\n            signer: {\n                id: ecdsaSignerId(account.eoa),\n                kind: 'ecdsa',\n            },\n        },\n        signerInvoker: signerInvoker(account, dependencies),\n        checkpoints: { read: async () => [] },\n    });\n}\nasync function signEip7702Authorizations(account, input, dependencies) {\n    if (!input.eip7702InitSignature)\n        return { authorizations: [] };\n    const chains = input.chains.flatMap((chain) => chain.kind === 'evm' ? [chain] : []);\n    const firstChain = chains[0];\n    if (!firstChain || !account.eoa) {\n        throw new Error('EIP-7702 authorization requires an EVM chain and EOA');\n    }\n    const runtime = createStaticAccountRuntime(account, firstChain, false);\n    const adoption = runtime.adapter.getEip7702AdoptionPlan?.(runtime.construction);\n    if (!adoption) {\n        throw new Error('EIP-7702 authorization is unavailable for this account');\n    }\n    const facts = new Map();\n    const nonceByChain = {};\n    for (const chain of chains) {\n        if (facts.has(chain.id))\n            continue;\n        const rpc = dependencies.rpc.forChain(chain);\n        const { code } = await rpc.getCode({ chain }, account.eoa.address);\n        facts.set(chain.id, {\n            kind: 'delegation-code',\n            id: `delegation-${chain.id}`,\n            ...(code ? { code } : {}),\n        });\n        const delegated = code?.toLowerCase() ===\n            `0xef0100${adoption.contract.slice(2)}`.toLowerCase();\n        nonceByChain[chain.id] = delegated\n            ? 0\n            : Number(await rpc.getTransactionCount({ chain }, account.eoa.address));\n    }\n    const result = await signAuthorizationList({\n        planInput: {\n            account: account.eoa.address,\n            contract: adoption.contract,\n            chains,\n            signer: {\n                id: ecdsaSignerId(account.eoa),\n                kind: 'ecdsa',\n            },\n            nonceByChain,\n        },\n        signerInvoker: signerInvoker(account, dependencies),\n        checkpoints: {\n            read: async (checkpoint) => {\n                if (checkpoint.kind !== 'delegation-code')\n                    return [];\n                const fact = facts.get(checkpoint.chain.id);\n                if (!fact)\n                    throw new Error(`Missing delegation fact ${checkpoint.id}`);\n                return [fact];\n            },\n        },\n    });\n    return result;\n}\nfunction referenceChain() {\n    // Account addresses are CREATE2 and chain-independent, so initialization only\n    // needs some EVM chain reference. With no bundled chain set, use mainnet.\n    return toEvmChainReference(1);\n}\nfunction accountInitData(account) {\n    const runtime = createStaticAccountRuntime(account, referenceChain(), false);\n    const plan = runtime.adapter.getDeploymentPlan(runtime.construction);\n    if (!plan.factory || !plan.factoryData) {\n        throw new FactoryArgsNotAvailableError();\n    }\n    return { factory: plan.factory, factoryData: plan.factoryData };\n}\nfunction hcaFactory(account) {\n    if (account.account.kind !== 'hca')\n        return undefined;\n    if (account.account.factory.source === 'explicit') {\n        return account.account.factory.value;\n    }\n    return account.initData && 'factory' in account.initData\n        ? account.initData.factory\n        : undefined;\n}\nasync function isAccountDeployed(account, chain, dependencies) {\n    if (account.account.kind === 'eoa')\n        return true;\n    const runtime = createStaticAccountRuntime(account, chain, false);\n    const { code } = await dependencies.rpc\n        .forChain(chain)\n        .getCode({ chain }, runtime.identity.address);\n    return code !== undefined && code !== '0x';\n}\n/**\n * The EIP-712 payloads that authorise the SOURCE side of a quote, in request\n * order.\n *\n * Deliberately not every EIP-712 payload: the account runtime chain is read off\n * the last of these, and a destination authorisation names the DELIVERY chain.\n * For a HyperCore destination that is a venue id, which hosts no account and\n * has no RPC, so widening this would reintroduce RHI-5510 on the reconstruction\n * path.\n */\nfunction evmOriginPayloads(requests) {\n    const payloads = requests.flatMap((request) => request.purpose === 'originAuthorization' &&\n        request.payload.kind === 'eip712'\n        ? [request.payload.typedData]\n        : []);\n    if (payloads.length === 0) {\n        throw new UnsupportedAccountCapabilityError('EVM intent signing requires at least one EIP-712 origin authorization.');\n    }\n    return payloads;\n}\nfunction intentMessages(prepared) {\n    return [...prepared.quote.signingRequests];\n}\nconst zeroAddress = '0x0000000000000000000000000000000000000000';\nasync function deployAccount(context, chain, options, dependencies) {\n    const account = context.account;\n    if (account.account.kind === 'eoa')\n        return false;\n    if (await isAccountDeployed(account, chain, dependencies))\n        return false;\n    const runtime = createStaticAccountRuntime(account, chain, false);\n    const adoption = account.eoa\n        ? runtime.adapter.getEip7702AdoptionPlan?.(runtime.construction)\n        : undefined;\n    const intentExecutorInstalled = account.initData && 'intentExecutorInstalled' in account.initData\n        ? account.initData.intentExecutorInstalled\n        : false;\n    const asUserOp = Boolean(account.initData) && !intentExecutorInstalled;\n    const useUserOperation = !adoption && (asUserOp || context.sdk.bundler?.kind === 'custom');\n    let initSignature = options?.eip7702InitSignature;\n    if (adoption && !initSignature) {\n        initSignature = (await signEip7702InitData(account, dependencies)).signature;\n    }\n    if (useUserOperation) {\n        const plan = runtime.adapter.getDeploymentPlan(runtime.construction);\n        if (!plan.factory || !plan.factoryData) {\n            throw new FactoryArgsNotAvailableError();\n        }\n        const workflowContext = userOperationContext(context, dependencies);\n        const submitted = await sendUserOperation(workflowContext, {\n            chain,\n            calls: [{ target: zeroAddress, value: 0n, data: '0x' }],\n        });\n        await waitForUserOperationStatus(workflowContext, submitted);\n    }\n    else {\n        const workflowContext = intentContext(context, dependencies);\n        const submitted = await sendIntent(workflowContext, {\n            destination: chain,\n            sourceChains: [chain],\n            calls: [],\n            tokenRequests: [],\n            ...(initSignature ? { eip7702InitSignature: initSignature } : {}),\n            options: options?.sponsored\n                ? { sponsorSettings: { gas: true, bridgeFees: true, swapFees: true } }\n                : {},\n        });\n        await waitForIntentStatus(workflowContext, submitted.intentId);\n    }\n    return true;\n}\nasync function setupAccount(context, chain, dependencies) {\n    const account = context.account;\n    if (account.account.kind === 'eoa' || account.account.kind === 'hca') {\n        return false;\n    }\n    const runtime = createStaticAccountRuntime(account, chain, true);\n    const plan = runtime.construction.setup;\n    const candidates = [\n        ...plan.validators,\n        ...plan.executors,\n        ...plan.fallbacks,\n        ...plan.hooks,\n    ].filter((module) => !(account.account.kind === 'startale' &&\n        isAddressEqual(module.address, K1_DEFAULT_VALIDATOR_ADDRESS)));\n    const installationState = await readModuleInstallations({\n        rpc: dependencies.rpc.forChain(chain),\n        chain,\n        account: runtime.identity.address,\n        modules: candidates,\n    });\n    const missing = candidates.filter((_module, index) => !installationState[index]);\n    if (missing.length === 0)\n        return false;\n    const calls = missing.flatMap((module) => runtime.adapter.encodeModuleInstallation(module).map((data) => ({\n        target: runtime.identity.address,\n        value: 0n,\n        data,\n    })));\n    const intentExecutor = getIntentExecutorModule(account.sessions.environment);\n    const usesIntent = missing.every((module) => !isAddressEqual(module.address, intentExecutor.address));\n    if (usesIntent) {\n        const submitted = await sendIntent(intentContext(context, dependencies), {\n            destination: chain,\n            sourceChains: [chain],\n            calls,\n            tokenRequests: [],\n            options: {},\n        });\n        await waitForIntentStatus(intentContext(context, dependencies), submitted.intentId);\n    }\n    else {\n        const submitted = await sendUserOperation(userOperationContext(context, dependencies), { chain, calls });\n        await waitForUserOperationStatus(userOperationContext(context, dependencies), submitted);\n    }\n    return true;\n}\nfunction accountSessionDetails(account, sessions, dependencies) {\n    const address = createStaticAccountRuntime(account, referenceChain(), false)\n        .identity.address;\n    const environment = account.sessions.environment;\n    return buildSessionDetails({\n        account: address,\n        sessions,\n        environment,\n        readNonce: (session) => {\n            const chain = toEvmChainReference(session.chain.id);\n            return readSessionNonce({\n                rpc: dependencies.rpc.forChain(chain),\n                chain,\n                account: address,\n                lockTag: SESSION_LOCK_TAG,\n                environment,\n            });\n        },\n    });\n}\nfunction accountSessionEnabled(account, session, dependencies) {\n    const chain = toEvmChainReference(session.chain.id);\n    const address = createStaticAccountRuntime(account, chain, false).identity\n        .address;\n    return readSessionEnabled({\n        rpc: dependencies.rpc.forChain(chain),\n        chain,\n        account: address,\n        session,\n        environment: account.sessions.environment,\n    });\n}\nasync function signAccountEnableSession(context, details, dependencies) {\n    const defaultChain = referenceChain();\n    const defaultRuntime = createStaticAccountRuntime(context.account, defaultChain, false);\n    const defaultSigning = createAccountSigningContext({\n        runtime: defaultRuntime,\n        purpose: 'session-enable',\n        signerInvoker: signerInvoker(context.account, dependencies),\n    });\n    const chain = resolveSessionEnableChain({\n        accountKind: context.account.account.kind,\n        validator: defaultSigning.validatorCapabilities.compatibilityKey.moduleAddress,\n        hashesAndChainIds: details.hashesAndChainIds,\n        defaultChain,\n    });\n    const runtime = chain.id === defaultChain.id\n        ? defaultRuntime\n        : createStaticAccountRuntime(context.account, chain, false);\n    const signing = createAccountSigningContext({\n        runtime,\n        purpose: 'session-enable',\n        signerInvoker: signerInvoker(context.account, dependencies),\n    });\n    const topology = signingTopology(signing.validator);\n    const route = resolveAccountTypedDataSigning({\n        typedData: details.data,\n        chain,\n        context: signing,\n    });\n    const accountRoute = getAccountSignatureRoute(runtime, signing, route.erc7739, route.payloadKind);\n    const result = await signSessionEnablement({\n        context: signing,\n        checkpoints: checkpointPort(context.account, dependencies),\n        planInput: {\n            typedData: details.data,\n            signingMaterial: route.material,\n            chain,\n            ...topology,\n            tasks: createValidatorSigningTasks({\n                validator: signing.validator,\n                signerReferences: signing.signerReferences,\n                taskPrefix: 'typed-data',\n                ecdsaInvocation: route.ecdsaInvocation,\n                webauthnInvocation: route.webauthnInvocation,\n            }),\n            validatorCodec: getSigningValidatorCodec(signing, route.payloadKind),\n            ...(signing.validator.kind === 'multi-factor'\n                ? {\n                    validatorFactors: getSigningValidatorFactors(signing, route.payloadKind),\n                }\n                : {}),\n            route: {\n                erc7739: accountRoute.erc7739,\n                accountEnvelope: accountRoute.accountEnvelope,\n                erc6492: { kind: 'none' },\n            },\n        },\n    });\n    return result.signature;\n}\nasync function reconstructPreparedIntent(context, input, dependencies) {\n    const accountChain = toEvmChainReference(accountChainIdFromOrigins(evmOriginPayloads(input.quote.signingRequests)));\n    const runtime = await createAccountRuntimePort(context.account, dependencies).forChain(accountChain);\n    let resolvedSessions;\n    if (input.intentInput.signers?.kind === 'smart-session') {\n        const prepared = await prepareIntentSessions({\n            intent: input.intentInput,\n            runtime,\n            context: { checkpoints: checkpointPort(context.account, dependencies) },\n        });\n        resolvedSessions = prepared?.byChain;\n    }\n    const signing = buildIntentSigningInput(runtime, input.quote, resolvedSessions, input.intentInput.signers?.kind === 'owner'\n        ? input.intentInput.signers.validator\n        : undefined, input.intentInput.signers?.kind === 'owner'\n        ? input.intentInput.signers.signerIds\n        : undefined);\n    return {\n        traceId: input.traceId,\n        input: input.intentInput,\n        request: input.request,\n        normalized: input.normalized,\n        quote: input.quote,\n        quotes: input.quotes,\n        signing,\n        accountChain,\n        ...(resolvedSessions\n            ? {\n                resolvedSessions,\n                sessionEnvironment: runtime.construction.sessions.environment,\n            }\n            : {}),\n    };\n}\nasync function signIntentFromRequests(context, input, dependencies) {\n    const accountChain = toEvmChainReference(accountChainIdFromOrigins(evmOriginPayloads(input.signingRequests)));\n    const runtime = await createAccountRuntimePort(context.account, dependencies).forChain(accountChain);\n    let resolvedSessions;\n    if (input.signers?.kind === 'smart-session') {\n        const preparedSessions = await prepareIntentSessions({\n            intent: {\n                destination: input.targetChain,\n                calls: [],\n                tokenRequests: [],\n                signers: input.signers,\n            },\n            runtime,\n            context: { checkpoints: checkpointPort(context.account, dependencies) },\n        });\n        resolvedSessions = preparedSessions?.byChain;\n    }\n    const quote = {\n        signingRequests: input.signingRequests,\n    };\n    const signing = buildIntentSigningInput(runtime, quote, resolvedSessions, input.signers?.kind === 'owner' ? input.signers.validator : undefined, input.signers?.kind === 'owner' ? input.signers.signerIds : undefined);\n    const prepared = {\n        traceId: '',\n        input: {\n            destination: input.targetChain,\n            calls: [],\n            tokenRequests: [],\n            ...(input.signers ? { signers: input.signers } : {}),\n        },\n        request: {},\n        normalized: {},\n        quote,\n        quotes: [quote],\n        signing,\n        accountChain,\n        ...(resolvedSessions\n            ? {\n                resolvedSessions,\n                sessionEnvironment: runtime.construction.sessions.environment,\n            }\n            : {}),\n    };\n    const signed = await signIntent(intentContext(context, dependencies, input.signers?.kind === 'owner' ? input.signers.validator : undefined), prepared);\n    return { proofs: signed.proofs, transcript: signed.transcript };\n}\n/**\n * Signs the delegations a quote explicitly requested.\n *\n * The nonce is read here, at signing time, because it can move between quoting\n * and signing. A delegation the quote asked for is always signed: skipping one\n * because the code already looks delegated would submit a proof vector shorter\n * than the request set.\n */\nasync function signDelegations(account, requests, dependencies) {\n    if (requests.length === 0)\n        return [];\n    if (!account.eoa) {\n        throw new UnsupportedAccountCapabilityError('This quote requires an EIP-7702 delegation, which needs an EOA-backed account.');\n    }\n    const eoa = account.eoa;\n    const delegations = await Promise.all(requests.map(async (request) => {\n        const chain = toEvmChainReference(request.chainId);\n        const nonce = await dependencies.rpc\n            .forChain(chain)\n            .getTransactionCount({ chain }, eoa.address);\n        return { ...request, nonce: Number(nonce) };\n    }));\n    const { authorizations } = await signRequestedDelegationList({\n        planInput: {\n            signer: { id: ecdsaSignerId(eoa), kind: 'ecdsa' },\n            delegations,\n        },\n        signerInvoker: signerInvoker(account, dependencies),\n        checkpoints: { read: async () => [] },\n    });\n    return authorizations;\n}\n/** Collects the quote's delegation proofs, bound to their request slots. */\nasync function signRequestedDelegations(context, prepared, dependencies) {\n    const requests = prepared.signing.requests.flatMap((request) => request.kind === 'eip7702' ? [request] : []);\n    const authorizations = await signDelegations(context.account, requests.map(({ chainId, contract }) => ({ chainId, contract })), dependencies);\n    const setId = requestSetId(prepared.quote.signingRequests);\n    return requests.map((request, index) => {\n        const authorization = authorizations[index];\n        return {\n            intentId: prepared.quote.intentId,\n            requestSetId: setId,\n            requestIndex: request.index,\n            proof: {\n                kind: 'eip7702',\n                nonce: authorization.nonce,\n                signature: {\n                    r: authorization.r,\n                    s: authorization.s,\n                    yParity: ((authorization.yParity ?? 0) === 1 ? 1 : 0),\n                },\n            },\n        };\n    });\n}\nfunction intentContext(context, dependencies, validator) {\n    return {\n        compatibilityConfig: context.compatibilityConfig,\n        account: createAccountRuntimePort(context.account, dependencies),\n        quoteClient: dependencies.orchestrator,\n        submissionClient: dependencies.orchestrator,\n        statusClient: dependencies.orchestrator,\n        signerInvoker: signerInvoker(context.account, dependencies, validator),\n        checkpoints: checkpointPort(context.account, dependencies),\n        signAuthorizations: async (input) => (await signEip7702Authorizations(context.account, input, dependencies))\n            .authorizations,\n        signDelegation: async (input) => {\n            const [authorization] = await signDelegations(context.account, [input], dependencies);\n            if (!authorization) {\n                throw new Error(`EIP-7702 delegation for chain ${input.chainId} was not signed`);\n            }\n            return authorization;\n        },\n        clock: dependencies.clock,\n    };\n}\nfunction userOperationContext(context, dependencies, selection) {\n    if (!dependencies.bundler) {\n        throw new Error('A bundler client is required for UserOperations');\n    }\n    return {\n        compatibilityConfig: context.compatibilityConfig,\n        account: createAccountRuntimePort(context.account, dependencies),\n        rpc: dependencies.rpc,\n        bundler: dependencies.bundler,\n        ...(dependencies.paymaster ? { paymaster: dependencies.paymaster } : {}),\n        signerInvoker: signerInvoker(context.account, dependencies, selection?.validator),\n        checkpoints: checkpointPort(context.account, dependencies),\n        clock: dependencies.clock,\n    };\n}\nfunction createAccountRuntimePort(account, dependencies) {\n    const cache = new Map();\n    return {\n        forChain: (chain) => {\n            const existing = cache.get(chain.id);\n            if (existing)\n                return existing;\n            const pending = materializeAccountRuntime(account, dependencies, chain);\n            cache.set(chain.id, pending);\n            return pending;\n        },\n    };\n}\nasync function materializeAccountRuntime(resolved, dependencies, chain) {\n    const material = accountMaterial(resolved);\n    const pendingConstruction = createAccountConstruction({\n        material,\n        chain,\n        deployed: false,\n    });\n    const pendingAdapter = createAccountAdapter(pendingConstruction);\n    const identity = pendingAdapter.getIdentity(pendingConstruction);\n    const { code } = await dependencies.rpc\n        .forChain(chain)\n        .getCode({ chain }, identity.address);\n    const deployed = code !== undefined && code !== '0x';\n    if (!deployed) {\n        return {\n            adapter: pendingAdapter,\n            construction: pendingConstruction,\n            identity,\n        };\n    }\n    const construction = createAccountConstruction({\n        material,\n        chain,\n        deployed: true,\n    });\n    const adapter = createAccountAdapter(construction);\n    return {\n        adapter,\n        construction,\n        identity: adapter.getIdentity(construction),\n    };\n}\nfunction signerInvoker(account, dependencies, validator) {\n    return (dependencies.signerInvoker ??\n        createSignerInvocationPort({\n            signers: signerRegistry(account, validator),\n            resolveChain: (chain) => getChainById(chain.id),\n        }));\n}\nfunction signerRegistry(account, validator) {\n    const signers = {};\n    for (const owner of [\n        ...validatorOwners(account.owners),\n        ...validatorOwners(validator),\n    ]) {\n        signers[owner.signerId] =\n            owner.kind === 'webauthn'\n                ? { kind: 'webauthn', account: owner.account }\n                : { kind: 'ecdsa', account: owner.account };\n    }\n    if (account.eoa) {\n        signers[ecdsaSignerId(account.eoa)] = {\n            kind: 'ecdsa',\n            account: account.eoa,\n        };\n    }\n    return signers;\n}\nfunction validatorOwners(validator) {\n    if (!validator)\n        return [];\n    return validator.kind === 'multi-factor'\n        ? validator.validators.flatMap(({ owners }) => owners)\n        : validator.owners;\n}\nfunction directSession(selection, chain) {\n    const selected = selection.byChain[chain.id];\n    if (!selected)\n        throw new Error(`No session configured for chain ${chain.id}`);\n    return {\n        kind: 'smart-session',\n        session: selected.session,\n        ...(selected.enableData ? { enableData: selected.enableData } : {}),\n        verifyExecutions: false,\n    };\n}\nfunction checkpointPort(account, dependencies) {\n    return {\n        read: async (checkpoint) => {\n            const rpc = dependencies.rpc.forChain(checkpoint.chain);\n            switch (checkpoint.kind) {\n                case 'account-deployment': {\n                    const { code } = await rpc.getCode({ chain: checkpoint.chain }, checkpoint.account);\n                    return [\n                        {\n                            kind: 'account-deployed',\n                            id: checkpoint.id,\n                            deployed: code !== undefined && code !== '0x',\n                        },\n                    ];\n                }\n                case 'delegation-code': {\n                    const { code } = await rpc.getCode({ chain: checkpoint.chain }, checkpoint.account);\n                    return [\n                        {\n                            kind: 'delegation-code',\n                            id: checkpoint.id,\n                            ...(code ? { code } : {}),\n                        },\n                    ];\n                }\n                case 'session-enabled': {\n                    const enabled = await rpc.readContract({ chain: checkpoint.chain }, {\n                        address: getSmartSessionEmissaryAddress(account.sessions.environment),\n                        abi: sessionEnabledAbi,\n                        functionName: 'isPermissionEnabled',\n                        args: [checkpoint.account, checkpoint.permissionId],\n                    });\n                    return [{ kind: 'session-enabled', id: checkpoint.id, enabled }];\n                }\n            }\n        },\n    };\n}\n","import { createPublicClient } from 'viem';\nimport { entryPoint07Address } from 'viem/account-abstraction';\nimport { getChainById } from '../../chains/catalog.js';\nimport { requestJsonRpc } from '../json-rpc.js';\nimport { createRpcTransport } from '../rpc/transport.js';\nimport { resolveBundlerUrl } from './endpoints.js';\nexport function createBundlerClient(input) {\n    const fetchPort = input.fetch ?? globalThis.fetch;\n    const request = (chainId, method, params) => requestJsonRpc({\n        fetch: fetchPort,\n        url: resolveBundlerUrl(chainId, input.endpoint),\n        method,\n        params,\n    });\n    return {\n        estimateGas: async (chain, operation) => mapGasEstimate(await request(chain.id, 'eth_estimateUserOperationGas', [\n            serializeUserOperation(operation),\n            entryPoint07Address,\n        ])),\n        getGasPrice: async (chain) => {\n            if (input.endpoint?.kind === 'custom') {\n                const client = createPublicClient({\n                    chain: getChainById(chain.id),\n                    transport: createRpcTransport(chain.id, input.provider),\n                });\n                const fees = await client.estimateFeesPerGas({ type: 'eip1559' });\n                return {\n                    maxFeePerGas: 2n * fees.maxFeePerGas,\n                    maxPriorityFeePerGas: 2n * fees.maxPriorityFeePerGas,\n                };\n            }\n            return mapGasPrice(await request(chain.id, 'pimlico_getUserOperationGasPrice', []));\n        },\n        send: async (chain, operation) => (await request(chain.id, 'eth_sendUserOperation', [\n            serializeUserOperation(operation),\n            entryPoint07Address,\n        ])),\n        getReceipt: async (chain, hash) => {\n            const receipt = await request(chain.id, 'eth_getUserOperationReceipt', [\n                hash,\n            ]);\n            return receipt === null\n                ? undefined\n                : receipt;\n        },\n    };\n}\nexport function serializeUserOperation(operation) {\n    return Object.fromEntries(Object.entries(operation)\n        .filter(([, value]) => value !== undefined)\n        .map(([key, value]) => [\n        key,\n        typeof value === 'bigint' ? `0x${value.toString(16)}` : value,\n    ]));\n}\nfunction mapGasEstimate(value) {\n    const result = value;\n    return {\n        callGasLimit: parseQuantity(result.callGasLimit),\n        verificationGasLimit: parseQuantity(result.verificationGasLimit),\n        preVerificationGas: parseQuantity(result.preVerificationGas),\n        ...(result.paymasterVerificationGasLimit\n            ? {\n                paymasterVerificationGasLimit: parseQuantity(result.paymasterVerificationGasLimit),\n            }\n            : {}),\n        ...(result.paymasterPostOpGasLimit\n            ? {\n                paymasterPostOpGasLimit: parseQuantity(result.paymasterPostOpGasLimit),\n            }\n            : {}),\n    };\n}\nfunction mapGasPrice(value) {\n    const result = value;\n    return {\n        maxFeePerGas: parseQuantity(result.fast?.maxFeePerGas),\n        maxPriorityFeePerGas: parseQuantity(result.fast?.maxPriorityFeePerGas),\n    };\n}\nfunction parseQuantity(value) {\n    if (value === undefined)\n        throw new Error('JSON-RPC quantity is missing');\n    return BigInt(value);\n}\n","export class JsonRpcClientError extends Error {\n    method;\n    code;\n    data;\n    constructor(input) {\n        super(input.message, input.cause === undefined ? undefined : { cause: input.cause });\n        this.name = 'JsonRpcClientError';\n        this.method = input.method;\n        this.code = input.code;\n        this.data = input.data;\n    }\n}\nlet nextRequestId = 1;\nexport async function requestJsonRpc(input) {\n    let response;\n    try {\n        response = await input.fetch(input.url, {\n            method: 'POST',\n            headers: { 'Content-Type': 'application/json' },\n            body: JSON.stringify({\n                jsonrpc: '2.0',\n                id: nextRequestId++,\n                method: input.method,\n                params: input.params,\n            }),\n        });\n    }\n    catch (cause) {\n        throw new JsonRpcClientError({\n            method: input.method,\n            message: `JSON-RPC request ${input.method} failed`,\n            cause,\n        });\n    }\n    let envelope;\n    try {\n        envelope = (await response.json());\n    }\n    catch (cause) {\n        throw new JsonRpcClientError({\n            method: input.method,\n            message: `JSON-RPC request ${input.method} returned invalid JSON`,\n            cause,\n        });\n    }\n    if (!response.ok || envelope.error) {\n        throw new JsonRpcClientError({\n            method: input.method,\n            message: envelope.error?.message ??\n                `JSON-RPC request ${input.method} failed with status ${response.status}`,\n            code: envelope.error?.code,\n            data: envelope.error?.data,\n        });\n    }\n    return envelope.result;\n}\n","import { http } from 'viem';\nimport { resolveRpcUrl } from './providers.js';\nexport function createRpcTransport(chainId, provider) {\n    return http(resolveRpcUrl(chainId, provider));\n}\n","export function resolveRpcUrl(chainId, provider) {\n    switch (provider.kind) {\n        case 'public':\n            return undefined;\n        case 'custom':\n            return provider.urls[chainId];\n    }\n}\n","export function resolveBundlerUrl(chainId, endpoint) {\n    if (!endpoint)\n        return `https://public.pimlico.io/v2/${chainId}/rpc`;\n    switch (endpoint.kind) {\n        case 'pimlico':\n            return `https://api.pimlico.io/v2/${chainId}/rpc?apikey=${endpoint.apiKey}`;\n        case 'biconomy':\n            return `https://bundler.biconomy.io/api/v3/${chainId}/${endpoint.apiKey}`;\n        case 'custom': {\n            const url = typeof endpoint.urls === 'string'\n                ? endpoint.urls\n                : endpoint.urls[chainId];\n            if (!url)\n                throw new Error(`No bundler URL configured for chain ${chainId}`);\n            return url;\n        }\n    }\n}\n","export function createOrchestratorAuth(auth) {\n    if (auth.kind === 'api-key') {\n        const headers = Object.freeze({ 'x-api-key': auth.apiKey });\n        return {\n            getHeaders: async () => headers,\n            requestsIntentExtension: () => false,\n            getQuoteHeaders: async () => headers,\n        };\n    }\n    const accessToken = async () => typeof auth.accessToken === 'function'\n        ? await auth.accessToken()\n        : auth.accessToken;\n    const headers = async () => ({\n        Authorization: `Bearer ${await accessToken()}`,\n    });\n    return {\n        getHeaders: headers,\n        requestsIntentExtension: (sponsored) => sponsored && auth.getIntentExtensionToken !== undefined,\n        getQuoteHeaders: async (intentInput, sponsored) => ({\n            ...(await headers()),\n            ...(sponsored && auth.getIntentExtensionToken\n                ? {\n                    'X-Intent-Extension': `Bearer ${await auth.getIntentExtensionToken(intentInput)}`,\n                }\n                : {}),\n        }),\n    };\n}\n","// Runtime chain catalog, sourced from the orchestrator's `GET /chains`.\n//\n// This replaces the SDK's bundled `@rhinestone/shared-configs` chain data: the\n// orchestrator is authoritative for chain *facts* (which chains are supported,\n// their tokens, and the wrapped-native token), so the SDK reads them at runtime\n// instead of baking them in at build time. That's what lets a new chain go live\n// without an SDK release.\n//\n// `Chain` objects themselves (rpc/nativeCurrency/formatters, needed for signing\n// and `createPublicClient`) still come from viem — `/chains` can't carry those.\n// The catalog only owns the chain *facts*.\nimport { chainIdFromCaip2, isCaip2 } from '../../chains/caip2.js';\n/**\n * Read-only view over the chain facts returned by `GET /chains`. Built once per\n * client (fetched lazily) and read synchronously thereafter.\n */\nexport class ChainCatalog {\n    chains;\n    constructor(chains) {\n        this.chains = chains;\n    }\n    getSupportedChainIds() {\n        return Object.keys(this.chains).map(Number);\n    }\n    isSupported(chainId) {\n        return chainId in this.chains;\n    }\n    getChainInfo(chainId) {\n        return this.chains[chainId];\n    }\n    /**\n     * Whether the chain is a testnet, per the orchestrator's `/chains`. Uses the\n     * catalog's own flag so it is authoritative for every supported chain\n     * (including non-EVM and chains newer than the SDK's viem), rather than\n     * viem's local chain list.\n     */\n    isTestnet(chainId) {\n        return this.chains[chainId]?.testnet ?? false;\n    }\n    /** The wrapped-native (e.g. WETH) token for the chain, if advertised. */\n    getWrappedNativeToken(chainId) {\n        return this.chains[chainId]?.wrappedNativeToken;\n    }\n    getSupportedTokens(chainId) {\n        return this.chains[chainId]?.supportedTokens;\n    }\n}\n// Adapter boundary: decode the CAIP-2-keyed wire response into a numeric-keyed\n// `ChainInfoMap`. Entries whose id can't be mapped are skipped rather than\n// failing the whole catalog.\nexport function parseChains(json) {\n    const out = {};\n    for (const [key, entry] of Object.entries(json)) {\n        const id = isCaip2(key) ? chainIdFromCaip2(key) : Number(key);\n        if (id === undefined || !Number.isFinite(id))\n            continue;\n        out[id] = {\n            name: entry.name,\n            testnet: entry.testnet,\n            supportedTokens: entry.supportedTokens,\n            ...(entry.wrappedNativeToken\n                ? { wrappedNativeToken: entry.wrappedNativeToken }\n                : {}),\n        };\n    }\n    return out;\n}\n","import { parseErrorEnvelope } from './errors.js';\nexport async function fetchOrchestratorJson(input) {\n    // Transport-level failures reject here and bubble up raw so `isConnectionError`\n    // can classify them for retry; only HTTP responses become typed errors.\n    const response = await input.fetch(input.url, input.init);\n    const traceId = response.headers.get('x-trace-id') ?? undefined;\n    if (!response.ok) {\n        let body;\n        try {\n            body = (await response.json());\n        }\n        catch {\n            body = {\n                code: 'INTERNAL_ERROR',\n                message: `Orchestrator request failed with status ${response.status}`,\n                traceId: '',\n            };\n        }\n        const envelope = {\n            code: body.code ?? 'INTERNAL_ERROR',\n            message: body.message ??\n                `Orchestrator request failed with status ${response.status}`,\n            traceId: traceId ?? body.traceId ?? '',\n            details: body.details,\n        };\n        const retryAfter = response.headers.get('retry-after') ?? undefined;\n        throw parseErrorEnvelope(envelope, response.status, retryAfter ?? undefined);\n    }\n    const body = await response.json();\n    if (body && typeof body === 'object' && !Array.isArray(body)) {\n        return {\n            ...body,\n            ...(traceId ? { traceId } : {}),\n        };\n    }\n    return body;\n}\n","import { chainIdFromReference, formatCaip2, parseCaip2, } from '../../chains/caip2.js';\nimport { ValidationError } from './errors.js';\nimport { serializeBigInts } from './serialization.js';\nexport function mapIntentRequestToWire(input) {\n    return serializeBigInts({\n        account: input.account,\n        destination: input.destination,\n        ...(input.source ? { source: input.source } : {}),\n        ...(input.options\n            ? {\n                options: {\n                    ...input.options,\n                    settlementLayers: mapSettlementLayers(input.options.settlementLayers),\n                    quoters: mapQuoters(input.options.quoters),\n                },\n            }\n            : {}),\n    });\n}\nexport function mapSignedIntentToWire(input) {\n    return serializeBigInts({\n        intentId: input.intentId,\n        proofs: input.proofs,\n        ...(input.dryRun ? { options: { dryRun: true } } : {}),\n    });\n}\nexport function mapIntentSubmissionFromWire(intentId, value) {\n    const input = value;\n    return { traceId: input.traceId ?? '', intentId: input.intentId ?? intentId };\n}\nexport function mapSplitRequestToWire(input) {\n    return serializeBigInts({\n        chainId: formatCaip2(input.chainId),\n        tokens: input.tokens,\n        settlementLayers: mapSettlementLayers(input.settlementLayers),\n    });\n}\nexport function mapSplitResultFromWire(value) {\n    const input = value;\n    return {\n        traceId: input.traceId ?? '',\n        intents: (input.intents ?? []).map((intent) => Object.fromEntries(Object.entries(intent).map(([token, amount]) => [\n            token,\n            BigInt(amount),\n        ]))),\n    };\n}\nexport function mapPortfolioFromWire(value) {\n    const input = value;\n    return {\n        tokens: (input.portfolio ?? []).map((token) => ({\n            symbol: token.symbol,\n            chains: token.chains.map((chain) => ({\n                chain: parseNumericChainId(chain.chainId),\n                address: chain.address,\n                decimals: chain.decimals,\n                amount: BigInt(chain.amount),\n            })),\n        })),\n    };\n}\n// ---------------------------------------------------------------------------\n// Quotes\n// ---------------------------------------------------------------------------\nexport function mapQuoteResponseFromWire(value) {\n    const input = value;\n    // An outcome this SDK version does not know is refused rather than read as\n    // \"no routes\": a reserved future status carries no route array, and treating\n    // it as an empty success would report \"no route available\" for a quote the\n    // orchestrator did answer.\n    if (input.status !== 'quoted') {\n        throw new ValidationError({\n            message: `The orchestrator returned an unsupported quote outcome: ${String(input.status)}.`,\n        });\n    }\n    return {\n        traceId: input.traceId ?? '',\n        routes: (input.routes ?? []).map(mapQuoteFromWire),\n    };\n}\nfunction mapQuoteFromWire(value) {\n    const route = {\n        intentId: value.intentId,\n        expiresAt: value.expiresAt,\n        estimatedFillTime: value.estimatedFillTime,\n        settlementLayer: value.settlementLayer,\n        plan: value.plan,\n        cost: mapCostFromWire(value.cost),\n        requirements: value.requirements.map(mapRequirementFromWire),\n        signingRequests: value.signingRequests.map(mapSigningRequestFromWire),\n    };\n    switch (value.purpose) {\n        case 'execution':\n            return {\n                ...route,\n                purpose: 'execution',\n                ...mapBridgeFillFromWire(value.bridgeFill),\n            };\n        case 'deployment':\n            return {\n                ...route,\n                purpose: 'deployment',\n                deploymentCosts: value.deploymentCosts.map(mapDeploymentCostFromWire),\n            };\n        default:\n            return invalid(`The orchestrator returned a route with an unsupported purpose: ${String(value.purpose)}.`);\n    }\n}\nfunction mapDeploymentCostFromWire(value) {\n    return {\n        vm: value.vm,\n        chainId: value.chainId,\n        rent: {\n            amount: BigInt(value.rent.amount),\n            usd: value.rent.usd,\n            sponsored: value.rent.sponsored,\n        },\n    };\n}\nfunction mapCostFromWire(value) {\n    return {\n        input: value.input.map(mapCostTokenFromWire),\n        output: value.output.map(mapCostTokenFromWire),\n        fees: value.fees,\n    };\n}\nfunction mapCostTokenFromWire(value) {\n    return {\n        chainId: value.chainId,\n        tokenAddress: value.tokenAddress,\n        symbol: value.symbol,\n        decimals: value.decimals,\n        price: value.price,\n        amount: BigInt(value.amount),\n    };\n}\nfunction mapRequirementFromWire(value) {\n    return {\n        ...value,\n        amount: BigInt(value.amount),\n    };\n}\n// ---------------------------------------------------------------------------\n// Signing requests\n//\n// This is the trust boundary: an unrecognised authority, scope or payload kind\n// must never be narrowed onto a familiar one, because the difference is what\n// the user is authorising. Everything else is disclosure and passes through.\n// ---------------------------------------------------------------------------\nconst SIGNING_PURPOSES = new Set([\n    'originAuthorization',\n    'destinationAuthorization',\n    'targetExecutionAuthorization',\n    'delegationAuthorization',\n]);\nfunction invalid(message) {\n    throw new ValidationError({ message });\n}\nfunction isObject(value) {\n    return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\nexport function mapSigningRequestFromWire(value) {\n    if (!isObject(value)) {\n        invalid('The orchestrator returned a malformed signing request.');\n    }\n    const account = value.account;\n    if (!isObject(account) ||\n        (account.vm !== 'evm' && account.vm !== 'svm') ||\n        (account.vm === 'evm' && typeof account.address !== 'string') ||\n        (account.vm === 'svm' &&\n            (typeof account.wallet !== 'string' ||\n                typeof account.swigAccount !== 'string'))) {\n        invalid(`The orchestrator returned a signing request for an unsupported account: ${String(account?.vm)}.`);\n    }\n    const authority = value.authority;\n    if (!isObject(authority) ||\n        (authority.kind !== 'secp256k1' &&\n            authority.kind !== 'account' &&\n            authority.kind !== 'swigRole')) {\n        invalid(`The orchestrator returned a signing request with an unsupported authority: ${String(authority?.kind)}.`);\n    }\n    if (authority.kind === 'swigRole') {\n        const role = authority.authority;\n        if (!isObject(role) ||\n            !((role.kind === 'secp256k1' && typeof role.address === 'string') ||\n                (role.kind === 'secp256r1' && typeof role.publicKey === 'string'))) {\n            invalid(`The orchestrator returned a signing request with an unsupported Swig role authority: ${String(role?.kind)}.`);\n        }\n    }\n    const scope = value.scope;\n    if (!isObject(scope) || (scope.vm !== 'evm' && scope.vm !== 'svm')) {\n        invalid(`The orchestrator returned a signing request with an unsupported scope: ${String(scope?.vm)}.`);\n    }\n    if (typeof value.purpose !== 'string' ||\n        !SIGNING_PURPOSES.has(value.purpose)) {\n        invalid(`The orchestrator returned a signing request with an unsupported purpose: ${String(value.purpose)}.`);\n    }\n    if (!Array.isArray(value.chainIds) || !Array.isArray(value.validity)) {\n        invalid('The orchestrator returned a signing request without chain or validity context.');\n    }\n    return {\n        account,\n        authority,\n        scope,\n        chainIds: value.chainIds,\n        purpose: value.purpose,\n        validity: value.validity,\n        payload: mapSigningPayloadFromWire(value.payload),\n    };\n}\nfunction mapSigningPayloadFromWire(value) {\n    if (!isObject(value)) {\n        invalid('The orchestrator returned a signing request with no payload.');\n    }\n    switch (value.kind) {\n        case 'eip712': {\n            const typedData = value.typedData;\n            if (!isObject(typedData) ||\n                !isObject(typedData.domain) ||\n                !isObject(typedData.types) ||\n                typeof typedData.primaryType !== 'string' ||\n                !isObject(typedData.message) ||\n                (value.signatureFormat !== 'secp256k1' &&\n                    value.signatureFormat !== 'account')) {\n                invalid('The orchestrator returned an invalid EIP-712 signing payload.');\n            }\n            return value;\n        }\n        case 'personalSign': {\n            const message = value.message;\n            if (!isObject(message) ||\n                message.encoding !== 'utf8' ||\n                typeof message.value !== 'string') {\n                invalid('The orchestrator returned an invalid personal-sign signing payload.');\n            }\n            return value;\n        }\n        case 'eip7702': {\n            const authorization = value.authorization;\n            if (!isObject(authorization) ||\n                typeof authorization.chainId !== 'number' ||\n                typeof authorization.address !== 'string') {\n                invalid('The orchestrator returned an invalid EIP-7702 signing payload.');\n            }\n            return value;\n        }\n        case 'webauthn':\n            if (typeof value.challenge !== 'string') {\n                invalid('The orchestrator returned an invalid WebAuthn signing payload.');\n            }\n            return value;\n        default:\n            return invalid(`The orchestrator returned an unsupported signing payload kind: ${String(value.kind)}.`);\n    }\n}\n/** Narrows a caller-supplied proof before it is sent. */\nexport function assertSupportedProof(value) {\n    switch (value.kind) {\n        case 'eip712':\n        case 'personalSign':\n        case 'eip7702':\n        case 'webauthn':\n            return value;\n        default:\n            return invalid(`Unsupported intent proof kind: ${String(value.kind)}.`);\n    }\n}\n// A bridge fill is a delivery-tracking handle, not part of what the user signs,\n// so a type this SDK version predates must not fail the whole quote. Returning\n// a key-or-nothing spread leaves an unknown layer as an untracked route, the\n// same shape a layer that publishes no handle already produces.\nfunction mapBridgeFillFromWire(value) {\n    if (value === undefined)\n        return {};\n    switch (value.type) {\n        case 'OFT':\n        case 'ECO':\n        case 'RELAY':\n        case 'NEAR':\n        case 'RHINO':\n        case 'CCTP':\n        case 'LZ':\n            return { bridgeFill: value };\n        default:\n            return {};\n    }\n}\n// ---------------------------------------------------------------------------\n// Status\n// ---------------------------------------------------------------------------\nexport function mapIntentStatusFromWire(intentId, value) {\n    const input = value;\n    return {\n        traceId: input.traceId ?? '',\n        intentId: input.intentId ?? intentId,\n        purpose: input.purpose,\n        status: input.status,\n        // Absent stays absent: the record either identifies the accounts or it\n        // does not, and a fabricated zero address is not the same fact.\n        ...(input.accounts\n            ? { accounts: input.accounts }\n            : {}),\n        operations: (input.operations ?? []),\n        ...(input.refunds\n            ? { refunds: input.refunds }\n            : {}),\n        ...(input.details\n            ? { details: mapIntentDetailsFromWire(input.details) }\n            : {}),\n    };\n}\nfunction mapIntentDetailsFromWire(value) {\n    const leg = (entry) => ({\n        ...entry,\n        tokens: (entry?.tokens ?? []).map((token) => ({\n            ...token,\n            amount: BigInt(token.amount),\n        })),\n    });\n    return {\n        ...value,\n        source: value.source.map(leg),\n        destination: leg(value.destination),\n        cost: {\n            sponsored: value.cost.sponsored,\n            ...(value.cost.sponsoredValue === undefined\n                ? {}\n                : { sponsoredValue: BigInt(value.cost.sponsoredValue) }),\n            ...(value.cost.protocolFee === undefined\n                ? {}\n                : { protocolFee: BigInt(value.cost.protocolFee) }),\n            ...(value.cost.sponsorSurcharge === undefined\n                ? {}\n                : { sponsorSurcharge: BigInt(value.cost.sponsorSurcharge) }),\n        },\n    };\n}\n/**\n * Numeric chain id for the endpoints whose SDK projection is still numeric\n * (portfolio, splits). Wire-facing Caucasus metadata keeps its CAIP-2 string.\n */\nfunction parseNumericChainId(value) {\n    if (typeof value === 'number')\n        return value;\n    if (value === undefined)\n        throw new Error('Orchestrator chain id is missing');\n    if (/^\\d+$/u.test(value))\n        return Number(value);\n    return chainIdFromReference(parseCaip2(value));\n}\nfunction mapSettlementLayers(input) {\n    return input;\n}\nfunction mapQuoters(input) {\n    return input;\n}\n","import { chainIdFromCaip2 } from '../../chains/caip2.js';\nimport { UnsupportedSponsorshipApprovalError } from '../../errors/execution.js';\nfunction unsupported(field) {\n    throw new UnsupportedSponsorshipApprovalError({\n        reason: 'unsupported',\n        field,\n    });\n}\nfunction isObject(value) {\n    return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\nfunction object(value, field, allowed) {\n    if (!isObject(value))\n        unsupported(field);\n    for (const key of Object.keys(value)) {\n        if (!allowed.includes(key))\n            unsupported(field ? `${field}.${key}` : key);\n    }\n    return value;\n}\nfunction array(value, field) {\n    if (!Array.isArray(value))\n        unsupported(field);\n    return value;\n}\nfunction string(value, field) {\n    if (typeof value !== 'string')\n        unsupported(field);\n    return value;\n}\nfunction chainId(value, field) {\n    const id = chainIdFromCaip2(string(value, field));\n    if (id === undefined)\n        unsupported(field);\n    return id;\n}\n/** Re-keys a CAIP-2 map by decimal numeric chain id. */\nfunction byChainId(value, field) {\n    if (!isObject(value))\n        unsupported(field);\n    const result = {};\n    for (const [key, item] of Object.entries(value)) {\n        result[String(chainId(key, `${field}.${key}`))] = item;\n    }\n    return result;\n}\nfunction executions(value, field) {\n    return array(value, field).map((call, index) => {\n        object(call, `${field}.${index}`, ['to', 'value', 'data']);\n        return call;\n    });\n}\nfunction setupOps(value, field) {\n    return array(value, field).map((op, index) => {\n        object(op, `${field}.${index}`, ['to', 'data']);\n        return op;\n    });\n}\nfunction delegations(value, field) {\n    const entry = object(value, field, ['default', 'chains']);\n    // Per-chain delegations have no representation in the approval input, which\n    // only knows the chain-agnostic sentinel `0`.\n    if (entry.chains !== undefined)\n        unsupported(`${field}.chains`);\n    if (entry.default === undefined)\n        unsupported(`${field}.default`);\n    const contract = object(entry.default, `${field}.default`, ['contract']);\n    return {\n        0: { contract: string(contract.contract, `${field}.default.contract`) },\n    };\n}\n/** A typed EVM account or recipient, in the approval input's spelling. */\nfunction evmAccount(value, field, options) {\n    const signature = options.signatureMode ? ['signatureMode'] : [];\n    const entry = value.type === 'erc7579'\n        ? object(value, field, [\n            'type',\n            'address',\n            'initData',\n            'delegations',\n            'simulation',\n            ...signature,\n        ])\n        : value.type === 'eoa'\n            ? object(value, field, ['type', 'address', 'delegations', ...signature])\n            : unsupported(`${field}.type`);\n    const account = {\n        address: string(entry.address, `${field}.address`),\n        accountType: entry.type === 'eoa' ? 'EOA' : 'ERC7579',\n        setupOps: entry.initData === undefined\n            ? []\n            : setupOps(object(entry.initData, `${field}.initData`, ['setupOps']).setupOps, `${field}.initData.setupOps`),\n    };\n    if (entry.delegations !== undefined) {\n        account.delegations = delegations(entry.delegations, `${field}.delegations`);\n    }\n    if (entry.simulation !== undefined) {\n        const simulation = object(entry.simulation, `${field}.simulation`, [\n            'mockSignature',\n            'mockSignaturesByChain',\n        ]);\n        if (simulation.mockSignature !== undefined) {\n            unsupported(`${field}.simulation.mockSignature`);\n        }\n        if (simulation.mockSignaturesByChain !== undefined) {\n            account.mockSignatures = byChainId(simulation.mockSignaturesByChain, `${field}.simulation.mockSignaturesByChain`);\n        }\n    }\n    return {\n        account,\n        ...(entry.signatureMode === undefined\n            ? {}\n            : { signatureMode: entry.signatureMode }),\n    };\n}\nfunction evmRecipient(value, field) {\n    if (!isObject(value))\n        unsupported(field);\n    // A bare payee keeps the setup-free EOA spelling the released input gave it,\n    // so it reads exactly like a typed `eoa` recipient with no delegations.\n    if (value.type === undefined) {\n        return {\n            ...bareRecipient(value, field),\n            accountType: 'EOA',\n            setupOps: [],\n        };\n    }\n    return evmAccount(value, field, { signatureMode: false }).account;\n}\nfunction bareRecipient(value, field) {\n    return {\n        address: string(object(value, field, ['address']).address, `${field}.address`),\n    };\n}\nfunction swigAccount(value, field) {\n    const entry = object(value, field, [\n        'type',\n        'address',\n        'swigAccount',\n        'authorization',\n        'initData',\n    ]);\n    if (entry.type !== 'swig')\n        unsupported(`${field}.type`);\n    string(entry.address, `${field}.address`);\n    if (entry.swigAccount !== undefined) {\n        string(entry.swigAccount, `${field}.swigAccount`);\n    }\n    swigAuthority(entry.authorization, `${field}.authorization`);\n    if (entry.initData !== undefined) {\n        const init = object(entry.initData, `${field}.initData`, [\n            'authority',\n            'id',\n        ]);\n        const authority = object(init.authority, `${field}.initData.authority`, [\n            'kind',\n            'publicKey',\n        ]);\n        if (authority.kind !== 'secp256k1' && authority.kind !== 'secp256r1') {\n            unsupported(`${field}.initData.authority.kind`);\n        }\n        string(authority.publicKey, `${field}.initData.authority.publicKey`);\n        if (init.id !== undefined)\n            string(init.id, `${field}.initData.id`);\n    }\n    // Verbatim: the approval names the paying Swig exactly as the request does.\n    return entry;\n}\nfunction swigAuthority(value, field) {\n    if (!isObject(value))\n        unsupported(field);\n    if (value.kind === 'secp256k1') {\n        string(object(value, field, ['kind', 'address']).address, `${field}.address`);\n    }\n    else if (value.kind === 'secp256r1') {\n        string(object(value, field, ['kind', 'publicKey']).publicKey, `${field}.publicKey`);\n    }\n    else {\n        unsupported(`${field}.kind`);\n    }\n}\nfunction evmExecution(value, field, allowed) {\n    const execution = object(value, field, allowed);\n    const fields = {\n        destinationExecutions: executions(execution.calls, `${field}.calls`),\n    };\n    if (execution.gasLimit !== undefined) {\n        fields.destinationGasUnits = string(execution.gasLimit, `${field}.gasLimit`);\n    }\n    return fields;\n}\nfunction destination(value) {\n    if (!isObject(value))\n        unsupported('destination');\n    const common = (entry) => ({\n        destinationChainId: chainId(entry.chainId, 'destination.chainId'),\n        destinationExecutions: [],\n        tokenRequests: array(entry.tokenRequests, 'destination.tokenRequests').map((request, index) => {\n            object(request, `destination.tokenRequests.${index}`, [\n                'tokenAddress',\n                'amount',\n            ]);\n            return request;\n        }),\n    });\n    switch (value.vm) {\n        case 'evm': {\n            const entry = object(value, 'destination', [\n                'vm',\n                'chainId',\n                'recipient',\n                'tokenRequests',\n                'execution',\n            ]);\n            return {\n                fields: {\n                    ...common(entry),\n                    ...(entry.recipient === undefined\n                        ? {}\n                        : {\n                            recipient: evmRecipient(entry.recipient, 'destination.recipient'),\n                        }),\n                    ...(entry.execution === undefined\n                        ? {}\n                        : evmExecution(entry.execution, 'destination.execution', [\n                            'calls',\n                            'gasLimit',\n                        ])),\n                },\n            };\n        }\n        case 'svm': {\n            const entry = object(value, 'destination', [\n                'vm',\n                'chainId',\n                'recipient',\n                'tokenRequests',\n                'execution',\n            ]);\n            const fields = common(entry);\n            if (entry.recipient !== undefined) {\n                fields.recipient = bareRecipient(entry.recipient, 'destination.recipient');\n            }\n            if (entry.execution !== undefined) {\n                const execution = object(entry.execution, 'destination.execution', [\n                    'instructions',\n                    'addressLookupTables',\n                ]);\n                fields.destinationInstructions = array(execution.instructions, 'destination.execution.instructions');\n                if (execution.addressLookupTables !== undefined) {\n                    fields.addressLookupTableAddresses = array(execution.addressLookupTables, 'destination.execution.addressLookupTables');\n                }\n            }\n            return { fields };\n        }\n        case 'tvm':\n        case 'stellar': {\n            const entry = object(value, 'destination', [\n                'vm',\n                'chainId',\n                'recipient',\n                'tokenRequests',\n            ]);\n            return {\n                fields: {\n                    ...common(entry),\n                    recipient: bareRecipient(entry.recipient, 'destination.recipient'),\n                },\n            };\n        }\n        case 'hypercore': {\n            const entry = object(value, 'destination', [\n                'vm',\n                'chainId',\n                'recipient',\n                'tokenRequests',\n                'execution',\n            ]);\n            const fields = common(entry);\n            if (entry.recipient !== undefined) {\n                fields.recipient = evmRecipient(entry.recipient, 'destination.recipient');\n            }\n            let hyperCore;\n            if (entry.execution !== undefined) {\n                const execution = object(entry.execution, 'destination.execution', [\n                    'actions',\n                    'settlement',\n                ]);\n                if (execution.actions !== undefined) {\n                    const actions = array(execution.actions, 'destination.execution.actions');\n                    // The approval input carries a single `options.hyperCore.action`.\n                    if (actions.length !== 1) {\n                        unsupported('destination.execution.actions');\n                    }\n                    hyperCore = { action: actions[0] };\n                }\n                if (execution.settlement !== undefined) {\n                    Object.assign(fields, evmExecution(execution.settlement, 'destination.execution.settlement', ['calls', 'gasLimit']));\n                }\n            }\n            return { fields, ...(hyperCore ? { hyperCore } : {}) };\n        }\n        default:\n            return unsupported('destination.vm');\n    }\n}\nfunction onlyList(value, field) {\n    if (value === 'all')\n        return undefined;\n    const selector = object(value, field, ['only', 'except']);\n    if (selector.except !== undefined)\n        unsupported(`${field}.except`);\n    return array(selector.only, `${field}.only`).map((item, index) => string(item, `${field}.only.${index}`));\n}\nfunction sameSet(left, right) {\n    const a = new Set(left);\n    const b = new Set(right);\n    return a.size === b.size && [...a].every((item) => b.has(item));\n}\nfunction accessList(source) {\n    const limits = source.limits === undefined\n        ? []\n        : array(source.limits, 'source.limits').map((limit, index) => {\n            const entry = object(limit, `source.limits.${index}`, [\n                'chainId',\n                'tokenAddress',\n                'maxAmount',\n            ]);\n            return {\n                chainId: string(entry.chainId, `source.limits.${index}.chainId`),\n                tokenAddress: string(entry.tokenAddress, `source.limits.${index}.tokenAddress`),\n                maxAmount: string(entry.maxAmount, `source.limits.${index}.maxAmount`),\n            };\n        });\n    if (source.selection === undefined) {\n        if (limits.length > 0)\n            unsupported('source.limits');\n        return undefined;\n    }\n    const selection = object(source.selection, 'source.selection', [\n        'chains',\n        'tokens',\n        'perChain',\n    ]);\n    const chains = onlyList(selection.chains, 'source.selection.chains');\n    const tokens = onlyList(selection.tokens, 'source.selection.tokens');\n    if (selection.perChain === undefined) {\n        // A cap without a per-chain map has no approval-input spelling: a capped\n        // pair is always named in `chainTokenAmounts`.\n        if (limits.length > 0)\n            unsupported('source.limits');\n        if (!chains && !tokens)\n            return undefined;\n        return {\n            ...(chains\n                ? {\n                    chainIds: chains.map((chain, index) => chainId(chain, `source.selection.chains.only.${index}`)),\n                }\n                : {}),\n            ...(tokens ? { tokens } : {}),\n        };\n    }\n    const perChain = selection.perChain;\n    if (!isObject(perChain))\n        unsupported('source.selection.perChain');\n    const lists = Object.entries(perChain).map(([caip2, entry]) => {\n        const field = `source.selection.perChain.${caip2}`;\n        const list = onlyList(object(entry, field, ['tokens']).tokens, `${field}.tokens`);\n        if (!list)\n            unsupported(`${field}.tokens`);\n        return { caip2, id: chainId(caip2, field), tokens: list };\n    });\n    // The per-chain map is the whole allowlist; the global selectors must say\n    // exactly the same thing or they would carry a constraint the input lacks.\n    if (!chains ||\n        !sameSet(chains, lists.map(({ caip2 }) => caip2))) {\n        unsupported('source.selection.chains');\n    }\n    if (!tokens ||\n        !sameSet(tokens, lists.flatMap((list) => list.tokens))) {\n        unsupported('source.selection.tokens');\n    }\n    const caps = new Map();\n    for (const [index, limit] of limits.entries()) {\n        const key = `${limit.chainId}|${limit.tokenAddress}`;\n        const listed = lists\n            .find(({ caip2 }) => caip2 === limit.chainId)\n            ?.tokens.includes(limit.tokenAddress);\n        if (!listed || caps.has(key))\n            unsupported(`source.limits.${index}`);\n        caps.set(key, limit.maxAmount);\n    }\n    const chainTokens = {};\n    const chainTokenAmounts = {};\n    for (const { caip2, id, tokens: list } of lists) {\n        const uncapped = list.filter((token) => !caps.has(`${caip2}|${token}`));\n        // An empty list is still a named chain; a fully capped one is named by its\n        // caps alone.\n        if (uncapped.length > 0 || list.length === 0) {\n            chainTokens[String(id)] = uncapped;\n        }\n        for (const token of list) {\n            const cap = caps.get(`${caip2}|${token}`);\n            if (cap === undefined)\n                continue;\n            const amounts = (chainTokenAmounts[String(id)] ??= {});\n            amounts[token] = cap;\n        }\n    }\n    return {\n        ...(Object.keys(chainTokens).length > 0 ? { chainTokens } : {}),\n        ...(Object.keys(chainTokenAmounts).length > 0 ? { chainTokenAmounts } : {}),\n    };\n}\nfunction source(value) {\n    if (value === undefined)\n        return {};\n    const entry = object(value, 'source', [\n        'selection',\n        'limits',\n        'auxiliaryFunds',\n        'executions',\n    ]);\n    const list = accessList(entry);\n    const result = list ? { accountAccessList: list } : {};\n    if (entry.auxiliaryFunds !== undefined) {\n        result.auxiliaryFunds = byChainId(entry.auxiliaryFunds, 'source.auxiliaryFunds');\n    }\n    if (entry.executions !== undefined) {\n        const preClaim = {};\n        for (const [index, item] of array(entry.executions, 'source.executions').entries()) {\n            const field = `source.executions.${index}`;\n            const execution = object(item, field, ['vm', 'chainId', 'calls']);\n            if (execution.vm !== 'evm')\n                unsupported(`${field}.vm`);\n            const id = String(chainId(execution.chainId, `${field}.chainId`));\n            if (preClaim[id] !== undefined)\n                unsupported(`${field}.chainId`);\n            preClaim[id] = executions(execution.calls, `${field}.calls`);\n        }\n        result.preClaimExecutions = preClaim;\n    }\n    return result;\n}\nfunction options(value) {\n    if (value === undefined)\n        return {};\n    const entry = object(value, 'options', [\n        'appFees',\n        'protocolFees',\n        'customDeadline',\n        'sponsorship',\n        'settlementLayers',\n        'quoters',\n    ]);\n    const result = {};\n    for (const key of [\n        'appFees',\n        'protocolFees',\n        'customDeadline',\n        'settlementLayers',\n        'quoters',\n    ]) {\n        if (entry[key] !== undefined)\n            result[key] = entry[key];\n    }\n    // Renamed, not reshaped: an explicit `false` category is kept.\n    if (entry.sponsorship !== undefined) {\n        result.sponsorSettings = object(entry.sponsorship, 'options.sponsorship', [\n            'gas',\n            'bridgeFees',\n            'swapFees',\n            'protocolFees',\n        ]);\n    }\n    return result;\n}\nfunction account(value) {\n    const entry = object(value, 'account', ['evm', 'svm']);\n    const svm = entry.svm === undefined ? undefined : swigAccount(entry.svm, 'account.svm');\n    if (entry.evm !== undefined) {\n        if (!isObject(entry.evm))\n            unsupported('account.evm');\n        const evm = evmAccount(entry.evm, 'account.evm', { signatureMode: true });\n        return {\n            account: { ...evm.account, ...(svm ? { svm } : {}) },\n            ...(evm.signatureMode === undefined\n                ? {}\n                : { signatureMode: evm.signatureMode }),\n        };\n    }\n    if (!svm)\n        unsupported('account');\n    return { account: { address: svm.address, svm } };\n}\n/**\n * Derives the sponsorship approval input from a Caucasus `POST /quotes` body.\n *\n * Throws {@link UnsupportedSponsorshipApprovalError} on any field the approval\n * input cannot represent exactly.\n */\nexport function projectSponsorshipApproval(body) {\n    // Projected from the JSON that is sent, so an `undefined` member or a value\n    // `JSON.stringify` rewrites cannot make the two disagree.\n    const json = toJson(body);\n    const root = object(json, '', ['account', 'destination', 'source', 'options']);\n    const projectedAccount = account(root.account);\n    const projectedDestination = destination(root.destination);\n    const projectedSource = source(root.source);\n    const projectedOptions = options(root.options);\n    if (projectedAccount.signatureMode !== undefined) {\n        projectedOptions.signatureMode = projectedAccount.signatureMode;\n    }\n    if (projectedSource.auxiliaryFunds) {\n        projectedOptions.auxiliaryFunds = projectedSource.auxiliaryFunds;\n    }\n    if (projectedDestination.hyperCore) {\n        projectedOptions.hyperCore = projectedDestination.hyperCore;\n    }\n    return {\n        account: projectedAccount.account,\n        ...projectedDestination.fields,\n        ...(projectedSource.accountAccessList\n            ? { accountAccessList: projectedSource.accountAccessList }\n            : {}),\n        options: projectedOptions,\n        ...(projectedSource.preClaimExecutions\n            ? { preClaimExecutions: projectedSource.preClaimExecutions }\n            : {}),\n    };\n}\n/**\n * Refuses a quote whose approval input is not exactly the one derivable from\n * its body, so an integrator is never asked to approve something the\n * orchestrator would bind differently.\n */\nexport function assertSponsorshipApproval(body, intentInput) {\n    const projected = toJson(projectSponsorshipApproval(body));\n    const field = firstDifference(projected, toJson(intentInput), '');\n    if (field !== undefined) {\n        throw new UnsupportedSponsorshipApprovalError({\n            reason: 'mismatch',\n            ...(field ? { field } : {}),\n        });\n    }\n}\nfunction toJson(value) {\n    return JSON.parse(JSON.stringify(value));\n}\n/** Path of the first value that differs, or `undefined` when equal. */\nfunction firstDifference(left, right, path) {\n    const at = (key) => (path ? `${path}.${key}` : String(key));\n    if (Array.isArray(left) || Array.isArray(right)) {\n        if (!Array.isArray(left) || !Array.isArray(right))\n            return path;\n        if (left.length !== right.length)\n            return path;\n        for (const [index, item] of left.entries()) {\n            const difference = firstDifference(item, right[index], at(index));\n            if (difference !== undefined)\n                return difference;\n        }\n        return undefined;\n    }\n    if (isObject(left) || isObject(right)) {\n        if (!isObject(left) || !isObject(right))\n            return path;\n        const keys = [...new Set([...Object.keys(left), ...Object.keys(right)])];\n        for (const key of keys.sort()) {\n            if (!(key in left) || !(key in right))\n                return at(key);\n            const difference = firstDifference(left[key], right[key], at(key));\n            if (difference !== undefined)\n                return difference;\n        }\n        return undefined;\n    }\n    return left === right ? undefined : path;\n}\n","import { formatCaip2 } from '../../chains/caip2.js';\nimport { createOrchestratorAuth } from './auth.js';\nimport { ChainCatalog, parseChains } from './chain-catalog.js';\nimport { fetchOrchestratorJson } from './fetch.js';\nimport { mapIntentRequestToWire, mapIntentStatusFromWire, mapIntentSubmissionFromWire, mapPortfolioFromWire, mapQuoteResponseFromWire, mapSignedIntentToWire, mapSplitRequestToWire, mapSplitResultFromWire, } from './mappers.js';\nimport { assertSponsorshipApproval } from './sponsorship-approval.js';\nconst SDK_VERSION = '0.0.0-dev-20260925123020-2a6c3a5e2028247840cb9ebf04c05dbcd7d46787';\nconst API_VERSION = '2026-09.caucasus';\nexport function createOrchestratorClient(options) {\n    const fetchPort = options.fetch ?? globalThis.fetch;\n    const request = async (input) => {\n        const authHeaders = input.quoteContext\n            ? await options.auth.getQuoteHeaders(input.quoteContext.intentInput, input.quoteContext.sponsored)\n            : await options.auth.getHeaders();\n        return fetchOrchestratorJson({\n            fetch: fetchPort,\n            url: new URL(input.path, withTrailingSlash(options.url)).toString(),\n            init: {\n                method: input.method ?? 'GET',\n                headers: {\n                    'Content-Type': 'application/json',\n                    'x-sdk-version': SDK_VERSION,\n                    'x-api-version': API_VERSION,\n                    ...authHeaders,\n                    ...options.headers,\n                },\n                ...(input.body === undefined\n                    ? {}\n                    : { body: JSON.stringify(input.body) }),\n            },\n        });\n    };\n    // Memoized so the chain catalog is fetched at most once per client, lazily on\n    // first use — never at account construction.\n    let chainCatalogPromise;\n    return {\n        createQuote: async (input, context) => {\n            // One body object: the approval is checked against exactly the bytes\n            // that are sent, before the integrator is asked for a grant.\n            const body = mapIntentRequestToWire(input);\n            if (context && options.auth.requestsIntentExtension(context.sponsored)) {\n                assertSponsorshipApproval(body, context.intentInput);\n            }\n            return mapQuoteResponseFromWire(await request({\n                path: 'quotes',\n                method: 'POST',\n                body,\n                ...(context ? { quoteContext: context } : {}),\n            }));\n        },\n        // Never carries the intent extension: the grant was presented with the\n        // quote and is single-use, so the submission bills from the quoted fees.\n        submitIntent: async (input) => mapIntentSubmissionFromWire(input.intentId, await request({\n            path: 'intents',\n            method: 'POST',\n            body: mapSignedIntentToWire(input),\n        })),\n        getIntentStatus: async (intentId, options) => mapIntentStatusFromWire(intentId, await request({\n            path: `intents/${encodeURIComponent(intentId)}${options?.full ? '?full=true' : ''}`,\n        })),\n        splitIntents: async (input) => mapSplitResultFromWire(await request({\n            path: 'intents/splits',\n            method: 'POST',\n            body: mapSplitRequestToWire(input),\n        })),\n        getPortfolio: async (input) => {\n            const params = new URLSearchParams();\n            for (const chainId of input.chainIds ?? []) {\n                params.append('chainIds', formatCaip2(chainId));\n            }\n            for (const [chainId, tokens] of Object.entries(input.tokens ?? {})) {\n                for (const token of tokens) {\n                    params.append('tokens', `${formatCaip2(Number(chainId))}:${token}`);\n                }\n            }\n            const suffix = params.size > 0 ? `?${params}` : '';\n            return mapPortfolioFromWire(await request({\n                path: `accounts/${input.account}/portfolio${suffix}`,\n            }));\n        },\n        getAppFeeBalances: async () => {\n            const value = (await request({ path: 'app-fees/balances' }));\n            return {\n                withdrawableUsd: value.withdrawableUsd ?? 0,\n                pendingUsd: value.pendingUsd ?? 0,\n            };\n        },\n        getChainCatalog: () => {\n            chainCatalogPromise ??= (async () => {\n                const json = (await request({ path: 'chains' }));\n                return new ChainCatalog(parseChains(json));\n            })();\n            return chainCatalogPromise;\n        },\n    };\n}\nexport function createConfiguredOrchestratorClient(config, fetch) {\n    return createOrchestratorClient({\n        url: config.orchestratorUrl,\n        auth: createOrchestratorAuth(config.auth),\n        headers: config.headers,\n        ...(fetch ? { fetch } : {}),\n    });\n}\nfunction withTrailingSlash(value) {\n    return value.endsWith('/') ? value : `${value}/`;\n}\n","import { custom } from 'viem';\nimport { createPaymasterClient as createViemPaymasterClient, entryPoint07Address, } from 'viem/account-abstraction';\nimport { requestJsonRpc } from '../json-rpc.js';\nimport { resolvePaymasterUrl } from './endpoints.js';\nexport function createPaymasterClient(input) {\n    const fetchPort = input.fetch ?? globalThis.fetch;\n    const client = (chainId) => createViemPaymasterClient({\n        transport: custom({\n            request: ({ method, params }) => requestJsonRpc({\n                fetch: fetchPort,\n                url: resolvePaymasterUrl(chainId, input.endpoint),\n                method,\n                params: params ?? [],\n            }),\n        }),\n    });\n    return {\n        getStubData: async (chain, operation) => {\n            const { isFinal = false, sponsor: _, ...stub } = await client(chain.id).getPaymasterStubData({\n                ...operation,\n                chainId: chain.id,\n                entryPointAddress: entryPoint07Address,\n            });\n            return { ...requireV07(stub), isFinal };\n        },\n        getData: async (chain, operation) => requireV07(await client(chain.id).getPaymasterData({\n            ...operation,\n            chainId: chain.id,\n            entryPointAddress: entryPoint07Address,\n        })),\n    };\n}\nfunction requireV07(value) {\n    if (!value.paymaster || !value.paymasterData) {\n        throw new Error('Paymaster response is missing paymaster fields');\n    }\n    return value;\n}\n","export function resolvePaymasterUrl(chainId, endpoint) {\n    switch (endpoint.kind) {\n        case 'pimlico':\n            return `https://api.pimlico.io/v2/${chainId}/rpc?apikey=${endpoint.apiKey}`;\n        case 'biconomy':\n            return `https://paymaster.biconomy.io/api/v2/${chainId}/${endpoint.apiKey}`;\n        case 'custom': {\n            const url = typeof endpoint.urls === 'string'\n                ? endpoint.urls\n                : endpoint.urls[chainId];\n            if (!url)\n                throw new Error(`No paymaster URL configured for chain ${chainId}`);\n            return url;\n        }\n    }\n}\n","import { createPublicClient } from 'viem';\nimport { getChainById } from '../../chains/catalog.js';\nimport { createRpcTransport } from './transport.js';\nexport function createRpcReadPort(chain, provider) {\n    const client = createPublicClient({\n        chain,\n        transport: createRpcTransport(chain.id, provider),\n    });\n    const read = async (request, blockNumber) => client.readContract({\n        address: request.address,\n        abi: request.abi,\n        functionName: request.functionName,\n        ...(request.args ? { args: request.args } : {}),\n        ...(blockNumber === undefined ? {} : { blockNumber }),\n    });\n    return {\n        getCode: async (context, address) => ({\n            code: await client.getCode({\n                address,\n                ...(context.blockNumber === undefined\n                    ? {}\n                    : { blockNumber: context.blockNumber }),\n            }),\n        }),\n        getTransactionCount: async (context, address) => BigInt(await client.getTransactionCount({\n            address,\n            ...(context.blockNumber === undefined\n                ? {}\n                : { blockNumber: context.blockNumber }),\n        })),\n        readContract: (context, request) => read(request, context.blockNumber),\n        multicall: async (context, requests) => {\n            if (requests.length === 0)\n                return [];\n            const results = await client.multicall({\n                contracts: requests.map((request) => ({\n                    address: request.address,\n                    abi: request.abi,\n                    functionName: request.functionName,\n                    ...(request.args ? { args: request.args } : {}),\n                })),\n                allowFailure: true,\n                batchSize: 0,\n                ...(context.blockNumber === undefined\n                    ? {}\n                    : { blockNumber: context.blockNumber }),\n            });\n            return results.map((result) => result.status === 'success'\n                ? { result: result.result }\n                : { error: result.error });\n        },\n    };\n}\nexport function createRpcPort(provider) {\n    const readers = new Map();\n    return {\n        forChain: (chain) => {\n            const existing = readers.get(chain.id);\n            if (existing)\n                return existing;\n            const reader = createRpcReadPort(getChainById(chain.id), provider);\n            readers.set(chain.id, reader);\n            return reader;\n        },\n    };\n}\n","import { encodeAbiParameters } from 'viem';\nimport { moduleTypeId } from './erc7579-abi.js';\nimport { ENS_HCA_MODULE } from './validators/ens.js';\nimport { OWNABLE_VALIDATOR_ADDRESS } from './validators/ownable.js';\nconst sentinel = '0x0000000000000000000000000000000000000001';\nconst paginationAbi = (name) => [\n    {\n        name,\n        type: 'function',\n        inputs: [\n            { name: 'cursor', type: 'address' },\n            { name: 'size', type: 'uint256' },\n        ],\n        outputs: [\n            { name: 'array', type: 'address[]' },\n            { name: 'next', type: 'address' },\n        ],\n        stateMutability: 'view',\n    },\n];\nexport async function readInstalledModules(input) {\n    if (input.accountKind === 'eoa')\n        return [];\n    if (input.accountKind === 'kernel')\n        throw new Error('Kernel not supported');\n    const functionName = input.kind === 'validator'\n        ? 'getValidatorsPaginated'\n        : 'getExecutorsPaginated';\n    const result = await input.rpc.readContract({ chain: input.chain }, {\n        address: input.account,\n        abi: paginationAbi(functionName),\n        functionName,\n        args: [sentinel, 100n],\n    });\n    return result[0];\n}\nexport async function readValidatorInitialized(input) {\n    return input.rpc.readContract({ chain: input.chain }, {\n        address: input.validator,\n        abi: [\n            {\n                name: 'isInitialized',\n                type: 'function',\n                stateMutability: 'view',\n                inputs: [{ name: 'smartAccount', type: 'address' }],\n                outputs: [{ name: '', type: 'bool' }],\n            },\n        ],\n        functionName: 'isInitialized',\n        args: [input.account],\n    });\n}\nconst validatorThresholdAbi = [\n    {\n        name: 'threshold',\n        type: 'function',\n        stateMutability: 'view',\n        inputs: [{ name: 'account', type: 'address' }],\n        outputs: [{ name: '', type: 'uint256' }],\n    },\n];\nconst validatorOwnersAbi = [\n    {\n        name: 'getOwners',\n        type: 'function',\n        stateMutability: 'view',\n        inputs: [{ name: 'account', type: 'address' }],\n        outputs: [{ name: 'ownersArray', type: 'address[]' }],\n    },\n];\n/**\n * Reads an ownable-style validator's owner list and threshold.\n *\n * The owner list is returned in the validator's own linked-list order, which\n * callers need to derive the `prevOwner` argument for removals.\n */\nexport async function readValidatorOwnership(input) {\n    const [owners, threshold] = await input.rpc.multicall({ chain: input.chain }, [\n        {\n            address: input.validator,\n            abi: validatorOwnersAbi,\n            functionName: 'getOwners',\n            args: [input.account],\n        },\n        {\n            address: input.validator,\n            abi: validatorThresholdAbi,\n            functionName: 'threshold',\n            args: [input.account],\n        },\n    ]);\n    if (!owners.result || threshold.result === undefined) {\n        throw new Error('Failed to read existing owners or threshold');\n    }\n    return {\n        owners: owners.result.map((owner) => owner.toLowerCase()),\n        threshold: Number(threshold.result),\n    };\n}\n/** Reads a validator's signature threshold for an account. */\nexport async function readValidatorThreshold(input) {\n    const threshold = await input.rpc.readContract({ chain: input.chain }, {\n        address: input.validator,\n        abi: validatorThresholdAbi,\n        functionName: 'threshold',\n        args: [input.account],\n    });\n    return Number(threshold);\n}\nconst moduleInstalledAbi = [\n    {\n        type: 'function',\n        name: 'isModuleInstalled',\n        inputs: [\n            { type: 'uint256', name: 'moduleTypeId' },\n            { type: 'address', name: 'module' },\n            { type: 'bytes', name: 'additionalContext' },\n        ],\n        outputs: [{ type: 'bool', name: 'isInstalled' }],\n        stateMutability: 'view',\n    },\n];\nexport async function readModuleInstallations(input) {\n    const results = await input.rpc.multicall({ chain: input.chain }, input.modules.map((module) => ({\n        address: input.account,\n        abi: moduleInstalledAbi,\n        functionName: 'isModuleInstalled',\n        args: [\n            moduleTypeId(module.kind),\n            module.address,\n            module.additionalContext,\n        ],\n    })));\n    return results.map(({ result }) => result === true);\n}\nexport async function readOwners(input) {\n    let validator = input.ownerValidator ?? OWNABLE_VALIDATOR_ADDRESS;\n    if (input.accountKind === 'hca') {\n        validator = input.hcaFactory\n            ? await input.rpc.readContract({ chain: input.chain }, {\n                address: input.hcaFactory,\n                abi: [\n                    {\n                        name: 'initDataParser',\n                        type: 'function',\n                        stateMutability: 'view',\n                        inputs: [],\n                        outputs: [{ name: '', type: 'address' }],\n                    },\n                ],\n                functionName: 'initDataParser',\n            })\n            : ENS_HCA_MODULE;\n    }\n    const results = await input.rpc.multicall({ chain: input.chain }, [\n        {\n            address: validator,\n            abi: [\n                {\n                    name: 'getOwners',\n                    type: 'function',\n                    inputs: [{ name: 'account', type: 'address' }],\n                    outputs: [{ name: '', type: 'address[]' }],\n                    stateMutability: 'view',\n                },\n            ],\n            functionName: 'getOwners',\n            args: [input.account],\n        },\n        {\n            address: validator,\n            abi: [\n                {\n                    name: 'threshold',\n                    type: 'function',\n                    inputs: [{ name: 'module', type: 'address' }],\n                    outputs: [{ name: '', type: 'uint256' }],\n                    stateMutability: 'view',\n                },\n            ],\n            functionName: 'threshold',\n            args: [input.account],\n        },\n    ]);\n    const [owners, threshold] = results;\n    if (owners.error ||\n        threshold.error ||\n        !owners.result ||\n        threshold.result === undefined) {\n        return null;\n    }\n    return { accounts: owners.result, threshold: Number(threshold.result) };\n}\nexport function encodeAccountModuleDeInitData(input) {\n    if (input.module.kind !== 'validator' ||\n        !['nexus', 'safe', 'startale'].includes(input.accountKind)) {\n        return input.module.deInitData;\n    }\n    const index = input.installed.findIndex((address) => address.toLowerCase() === input.module.address.toLowerCase());\n    if (index < 0)\n        return input.module.deInitData;\n    return encodeAbiParameters([{ type: 'address' }, { type: 'bytes' }], [\n        index === 0 ? sentinel : input.installed[index - 1],\n        input.module.deInitData,\n    ]);\n}\n","import { hashStruct, maxUint256, } from 'viem';\nimport { getSessionData } from './digest.js';\nimport { getSmartSessionEmissaryAddress } from './module.js';\nimport { SMART_SESSIONS_FALLBACK_TARGET_FLAG, SMART_SESSIONS_FALLBACK_TARGET_SELECTOR_FLAG, } from './resolve.js';\nexport const SESSION_LOCK_TAG = '0x000000000000000000000000';\nexport const types = {\n    PolicyData: [\n        { name: 'policy', type: 'address' },\n        { name: 'initData', type: 'bytes' },\n    ],\n    ActionData: [\n        { name: 'actionTargetSelector', type: 'bytes4' },\n        { name: 'actionTarget', type: 'address' },\n        { name: 'actionPolicies', type: 'PolicyData[]' },\n    ],\n    ERC7739Context: [\n        { name: 'appDomainSeparator', type: 'bytes32' },\n        { name: 'contentName', type: 'string[]' },\n    ],\n    ERC7739Data: [\n        { name: 'allowedERC7739Content', type: 'ERC7739Context[]' },\n        { name: 'erc1271Policies', type: 'PolicyData[]' },\n    ],\n    LockTagData: [\n        { name: 'lockTag', type: 'bytes12' },\n        { name: 'claimPolicies', type: 'PolicyData[]' },\n    ],\n    SignedPermissions: [\n        { name: 'actions', type: 'ActionData[]' },\n        { name: 'erc7739Policies', type: 'ERC7739Data' },\n        { name: 'lockTagPolicies', type: 'LockTagData' },\n        { name: 'permitGenericPolicy', type: 'bool' },\n    ],\n    SignedSession: [\n        { name: 'account', type: 'address' },\n        { name: 'expires', type: 'uint256' },\n        { name: 'nonce', type: 'uint256' },\n        { name: 'permissions', type: 'SignedPermissions' },\n        { name: 'salt', type: 'bytes32' },\n        { name: 'sessionValidator', type: 'address' },\n        { name: 'sessionValidatorInitData', type: 'bytes' },\n        { name: 'smartSessionEmissary', type: 'address' },\n    ],\n    ChainSession: [\n        { name: 'chainId', type: 'uint64' },\n        { name: 'session', type: 'SignedSession' },\n    ],\n    MultiChainSession: [{ name: 'sessionsAndChainIds', type: 'ChainSession[]' }],\n};\nfunction signedSession(account, data, nonce, environment) {\n    return {\n        account,\n        permissions: {\n            permitGenericPolicy: data.actions.some((action) => action.actionTarget === SMART_SESSIONS_FALLBACK_TARGET_FLAG &&\n                action.actionTargetSelector ===\n                    SMART_SESSIONS_FALLBACK_TARGET_SELECTOR_FLAG),\n            lockTagPolicies: {\n                lockTag: SESSION_LOCK_TAG,\n                claimPolicies: data.claimPolicies,\n            },\n            erc7739Policies: {\n                allowedERC7739Content: data.erc7739Policies.allowedERC7739Content.map((content) => ({\n                    contentName: content.contentNames,\n                    appDomainSeparator: content.appDomainSeparator,\n                })),\n                erc1271Policies: data.erc7739Policies.erc1271Policies,\n            },\n            actions: data.actions,\n        },\n        sessionValidator: data.sessionValidator,\n        sessionValidatorInitData: data.sessionValidatorInitData,\n        salt: data.salt,\n        smartSessionEmissary: getSmartSessionEmissaryAddress(environment),\n        expires: maxUint256,\n        nonce,\n    };\n}\nexport async function getSessionDetails(input) {\n    const nonces = await Promise.all(input.sessions.map(input.readNonce));\n    const signed = input.sessions.map((session, index) => signedSession(input.account, getSessionData(session), nonces[index], input.environment));\n    const hashesAndChainIds = signed.map((session, index) => ({\n        chainId: BigInt(input.sessions[index].chain.id),\n        sessionDigest: hashStruct({\n            types,\n            primaryType: 'SignedSession',\n            data: session,\n        }),\n    }));\n    const data = {\n        domain: { name: 'SmartSessionEmissary', version: '1' },\n        types,\n        primaryType: 'MultiChainSession',\n        message: {\n            sessionsAndChainIds: signed.map((session, index) => ({\n                chainId: BigInt(input.sessions[index].chain.id),\n                session,\n            })),\n        },\n    };\n    return { nonces, hashesAndChainIds, data };\n}\n","import { getPermissionId } from './digest.js';\nimport { getSmartSessionEmissaryAddress } from './module.js';\nconst permissionEnabledAbi = [\n    {\n        type: 'function',\n        name: 'isPermissionEnabled',\n        inputs: [\n            { name: 'account', type: 'address' },\n            { name: 'permissionId', type: 'bytes32' },\n        ],\n        outputs: [{ name: 'isEnabled', type: 'bool' }],\n        stateMutability: 'view',\n    },\n];\nconst nonceAbi = [\n    {\n        type: 'function',\n        name: 'getNonce',\n        inputs: [\n            { name: 'sponsor', type: 'address' },\n            { name: 'lockTag', type: 'bytes12' },\n        ],\n        outputs: [{ name: '', type: 'uint256' }],\n        stateMutability: 'view',\n    },\n];\nexport async function readSessionEnabled(input) {\n    return input.rpc.readContract({ chain: input.chain }, {\n        address: getSmartSessionEmissaryAddress(input.environment),\n        abi: permissionEnabledAbi,\n        functionName: 'isPermissionEnabled',\n        args: [input.account, getPermissionId(input.session)],\n    });\n}\nexport async function readSessionNonce(input) {\n    return input.rpc.readContract({ chain: input.chain }, {\n        address: getSmartSessionEmissaryAddress(input.environment),\n        abi: nonceAbi,\n        functionName: 'getNonce',\n        args: [input.account, input.lockTag],\n    });\n}\n","import { isAddressEqual } from 'viem';\nimport { getValidatorCapabilities } from '../modules/validators/capabilities.js';\nimport { resolveValidator } from '../modules/validators/resolve.js';\nimport { ecdsaSignerId } from '../modules/validators/signer-id.js';\nimport { webauthnStatelessCodecContext } from '../modules/validators/webauthn.js';\nimport { signingTopology } from './plan.js';\nconst zeroAddress = '0x0000000000000000000000000000000000000000';\nexport function createAccountSigningContext(input) {\n    const validator = input.selection?.validator ??\n        input.runtime.construction.owner ??\n        eoaValidator(input.runtime);\n    const module = input.selection?.validator === undefined &&\n        input.runtime.construction.owner === undefined\n        ? {\n            kind: 'validator',\n            address: zeroAddress,\n            initData: '0x',\n            deInitData: '0x',\n            additionalContext: '0x',\n        }\n        : resolveValidator(validator);\n    const signerReferences = Object.fromEntries(validatorOwners(validator).map((owner) => [\n        owner.signerId,\n        {\n            id: owner.signerId,\n            kind: owner.kind === 'webauthn'\n                ? 'webauthn'\n                : 'ecdsa',\n        },\n    ]));\n    const topology = input.selection?.validator === undefined &&\n        input.runtime.construction.owner === undefined\n        ? {\n            configuredTopology: {\n                rootValidatorId: 'eoa',\n                validators: [],\n                threshold: 1,\n            },\n            effectiveSelection: {\n                validatorIds: [],\n                signerIds: Object.keys(signerReferences),\n                threshold: 1,\n            },\n        }\n        : signingTopology(validator, input.selection?.signerIds);\n    return {\n        account: input.runtime.identity,\n        accountAdapter: input.runtime.adapter,\n        accountCapabilities: input.runtime.adapter.capabilities,\n        validator,\n        validatorCapabilities: getValidatorCapabilities(validator, module, input.runtime.construction.account.kind, input.purpose, input.runtime.adapter.capabilities.supportsOriginSignatureReuse),\n        effectiveSigners: topology.effectiveSelection,\n        signerReferences,\n        signerInvoker: input.signerInvoker,\n    };\n}\nexport function getSigningValidatorCodec(context, payloadKind) {\n    const codec = context.validatorCapabilities.contributionCodec;\n    const normalizedCodec = payloadKind === 'typed-data' && codec.kind === 'ordered-threshold'\n        ? { ...codec, recoveryEncoding: 'ethereum' }\n        : codec;\n    if (context.validator.kind !== 'passkey' ||\n        normalizedCodec.kind !== 'ordered-threshold') {\n        return normalizedCodec;\n    }\n    return {\n        ...normalizedCodec,\n        webauthn: {\n            account: context.account.address,\n            usePrecompile: false,\n            format: 'current',\n        },\n    };\n}\nexport function getSigningValidatorFactors(context, payloadKind) {\n    if (context.validator.kind !== 'multi-factor')\n        return [];\n    return context.validator.validators.map((factor) => {\n        const module = resolveValidator(factor);\n        const codec = getValidatorCapabilities(factor, module, context.account.definition.kind, context.validatorCapabilities.compatibilityKey.purpose, context.accountCapabilities.supportsOriginSignatureReuse).contributionCodec;\n        const normalizedCodec = payloadKind === 'typed-data' && codec.kind === 'ordered-threshold'\n            ? { ...codec, recoveryEncoding: 'ethereum' }\n            : codec;\n        if (normalizedCodec.kind !== 'ordered-threshold') {\n            throw new Error(`Multi-factor validator ${factor.id} is not atomic`);\n        }\n        return {\n            id: factor.id,\n            publicId: factor.publicId,\n            validator: module.address,\n            codec: factor.kind === 'passkey'\n                ? {\n                    ...normalizedCodec,\n                    webauthn: webauthnStatelessCodecContext(factor),\n                }\n                : normalizedCodec,\n        };\n    });\n}\nexport function getAccountSignatureRoute(runtime, context, erc7739 = { kind: 'none' }, payloadKind = 'message') {\n    const deployment = runtime.adapter.getDeploymentPlan(runtime.construction);\n    let erc6492 = { kind: 'none' };\n    if (!deployment.deployed) {\n        if (!deployment.factory || !deployment.factoryData) {\n            throw new Error('Account factory arguments are unavailable');\n        }\n        erc6492 = {\n            kind: 'wrap-deployless',\n            factory: deployment.factory,\n            factoryData: deployment.factoryData,\n        };\n    }\n    return {\n        validatorCodec: getSigningValidatorCodec(context, payloadKind),\n        ...(context.validator.kind === 'multi-factor'\n            ? { validatorFactors: getSigningValidatorFactors(context, payloadKind) }\n            : {}),\n        erc7739,\n        accountEnvelope: getAccountSignatureEnvelope(context),\n        erc6492,\n    };\n}\nexport function getAccountSignatureEnvelope(context) {\n    const envelope = context.accountCapabilities.signatureEnvelope;\n    if (envelope.kind === 'none' || envelope.kind === 'hca')\n        return envelope;\n    const validator = context.validatorCapabilities.compatibilityKey.moduleAddress;\n    return envelope.kind === 'kernel'\n        ? {\n            ...envelope,\n            validator,\n            isRoot: isAddressEqual(validator, envelope.validator),\n        }\n        : { ...envelope, validator };\n}\nfunction eoaValidator(runtime) {\n    const account = runtime.construction.eoa;\n    if (!account)\n        throw new Error('EOA account signer is missing');\n    return {\n        kind: 'ecdsa',\n        id: 'eoa',\n        publicId: 0,\n        module: { source: 'explicit', address: zeroAddress },\n        owners: [\n            {\n                kind: 'ecdsa',\n                id: 'eoa/owner/0',\n                signerId: ecdsaSignerId(account),\n                account,\n            },\n        ],\n        threshold: 1,\n    };\n}\nfunction validatorOwners(validator) {\n    return validator.kind === 'multi-factor'\n        ? validator.validators.flatMap(({ owners }) => owners)\n        : validator.owners;\n}\n","import { ENS_HCA_MODULE } from './ens.js';\nimport { K1_DEFAULT_VALIDATOR_ADDRESS } from './k1.js';\nimport { OWNABLE_BETA_VALIDATOR_ADDRESS, OWNABLE_V0_VALIDATOR_ADDRESS, OWNABLE_VALIDATOR_ADDRESS, } from './ownable.js';\nexport function getValidatorCapabilities(definition, module, accountProfile, purpose, supportsOriginReuse) {\n    const nested = definition.kind === 'multi-factor';\n    const legacyOwnable = [\n        OWNABLE_V0_VALIDATOR_ADDRESS.toLowerCase(),\n        OWNABLE_BETA_VALIDATOR_ADDRESS.toLowerCase(),\n    ].includes(module.address.toLowerCase());\n    const validatorRecovery = purpose !== 'user-operation' &&\n        [OWNABLE_VALIDATOR_ADDRESS, ENS_HCA_MODULE]\n            .map((address) => address.toLowerCase())\n            .includes(module.address.toLowerCase())\n        ? 'validator-offset-4'\n        : 'ethereum';\n    return {\n        compatibilityKey: {\n            validatorKind: definition.kind,\n            moduleAddress: module.address,\n            accountProfile,\n            purpose,\n        },\n        payloadKinds: [\n            'message',\n            'typed-data',\n            'intent',\n            'user-operation',\n            'session-enable',\n        ],\n        signatureModes: ['owner'],\n        signerTopology: nested\n            ? 'nested-threshold'\n            : definition.kind === 'quorum' || definition.owners.length > 1\n                ? 'threshold'\n                : 'single',\n        supportsIndependentSigning: definition.kind !== 'smart-session' &&\n            module.address.toLowerCase() !==\n                K1_DEFAULT_VALIDATOR_ADDRESS.toLowerCase(),\n        supportsOriginReuse,\n        supportsMockSignature: true,\n        supportsEip712: !legacyOwnable,\n        recoveryEncoding: validatorRecovery,\n        contributionCodec: nested\n            ? {\n                kind: 'nested-threshold',\n                validator: module,\n                factorOrder: definition.validators.map((factor) => factor.id),\n                threshold: definition.threshold,\n            }\n            : definition.kind === 'quorum'\n                ? {\n                    kind: 'weighted-quorum',\n                    validator: module,\n                    owners: definition.owners.map((owner) => {\n                        if (owner.kind === 'webauthn' || owner.weight === undefined) {\n                            throw new Error('Quorum validator requires weighted ECDSA owners');\n                        }\n                        return {\n                            ownerId: owner.id,\n                            signer: owner.account.address,\n                            weight: owner.weight,\n                        };\n                    }),\n                    thresholdWeight: requireQuorumThreshold(definition),\n                }\n                : {\n                    kind: 'ordered-threshold',\n                    validator: module,\n                    ownerOrder: definition.owners.map((owner) => owner.id),\n                    threshold: definition.threshold,\n                    recoveryEncoding: validatorRecovery,\n                },\n    };\n}\nfunction requireQuorumThreshold(definition) {\n    if (definition.kind !== 'quorum' ||\n        definition.thresholdWeight === undefined) {\n        throw new Error('Quorum validator threshold weight is missing');\n    }\n    return definition.thresholdWeight;\n}\n","import { encodeAbiParameters, hashTypedData, keccak256, } from 'viem';\nimport { toEvmChainReference } from '../chains/caip2.js';\nimport { executeSigningPlan } from './execute.js';\nexport function createNexusEip7702InitTypedData(input) {\n    return {\n        domain: { name: 'Nexus', version: '1.2.0' },\n        types: {\n            Initialize: [\n                { name: 'nexus', type: 'address' },\n                { name: 'chainIds', type: 'uint256[]' },\n                { name: 'initData', type: 'bytes' },\n            ],\n        },\n        primaryType: 'Initialize',\n        message: {\n            nexus: input.contract,\n            chainIds: [0n],\n            initData: input.initData,\n        },\n    };\n}\nexport function createNexusEip7702InitPlan(input) {\n    const payloadId = hashTypedData(input.typedData);\n    return directSigningPlan({\n        kind: 'nexus-eip7702-init',\n        payload: { kind: 'typed-data', id: payloadId },\n        stageId: 'nexus-eip7702-init',\n        task: {\n            id: 'nexus-eip7702-init-signer',\n            signer: input.signer,\n            role: 'owner',\n            invocationKind: 'ecdsa-sign-typed-data',\n            payload: { source: 'plan-payload', payloadId },\n        },\n        artifactId: 'nexus-eip7702-init-signature',\n    });\n}\nexport async function signNexusEip7702Init(input) {\n    const plan = createNexusEip7702InitPlan(input.planInput);\n    const transcript = await executeDirectPlan({\n        plan,\n        payloads: {\n            [plan.payload.id]: {\n                kind: 'typed-data',\n                typedData: input.planInput.typedData,\n            },\n        },\n        signerInvoker: input.signerInvoker,\n        checkpoints: input.checkpoints,\n        artifactId: 'nexus-eip7702-init-signature',\n    });\n    const signature = transcript.stages[0].outputs['nexus-eip7702-init-signature'];\n    return { signature, transcript };\n}\nexport function createAuthorizationListPlan(input) {\n    const chains = dedupeEvmChains(input.chains);\n    const payloadId = keccak256(encodeAbiParameters([{ type: 'address' }, { type: 'uint256[]' }], [input.contract, chains.map(({ id }) => BigInt(id))]));\n    const payloads = {};\n    const stages = chains.map((chain) => {\n        const nonce = input.nonceByChain[chain.id];\n        if (nonce === undefined) {\n            throw new Error(`Authorization nonce for chain ${chain.id} is missing`);\n        }\n        const chainPayloadId = keccak256(encodeAbiParameters([{ type: 'bytes32' }, { type: 'uint256' }], [payloadId, BigInt(chain.id)]));\n        payloads[chainPayloadId] = {\n            kind: 'authorization',\n            authorization: {\n                contractAddress: input.contract,\n                chainId: chain.id,\n                nonce,\n            },\n        };\n        const taskId = `authorization-${chain.id}`;\n        const factId = `delegation-${chain.id}`;\n        return {\n            id: `authorization-chain-${chain.id}`,\n            checkpoint: {\n                kind: 'delegation-code',\n                id: factId,\n                chain,\n                account: input.account,\n            },\n            priorOutputs: [],\n            taskTemplates: [\n                {\n                    id: taskId,\n                    signer: input.signer,\n                    role: 'authorization',\n                    chain,\n                    invocationKind: 'sign-authorization',\n                    payload: {\n                        source: 'plan-payload',\n                        payloadId: chainPayloadId,\n                    },\n                    when: {\n                        kind: 'delegation-required',\n                        factId,\n                        contract: input.contract,\n                    },\n                    contribution: { kind: 'authorization' },\n                },\n            ],\n            schedule: [\n                {\n                    id: `authorization-prompt-${chain.id}`,\n                    execution: 'serial',\n                    taskIds: [taskId],\n                },\n            ],\n            artifacts: [],\n        };\n    });\n    const plan = {\n        version: 1,\n        kind: 'eip7702-authorization-list',\n        payload: { kind: 'authorization', id: payloadId },\n        configuredTopology: emptyTopology,\n        effectiveSelection: emptySelection,\n        stages,\n        publicOutputs: stages.map((stage) => ({\n            id: `${stage.id}-result`,\n            source: { kind: 'task-result', taskId: stage.taskTemplates[0].id },\n            exposedForIndependentSigning: false,\n        })),\n    };\n    return { plan, payloads };\n}\nexport async function signAuthorizationList(input) {\n    const { plan, payloads } = createAuthorizationListPlan(input.planInput);\n    const transcript = await executeSigningPlan({\n        plan,\n        payloads,\n        signerInvoker: input.signerInvoker,\n        checkpoints: input.checkpoints,\n        assembleStage: () => ({}),\n    });\n    const authorizations = transcript.stages.flatMap(({ results }) => Object.values(results).flatMap((result) => result.kind === 'signed-authorization' ? [result.authorization] : []));\n    return { authorizations, transcript };\n}\n/**\n * Signs the delegations a quote explicitly asked for, in the order it asked.\n *\n * Unlike {@link createAuthorizationListPlan} this has no delegation-code\n * condition and derives no chain set of its own: the quote named these\n * authorisations, so producing fewer than it asked for submits an incomplete\n * proof vector rather than a cheaper one.\n */\nexport function createRequestedDelegationPlan(input) {\n    const payloads = {};\n    const stages = input.delegations.map((delegation, index) => {\n        const payloadId = keccak256(encodeAbiParameters([{ type: 'address' }, { type: 'uint256' }, { type: 'uint256' }], [\n            delegation.contract,\n            BigInt(delegation.chainId),\n            BigInt(delegation.nonce),\n        ]));\n        payloads[payloadId] = {\n            kind: 'authorization',\n            authorization: {\n                contractAddress: delegation.contract,\n                chainId: delegation.chainId,\n                nonce: delegation.nonce,\n            },\n        };\n        const taskId = `delegation-${index}`;\n        return {\n            id: `delegation-request-${index}`,\n            checkpoint: { kind: 'none', id: `delegation-${index}:none` },\n            priorOutputs: [],\n            taskTemplates: [\n                {\n                    id: taskId,\n                    signer: input.signer,\n                    role: 'authorization',\n                    chain: toEvmChainReference(delegation.chainId),\n                    invocationKind: 'sign-authorization',\n                    payload: { source: 'plan-payload', payloadId },\n                    contribution: { kind: 'authorization' },\n                },\n            ],\n            schedule: [\n                {\n                    id: `delegation-prompt-${index}`,\n                    execution: 'serial',\n                    taskIds: [taskId],\n                },\n            ],\n            artifacts: [],\n        };\n    });\n    const plan = {\n        version: 1,\n        kind: 'eip7702-authorization-list',\n        payload: {\n            kind: 'authorization',\n            id: keccak256(encodeAbiParameters([{ type: 'address[]' }, { type: 'uint256[]' }], [\n                input.delegations.map(({ contract }) => contract),\n                input.delegations.map(({ chainId }) => BigInt(chainId)),\n            ])),\n        },\n        configuredTopology: emptyTopology,\n        effectiveSelection: emptySelection,\n        stages,\n        publicOutputs: stages.map((stage) => ({\n            id: `${stage.id}-result`,\n            source: { kind: 'task-result', taskId: stage.taskTemplates[0].id },\n            exposedForIndependentSigning: false,\n        })),\n    };\n    return { plan, payloads };\n}\nexport async function signRequestedDelegations(input) {\n    const { plan, payloads } = createRequestedDelegationPlan(input.planInput);\n    const transcript = await executeSigningPlan({\n        plan,\n        payloads,\n        signerInvoker: input.signerInvoker,\n        checkpoints: input.checkpoints,\n        assembleStage: () => ({}),\n    });\n    const byTask = Object.assign({}, ...transcript.stages.map(({ results }) => results));\n    const authorizations = input.planInput.delegations.map((_, index) => {\n        const result = byTask[`delegation-${index}`];\n        if (result?.kind !== 'signed-authorization' || !result.authorization) {\n            throw new Error(`Requested delegation ${index} was not signed`);\n        }\n        return result.authorization;\n    });\n    return { authorizations, transcript };\n}\nfunction directSigningPlan(input) {\n    return {\n        version: 1,\n        kind: input.kind,\n        payload: input.payload,\n        configuredTopology: emptyTopology,\n        effectiveSelection: emptySelection,\n        stages: [\n            {\n                id: input.stageId,\n                checkpoint: { kind: 'none', id: `${input.stageId}-no-read` },\n                priorOutputs: [],\n                taskTemplates: [input.task],\n                schedule: [\n                    {\n                        id: `${input.stageId}-signer`,\n                        execution: 'serial',\n                        taskIds: [input.task.id],\n                    },\n                ],\n                artifacts: [\n                    {\n                        id: input.artifactId,\n                        stageId: input.stageId,\n                        usage: 'erc1271',\n                        input: { kind: 'task-results', taskIds: [input.task.id] },\n                        validatorCodec: { kind: 'none' },\n                        erc7739: { kind: 'none' },\n                        accountEnvelope: { kind: 'none' },\n                        erc6492: { kind: 'none' },\n                    },\n                ],\n            },\n        ],\n        publicOutputs: [\n            {\n                id: input.artifactId,\n                source: { kind: 'artifact', artifactId: input.artifactId },\n                exposedForIndependentSigning: false,\n            },\n        ],\n    };\n}\nasync function executeDirectPlan(input) {\n    return executeSigningPlan({\n        plan: input.plan,\n        payloads: input.payloads,\n        signerInvoker: input.signerInvoker,\n        checkpoints: input.checkpoints,\n        assembleStage: ({ results }) => {\n            const result = Object.values(results)[0];\n            if (result?.kind !== 'ecdsa-signature') {\n                throw new Error('Direct signing task did not return an ECDSA signature');\n            }\n            return { [input.artifactId]: result.signature };\n        },\n    });\n}\nfunction dedupeEvmChains(chains) {\n    const seen = new Set();\n    return chains.flatMap((chain) => {\n        if (chain.kind !== 'evm' || seen.has(chain.id))\n            return [];\n        seen.add(chain.id);\n        return [chain];\n    });\n}\nconst emptyTopology = {\n    rootValidatorId: 'none',\n    validators: [],\n    threshold: 0,\n};\nconst emptySelection = {\n    validatorIds: [],\n    signerIds: [],\n    threshold: 0,\n};\n","import { SigningPipelineError } from './error.js';\nimport { materializeSigningStage, validateSigningPlan } from './plan.js';\nexport async function executeSigningPlan(input) {\n    try {\n        validateSigningPlan(input.plan);\n    }\n    catch (cause) {\n        if (cause instanceof SigningPipelineError)\n            throw cause;\n        throw pipelineError(input.plan, 'plan', 'Signing plan validation failed', {}, cause);\n    }\n    for (const stage of input.plan.stages) {\n        for (const task of stage.taskTemplates) {\n            if (!task.when &&\n                input.signerInvoker.has &&\n                !input.signerInvoker.has(task.signer)) {\n                throw pipelineError(input.plan, 'invoke', `Missing signer ${task.signer.id}`, {\n                    stageId: stage.id,\n                    taskId: task.id,\n                    signerRole: task.role,\n                    ...(task.chain ? { chain: task.chain } : {}),\n                });\n            }\n        }\n    }\n    const priorOutputs = {};\n    const transcripts = [];\n    for (const stagePlan of input.plan.stages) {\n        let facts = [];\n        if (stagePlan.checkpoint.kind !== 'none') {\n            try {\n                facts = await input.checkpoints.read(stagePlan.checkpoint);\n            }\n            catch (cause) {\n                throw pipelineError(input.plan, 'read', `Signing checkpoint ${stagePlan.checkpoint.id} failed`, { stageId: stagePlan.id }, cause);\n            }\n        }\n        let declaredPriorOutputs;\n        let stage;\n        try {\n            declaredPriorOutputs = selectDeclaredPriorOutputs(stagePlan, priorOutputs);\n            stage = materializeSigningStage({\n                plan: input.plan,\n                stage: stagePlan,\n                payloads: input.payloads,\n                facts,\n                priorOutputs: declaredPriorOutputs,\n            });\n        }\n        catch (cause) {\n            throw pipelineError(input.plan, 'plan', `Signing stage ${stagePlan.id} materialization failed`, { stageId: stagePlan.id }, cause);\n        }\n        for (const task of stage.tasks) {\n            if (task.when &&\n                input.signerInvoker.has &&\n                !input.signerInvoker.has(task.signer)) {\n                throw pipelineError(input.plan, 'invoke', `Missing signer ${task.signer.id}`, {\n                    stageId: stage.stageId,\n                    taskId: task.id,\n                    signerRole: task.role,\n                    ...(task.chain ? { chain: task.chain } : {}),\n                });\n            }\n        }\n        const results = {};\n        const invoke = async (taskId) => {\n            const task = stage.tasks.find(({ id }) => id === taskId);\n            if (!task)\n                throw new Error(`Unknown materialized signing task ${taskId}`);\n            try {\n                results[task.id] = await input.signerInvoker.invoke(task.signer, task.invocation);\n            }\n            catch (cause) {\n                throw pipelineError(input.plan, 'invoke', `Signing task ${task.id} failed`, {\n                    stageId: stage.stageId,\n                    taskId: task.id,\n                    signerRole: task.role,\n                    ...(task.chain ? { chain: task.chain } : {}),\n                }, cause);\n            }\n        };\n        for (const batch of stage.schedule) {\n            if (batch.execution === 'parallel') {\n                await Promise.all(batch.taskIds.map(invoke));\n            }\n            else {\n                for (const taskId of batch.taskIds)\n                    await invoke(taskId);\n            }\n        }\n        let outputs;\n        try {\n            outputs = input.assembleStage({\n                plan: input.plan,\n                stagePlan,\n                stage,\n                results,\n                priorOutputs: declaredPriorOutputs,\n            });\n        }\n        catch (cause) {\n            if (cause instanceof SigningPipelineError)\n                throw cause;\n            throw pipelineError(input.plan, 'final-assembly', `Signing stage ${stage.stageId} assembly failed`, { stageId: stage.stageId }, cause);\n        }\n        for (const artifact of stagePlan.artifacts) {\n            const output = outputs[artifact.id];\n            if (output === undefined) {\n                throw pipelineError(input.plan, 'final-assembly', `Assembler omitted artifact ${artifact.id}`, { stageId: stage.stageId, artifactId: artifact.id });\n            }\n            priorOutputs[`${stage.stageId}:${artifact.id}`] = output;\n        }\n        transcripts.push({ stage, results, outputs });\n    }\n    return {\n        planKind: input.plan.kind,\n        payloadId: input.plan.payload.id,\n        stages: transcripts,\n    };\n}\nfunction selectDeclaredPriorOutputs(stage, outputs) {\n    return Object.fromEntries(stage.priorOutputs.map((reference) => {\n        const key = `${reference.stageId}:${reference.outputId}`;\n        const output = outputs[key];\n        if (output === undefined) {\n            throw new Error(`Declared prior output ${key} is unavailable`);\n        }\n        return [key, output];\n    }));\n}\nfunction pipelineError(plan, failureStage, message, context, cause) {\n    return new SigningPipelineError(message, {\n        planKind: plan.kind,\n        payloadKind: plan.payload.kind,\n        failureStage,\n        ...context,\n    }, cause === undefined ? undefined : { cause });\n}\n","import { hashTypedData, isAddressEqual, } from 'viem';\nimport { toEvmChainReference } from '../chains/caip2.js';\nimport { K1_DEFAULT_VALIDATOR_ADDRESS } from '../modules/validators/k1.js';\nimport { executeSigningPlan } from './execute.js';\nimport { createSingleStageSigningPlan } from './plan.js';\nimport { assembleTypedDataStage } from './typed-data.js';\nexport function createSessionEnableSigningPlan(input) {\n    return createSingleStageSigningPlan({\n        kind: 'session-enable',\n        payload: { kind: 'session-enable', id: hashTypedData(input.typedData) },\n        configuredTopology: input.configuredTopology,\n        effectiveSelection: input.effectiveSelection,\n        stageId: 'session-enable',\n        chain: input.chain,\n        tasks: input.tasks,\n        artifacts: [\n            {\n                id: 'session-enable-signature',\n                usage: 'session-enable',\n                validatorCodec: input.validatorCodec,\n                ...(input.validatorFactors\n                    ? { validatorFactors: input.validatorFactors }\n                    : {}),\n                ...input.route,\n            },\n        ],\n    });\n}\nexport async function signSessionEnablement(input) {\n    const plan = createSessionEnableSigningPlan(input.planInput);\n    const transcript = await executeSigningPlan({\n        plan,\n        payloads: {\n            [plan.payload.id]: input.planInput.signingMaterial ?? {\n                kind: 'typed-data',\n                typedData: input.planInput.typedData,\n            },\n        },\n        signerInvoker: input.context.signerInvoker,\n        checkpoints: input.checkpoints,\n        assembleStage: (stage) => assembleTypedDataStage(stage, input.context),\n    });\n    const signature = transcript.stages[0].outputs['session-enable-signature'];\n    return { signature, transcript };\n}\nexport function resolveSessionEnableChain(input) {\n    const startaleK1 = input.accountKind === 'startale' &&\n        isAddressEqual(input.validator, K1_DEFAULT_VALIDATOR_ADDRESS);\n    if (!startaleK1)\n        return input.defaultChain;\n    const chainIds = [\n        ...new Set(input.hashesAndChainIds.map(({ chainId }) => chainId.toString())),\n    ];\n    if (chainIds.length > 1) {\n        throw new Error('Startale accounts with K1 validator do not support multi-chain session enable');\n    }\n    const chainId = chainIds[0];\n    if (chainId === undefined) {\n        throw new Error('Startale K1 session enable requires one session chain');\n    }\n    return toEvmChainReference(Number(chainId));\n}\n","import { hashTypedData } from 'viem';\nimport { K1_DEFAULT_VALIDATOR_ADDRESS, startaleEip712Domain, } from '../accounts/adapters/startale.js';\nimport { EoaSigningNotSupportedError } from '../accounts/error.js';\nimport { encodePlannedValidatorContribution } from './contribution.js';\nimport { runSigningStep } from './error.js';\nimport { executeSigningPlan } from './execute.js';\nimport { resolveAccountValidatorSignableHash } from './hash.js';\nimport { createSingleStageSigningPlan } from './plan.js';\nimport { wrapErc6492Signature } from './protocols/erc6492.js';\nimport { hashErc7739TypedData, wrapErc7739TypedDataSignature, } from './protocols/erc7739.js';\nexport function resolveAccountTypedDataSigning(input) {\n    const payload = input.validationHash ?? hashTypedData(input.typedData);\n    const accountKind = input.context.account.definition.kind;\n    const startaleK1 = accountKind === 'startale' &&\n        input.context.validatorCapabilities.compatibilityKey.moduleAddress.toLowerCase() ===\n            K1_DEFAULT_VALIDATOR_ADDRESS.toLowerCase();\n    const requiresRawHash = accountKind === 'kernel' || input.context.validator.kind === 'quorum';\n    // A quorum validator hashes the chain id into what the signer signs, and\n    // Startale's K1 route puts it in the ERC-7739 verifier domain. Either one\n    // yields a signature that validates on `input.chain` and nowhere else, so a\n    // payload whose legs are spread across chains must be refused here — while\n    // the caller is still preparing, not after the user has approved a bundle\n    // whose later legs cannot execute. Same-chain legs are unaffected, and\n    // Kernel's wrapping is address-only, so it stays fine either way.\n    if (input.spansMultipleChains &&\n        (input.context.validator.kind === 'quorum' || startaleK1)) {\n        throw new Error(`Cannot sign a multi-chain intent payload with ${input.context.validator.kind === 'quorum'\n            ? 'a quorum validator'\n            : \"Startale's K1 validator\"}: it binds the chain id into the signed hash, so the signature would validate only on chain ${input.chain.id} and fail on the intent's legs on other chains`);\n    }\n    const messagePayload = requiresRawHash\n        ? resolveAccountValidatorSignableHash({\n            hash: payload,\n            chain: input.chain,\n            context: input.context,\n        })\n        : startaleK1\n            ? hashErc7739TypedData({\n                typedData: input.typedData,\n                verifierDomain: startaleEip712Domain(input.context.account.address, input.chain.id),\n            })\n            : input.context.validatorCapabilities.supportsEip712\n                ? undefined\n                : payload;\n    return messagePayload\n        ? {\n            material: { kind: 'message', message: { raw: messagePayload } },\n            payloadKind: 'message',\n            ecdsaInvocation: 'ecdsa-sign-message',\n            webauthnInvocation: 'webauthn-sign-hash',\n            erc7739: startaleK1\n                ? { kind: 'wrap-typed-data', typedData: input.typedData }\n                : { kind: 'none' },\n        }\n        : {\n            material: { kind: 'typed-data', typedData: input.typedData },\n            payloadKind: 'typed-data',\n            ecdsaInvocation: 'ecdsa-sign-typed-data',\n            webauthnInvocation: 'webauthn-sign-typed-data',\n            erc7739: { kind: 'none' },\n        };\n}\nexport function createTypedDataSigningPlan(input) {\n    return createSingleStageSigningPlan({\n        kind: 'account-typed-data',\n        payload: { kind: 'typed-data', id: hashTypedData(input.typedData) },\n        configuredTopology: input.configuredTopology,\n        effectiveSelection: input.effectiveSelection,\n        stageId: 'typed-data',\n        ...(input.checkpoint ? { checkpoint: input.checkpoint } : {}),\n        chain: input.chain,\n        tasks: input.tasks,\n        artifacts: [\n            {\n                id: 'typed-data-signature',\n                usage: 'erc1271',\n                ...input.route,\n            },\n        ],\n    });\n}\nexport async function signAccountTypedData(input) {\n    if (input.context.account.definition.kind === 'eoa') {\n        throw new EoaSigningNotSupportedError('packed signatures');\n    }\n    const plan = createTypedDataSigningPlan(input.planInput);\n    const transcript = await executeSigningPlan({\n        plan,\n        payloads: {\n            [plan.payload.id]: input.planInput.signingMaterial ?? {\n                kind: 'typed-data',\n                typedData: input.planInput.typedData,\n            },\n        },\n        checkpoints: input.checkpoints,\n        signerInvoker: input.context.signerInvoker,\n        assembleStage: (stage) => assembleTypedDataStage(stage, input.context),\n    });\n    const signature = transcript.stages[0].outputs['typed-data-signature'];\n    return { signature, transcript };\n}\nexport function assembleTypedDataStage(input, context) {\n    const artifact = input.stagePlan.artifacts[0];\n    if (!artifact)\n        throw new Error('Typed-data plan has no artifact');\n    const step = (failureStage, operation) => runSigningStep({\n        plan: input.plan,\n        failureStage,\n        stageId: input.stage.stageId,\n        artifactId: artifact.id,\n        usage: artifact.usage,\n        operation,\n    });\n    let contribution = step('validator-encode', () => encodePlannedValidatorContribution({\n        artifact,\n        stage: input.stage,\n        results: input.results,\n    }));\n    const erc7739 = artifact.erc7739;\n    if (erc7739.kind !== 'none') {\n        contribution = step('protocol-operation', () => wrapErc7739TypedDataSignature({\n            typedData: erc7739.typedData,\n            signature: contribution,\n        }));\n    }\n    const accountSignature = artifact.accountEnvelope.kind === 'none'\n        ? contribution\n        : step('account-envelope', () => context.accountAdapter.encodeSignatureEnvelope({\n            account: context.account,\n            envelope: artifact.accountEnvelope,\n            validatorContribution: contribution,\n            purpose: 'erc1271',\n        }));\n    const erc6492 = artifact.erc6492;\n    if (erc6492.kind === 'none') {\n        return { [artifact.id]: accountSignature };\n    }\n    const deployed = input.stage.facts.find((fact) => fact.kind === 'account-deployed');\n    return {\n        [artifact.id]: deployed?.kind === 'account-deployed' && deployed.deployed\n            ? accountSignature\n            : step('protocol-operation', () => wrapErc6492Signature({\n                factory: erc6492.factory,\n                factoryData: erc6492.factoryData,\n                signature: accountSignature,\n            })),\n    };\n}\n","import { encodeMultiFactorContribution } from './multi-factor.js';\nimport { encodeEcdsaValidatorContribution } from './ownable.js';\nimport { encodeQuorumValidatorContribution } from './quorum.js';\nimport { encodeSmartSessionContribution } from './smart-sessions/signature.js';\nimport { encodeWebauthnValidatorContribution } from './webauthn.js';\nexport function encodeValidatorContribution(codec, contributions) {\n    switch (codec.kind) {\n        case 'ordered-threshold': {\n            const ecdsa = contributions.filter((contribution) => contribution.kind === 'ecdsa');\n            const webauthn = contributions.filter((contribution) => contribution.kind === 'webauthn');\n            if (ecdsa.length > 0 && webauthn.length > 0) {\n                throw new Error('Atomic validators cannot mix signer result kinds');\n            }\n            if (webauthn.length > 0) {\n                if (!codec.webauthn) {\n                    throw new Error('WebAuthn contribution codec context is missing');\n                }\n                return encodeWebauthnValidatorContribution({\n                    ownerOrder: codec.ownerOrder,\n                    threshold: codec.threshold,\n                    ...codec.webauthn,\n                    contributions: webauthn,\n                });\n            }\n            if (ecdsa.length !== contributions.length) {\n                throw new Error('Ordered validator received an incompatible result');\n            }\n            return encodeEcdsaValidatorContribution({\n                ownerOrder: codec.ownerOrder,\n                threshold: codec.threshold,\n                recoveryEncoding: codec.recoveryEncoding,\n                contributions: ecdsa,\n            });\n        }\n        case 'weighted-quorum': {\n            const ecdsa = contributions.filter((contribution) => contribution.kind === 'ecdsa');\n            if (ecdsa.length !== contributions.length) {\n                throw new Error('Quorum validator received a non-ECDSA contribution');\n            }\n            return encodeQuorumValidatorContribution({\n                owners: codec.owners,\n                thresholdWeight: codec.thresholdWeight,\n                contributions: ecdsa,\n            });\n        }\n        case 'nested-threshold': {\n            const factors = contributions.filter((contribution) => contribution.kind === 'factor');\n            if (factors.length !== contributions.length) {\n                throw new Error('Nested validator received a non-factor contribution');\n            }\n            return encodeMultiFactorContribution({\n                factorOrder: codec.factorOrder,\n                threshold: codec.threshold,\n                contributions: factors,\n            });\n        }\n        case 'smart-session': {\n            const signature = codec.signerCodec\n                ? encodeValidatorContribution(codec.signerCodec, contributions)\n                : contributions.length === 1 && contributions[0]?.kind === 'session'\n                    ? contributions[0].signature\n                    : undefined;\n            if (!signature)\n                throw new Error('Smart Session signer result is missing');\n            return encodeSmartSessionContribution({\n                mode: codec.mode,\n                permissionId: codec.permissionId,\n                signature,\n                ...(codec.claimPolicyData\n                    ? { claimPolicyData: codec.claimPolicyData }\n                    : {}),\n                ...(codec.enableData ? { enableData: codec.enableData } : {}),\n            });\n        }\n    }\n}\n","import { encodeValidatorContribution } from '../modules/validators/contribution.js';\nimport { encodeEcdsaRecoveryValue } from '../modules/validators/ownable.js';\nexport function encodePlannedValidatorContribution(input) {\n    const codec = resolvePlannedValidatorCodec(input.artifact.validatorCodec, input.stage);\n    if (codec.kind === 'none') {\n        throw new Error(`Artifact ${input.artifact.id} has no validator codec`);\n    }\n    if (input.artifact.input.kind !== 'task-results') {\n        throw new Error(`Artifact ${input.artifact.id} does not use task results`);\n    }\n    const planned = input.artifact.input.taskIds.map((taskId) => {\n        const task = input.stage.tasks.find(({ id }) => id === taskId);\n        const result = input.results[taskId];\n        if (!task || !result || !task.contribution) {\n            throw new Error(`Signing contribution ${taskId} is incomplete`);\n        }\n        return {\n            metadata: task.contribution,\n            contribution: contributionFromResult(task.contribution, result),\n        };\n    });\n    if (!input.artifact.validatorFactors) {\n        return encodeValidatorContribution(codec, planned.map(({ contribution }) => contribution));\n    }\n    const factors = input.artifact.validatorFactors.map((factor) => ({\n        kind: 'factor',\n        factorId: factor.id,\n        publicId: factor.publicId,\n        validator: factor.validator,\n        contribution: encodeValidatorContribution(factor.codec, planned.flatMap(({ metadata, contribution }) => 'factorId' in metadata && metadata.factorId === factor.id\n            ? [contribution]\n            : [])),\n    }));\n    return encodeValidatorContribution(codec, factors);\n}\nexport function resolvePlannedValidatorCodec(codec, stage) {\n    if (codec.kind !== 'smart-session-state')\n        return codec;\n    const fact = stage.facts.find(({ id }) => id === codec.factId);\n    if (fact?.kind !== 'session-enabled') {\n        throw new Error(`Session-state fact ${codec.factId} is missing`);\n    }\n    return fact.enabled ? codec.whenEnabled : codec.whenDisabled;\n}\nfunction contributionFromResult(metadata, result) {\n    switch (metadata.kind) {\n        case 'ecdsa':\n            if (result.kind !== 'ecdsa-signature') {\n                throw new Error('ECDSA task returned an incompatible result');\n            }\n            return {\n                kind: 'ecdsa',\n                ownerId: metadata.ownerId,\n                signature: result.signature,\n                encoding: metadata.encoding,\n            };\n        case 'webauthn':\n            if (result.kind !== 'webauthn-assertion') {\n                throw new Error('WebAuthn task returned an incompatible result');\n            }\n            return {\n                kind: 'webauthn',\n                ownerId: metadata.ownerId,\n                publicKey: metadata.publicKey,\n                signature: result.signature,\n                authenticatorData: result.authenticatorData,\n                clientDataJSON: result.clientDataJSON,\n                challengeIndex: result.challengeIndex,\n                typeIndex: result.typeIndex,\n                userVerificationRequired: result.userVerificationRequired,\n            };\n        case 'session':\n            if (result.kind !== 'ecdsa-signature') {\n                throw new Error('Session task returned an incompatible result');\n            }\n            return {\n                kind: 'session',\n                signature: encodeEcdsaRecoveryValue(result.signature, metadata.recoveryEncoding),\n            };\n        case 'authorization':\n            throw new Error('Authorization results are not validator contributions');\n    }\n}\n","import { concatHex, domainSeparator, encodeAbiParameters, keccak256, stringToHex, } from 'viem';\nexport function wrapKernelMessageHash(messageHash, account) {\n    const separator = domainSeparator({\n        domain: {\n            name: 'Kernel',\n            version: '0.3.3',\n            chainId: 0,\n            verifyingContract: account,\n        },\n    });\n    const structHash = keccak256(encodeAbiParameters([{ type: 'bytes32' }, { type: 'bytes32' }], [keccak256(stringToHex('Kernel(bytes32 hash)')), messageHash]));\n    return keccak256(concatHex(['0x1901', separator, structHash]));\n}\n","import { wrapKernelMessageHash } from '../accounts/kernel-signing.js';\nimport { getQuorumSignableHash } from '../modules/validators/quorum.js';\nexport function resolveAccountValidatorSignableHash(input) {\n    const accountHash = input.context.account.definition.kind === 'kernel'\n        ? wrapKernelMessageHash(input.hash, input.context.account.address)\n        : input.hash;\n    return input.context.validator.kind === 'quorum'\n        ? getQuorumSignableHash({\n            validator: input.context.validatorCapabilities.compatibilityKey.moduleAddress,\n            chainId: input.chain.id,\n            account: input.context.account.address,\n            hash: accountHash,\n        })\n        : accountHash;\n}\n","import { concat, decodeAbiParameters, encodeAbiParameters, size, slice, } from 'viem';\nexport const ERC6492_MAGIC_BYTES = '0x6492649264926492649264926492649264926492649264926492649264926492';\nexport function isErc6492Signature(signature) {\n    return (size(signature) >= 32 &&\n        slice(signature, size(signature) - 32).toLowerCase() === ERC6492_MAGIC_BYTES);\n}\nexport function wrapErc6492Signature(input) {\n    return concat([\n        encodeAbiParameters([\n            { name: 'create2Factory', type: 'address' },\n            { name: 'factoryCalldata', type: 'bytes' },\n            { name: 'originalERC1271Signature', type: 'bytes' },\n        ], [input.factory, input.factoryData, input.signature]),\n        ERC6492_MAGIC_BYTES,\n    ]);\n}\nexport function unwrapErc6492Signature(signature) {\n    if (!isErc6492Signature(signature)) {\n        throw new Error('Signature is not ERC-6492 encoded');\n    }\n    const encoded = slice(signature, 0, size(signature) - 32);\n    const [factory, factoryData, originalSignature] = decodeAbiParameters([{ type: 'address' }, { type: 'bytes' }, { type: 'bytes' }], encoded);\n    return { factory, factoryData, signature: originalSignature };\n}\n","import { concat, encodeAbiParameters, hashDomain, hashStruct, keccak256, toHex, } from 'viem';\nimport { wrapTypedDataSignature } from 'viem/experimental/erc7739';\nimport { encodeErc7739ContentType } from '../../modules/validators/smart-sessions/erc7739.js';\nexport { encodeErc7739ContentType };\nexport function hashErc7739TypedData(input) {\n    const { domain, types, primaryType, message } = input.typedData;\n    if (!domain || !primaryType) {\n        throw new Error('ERC-7739 requires a complete typed-data definition');\n    }\n    const typeFields = types;\n    const contentsType = encodeErc7739ContentType({\n        primaryType,\n        types: typeFields,\n    });\n    const typedDataSignTypeHash = keccak256(toHex(`TypedDataSign(${primaryType} contents,string name,string version,uint256 chainId,address verifyingContract,bytes32 salt)${contentsType}`));\n    const contentsHash = hashStruct({\n        data: message,\n        primaryType,\n        types: typeFields,\n    });\n    const verifier = input.verifierDomain;\n    const structHash = keccak256(encodeAbiParameters([\n        { type: 'bytes32' },\n        { type: 'bytes32' },\n        { type: 'bytes32' },\n        { type: 'bytes32' },\n        { type: 'uint256' },\n        { type: 'address' },\n        { type: 'bytes32' },\n    ], [\n        typedDataSignTypeHash,\n        contentsHash,\n        keccak256(toHex(verifier.name)),\n        keccak256(toHex(verifier.version)),\n        BigInt(verifier.chainId),\n        verifier.verifyingContract,\n        verifier.salt,\n    ]));\n    const domainTypes = [];\n    if (domain.name)\n        domainTypes.push({ name: 'name', type: 'string' });\n    if (domain.version)\n        domainTypes.push({ name: 'version', type: 'string' });\n    if (domain.chainId)\n        domainTypes.push({ name: 'chainId', type: 'uint256' });\n    if (domain.verifyingContract) {\n        domainTypes.push({ name: 'verifyingContract', type: 'address' });\n    }\n    if (domain.salt)\n        domainTypes.push({ name: 'salt', type: 'bytes32' });\n    const appDomainSeparator = hashDomain({\n        domain,\n        types: { EIP712Domain: domainTypes },\n    });\n    return keccak256(concat(['0x1901', appDomainSeparator, structHash]));\n}\nexport function wrapErc7739TypedDataSignature(input) {\n    const typedData = input.typedData;\n    return wrapTypedDataSignature({\n        domain: typedData.domain,\n        primaryType: typedData.primaryType,\n        types: typedData.types,\n        message: typedData.message,\n        signature: input.signature,\n    });\n}\n","export async function invokeWebauthnSigner(input) {\n    const result = input.invocation.kind === 'webauthn-sign-hash'\n        ? await input.signer.account.sign({ hash: input.invocation.hash })\n        : await input.signer.account.signTypedData(input.invocation.typedData);\n    return {\n        kind: 'webauthn-assertion',\n        signature: result.signature,\n        authenticatorData: result.webauthn.authenticatorData,\n        clientDataJSON: result.webauthn.clientDataJSON,\n        challengeIndex: result.webauthn.challengeIndex ?? 0,\n        typeIndex: result.webauthn.typeIndex ?? 0,\n        userVerificationRequired: result.webauthn.userVerificationRequired ?? false,\n    };\n}\n","import { invokeEcdsaSigner } from './ecdsa.js';\nimport { invokeWebauthnSigner } from './webauthn.js';\nexport function createSignerInvocationPort(input) {\n    return {\n        has: (reference) => {\n            const signer = input.signers[reference.id];\n            return signer !== undefined && signer.kind === reference.kind;\n        },\n        invoke: async (reference, invocation) => {\n            const signer = input.signers[reference.id];\n            if (!signer)\n                throw new Error(`Signer ${reference.id} is not registered`);\n            if (signer.kind !== reference.kind) {\n                throw new Error(`Signer ${reference.id} has kind ${signer.kind}, expected ${reference.kind}`);\n            }\n            if (invocation.kind === 'webauthn-sign-hash' ||\n                invocation.kind === 'webauthn-sign-typed-data') {\n                if (signer.kind !== 'webauthn') {\n                    throw new Error(`Signer ${reference.id} cannot invoke WebAuthn`);\n                }\n                return invokeWebauthnSigner({ signer, invocation });\n            }\n            if (signer.kind === 'webauthn') {\n                throw new Error(`Signer ${reference.id} cannot invoke ECDSA`);\n            }\n            return invokeEcdsaSigner({\n                signer,\n                invocation,\n                ...(input.resolveChain ? { resolveChain: input.resolveChain } : {}),\n            });\n        },\n    };\n}\n","import { keccak256, stringToHex } from 'viem';\nimport { IncompleteIntentProofsError, MismatchedIntentProofError, } from '../../errors/execution.js';\nfunction canonical(value) {\n    if (typeof value === 'bigint')\n        return { $bigint: value.toString() };\n    if (Array.isArray(value))\n        return value.map(canonical);\n    if (value && typeof value === 'object') {\n        return Object.fromEntries(Object.entries(value)\n            .sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))\n            .map(([key, item]) => [key, canonical(item)]));\n    }\n    return value;\n}\n/**\n * A fingerprint of the whole ordered request set.\n *\n * Binds an externally collected contribution to the exact quote it was made\n * against: a re-quote of the same intent produces different requests, and a\n * proof for slot 2 of the old set is not a proof for slot 2 of the new one.\n * Internal only — it is not a wire id, and it is not evidence the server\n * produced the requests.\n */\nexport function requestSetId(requests) {\n    return keccak256(stringToHex(JSON.stringify(canonical(requests))));\n}\n/**\n * Merges locally produced proofs with externally collected contributions into\n * the ordered vector the orchestrator expects.\n *\n * Every slot must be filled exactly once. A sparse vector is never returned as\n * a signed transaction.\n */\nexport function assembleProofVector(input) {\n    const slots = new Map(input.local);\n    for (const contribution of input.contributions ?? []) {\n        if (contribution.intentId !== input.intentId) {\n            throw new MismatchedIntentProofError({\n                context: {\n                    intentIds: [input.intentId, contribution.intentId],\n                    requestIndex: contribution.requestIndex,\n                },\n            });\n        }\n        if (contribution.requestSetId !== input.requestSetId) {\n            throw new MismatchedIntentProofError({\n                context: {\n                    intentId: input.intentId,\n                    requestIndex: contribution.requestIndex,\n                    reason: 'request-set',\n                },\n            });\n        }\n        const request = input.requests[contribution.requestIndex];\n        if (!request) {\n            throw new MismatchedIntentProofError({\n                context: {\n                    intentId: input.intentId,\n                    requestIndex: contribution.requestIndex,\n                    reason: 'out-of-range',\n                },\n            });\n        }\n        if (!matchesRequestKind(request, contribution.proof)) {\n            throw new MismatchedIntentProofError({\n                context: {\n                    intentId: input.intentId,\n                    requestIndex: contribution.requestIndex,\n                    reason: 'kind',\n                },\n            });\n        }\n        if (slots.has(contribution.requestIndex)) {\n            throw new MismatchedIntentProofError({\n                context: {\n                    intentId: input.intentId,\n                    requestIndex: contribution.requestIndex,\n                    reason: 'duplicate',\n                },\n            });\n        }\n        slots.set(contribution.requestIndex, contribution.proof);\n    }\n    const missing = input.requests\n        .map(({ index }) => index)\n        .filter((index) => !slots.has(index));\n    if (missing.length > 0) {\n        throw new IncompleteIntentProofsError({\n            intentId: input.intentId,\n            missing,\n        });\n    }\n    return input.requests.map(({ index }) => slots.get(index));\n}\nfunction matchesRequestKind(request, proof) {\n    switch (request.kind) {\n        case 'eip712':\n            return proof.kind === 'eip712';\n        case 'eip7702':\n            return proof.kind === 'eip7702';\n        case 'personalSign':\n            return proof.kind === 'personalSign';\n        default:\n            return false;\n    }\n}\n","import { encodeQuorumMerkleEnvelope } from '../../modules/validators/quorum.js';\nimport { encodePlannedValidatorContribution } from '../contribution.js';\nimport { runSigningStep } from '../error.js';\nimport { wrapErc7739TypedDataSignature } from '../protocols/erc7739.js';\nexport function assembleIntentStage(input, context) {\n    const outputs = {};\n    for (const artifact of input.stagePlan.artifacts) {\n        if (artifact.input.kind === 'session-claim-pair')\n            continue;\n        outputs[artifact.id] =\n            artifact.input.kind === 'reuse-artifact'\n                ? resolveReusedArtifact(artifact.id, artifact.input, input.priorOutputs)\n                : assembleSignedArtifact(input, artifact, context);\n    }\n    for (const artifact of input.stagePlan.artifacts) {\n        if (artifact.input.kind !== 'session-claim-pair')\n            continue;\n        const preClaimSig = outputs[artifact.input.preClaimArtifactId];\n        const notarizedClaimSig = outputs[artifact.input.notarizedClaimArtifactId];\n        if (typeof preClaimSig !== 'string' ||\n            typeof notarizedClaimSig !== 'string') {\n            throw new Error(`Session claim pair ${artifact.id} is incomplete`);\n        }\n        outputs[artifact.id] = { preClaimSig, notarizedClaimSig };\n    }\n    return outputs;\n}\nexport function assembleIntentValidatorArtifact(input) {\n    if (input.artifact.erc6492.kind !== 'none') {\n        throw new Error('ERC-6492 is forbidden for intent signatures');\n    }\n    const step = (failureStage, operation) => input.diagnostics\n        ? runSigningStep({\n            plan: input.diagnostics.plan,\n            failureStage,\n            stageId: input.diagnostics.stageId,\n            artifactId: input.artifact.id,\n            usage: input.artifact.usage,\n            operation,\n        })\n        : operation();\n    let contribution = input.validatorContribution;\n    if (input.artifact.quorumMerkleProof) {\n        if (!contribution.startsWith('0x00')) {\n            throw new Error('Quorum Merkle contribution has no regular envelope prefix');\n        }\n        contribution = step('validator-encode', () => encodeQuorumMerkleEnvelope({\n            proof: input.artifact.quorumMerkleProof,\n            signatures: `0x${contribution.slice(4)}`,\n        }));\n    }\n    const erc7739 = input.artifact.erc7739;\n    if (erc7739.kind === 'wrap-typed-data') {\n        contribution = step('protocol-operation', () => wrapErc7739TypedDataSignature({\n            typedData: erc7739.typedData,\n            signature: contribution,\n        }));\n    }\n    return input.artifact.accountEnvelope.kind === 'none'\n        ? contribution\n        : step('account-envelope', () => input.context.accountAdapter.encodeSignatureEnvelope({\n            account: input.context.account,\n            envelope: input.artifact.accountEnvelope,\n            validatorContribution: contribution,\n            purpose: 'intent',\n        }));\n}\nfunction assembleSignedArtifact(input, artifact, context) {\n    if (artifact.validatorCodec.kind === 'none') {\n        if (artifact.input.kind !== 'task-results' ||\n            artifact.input.taskIds.length !== 1) {\n            throw new Error(`Direct artifact ${artifact.id} requires one task`);\n        }\n        const result = input.results[artifact.input.taskIds[0]];\n        if (result?.kind !== 'ecdsa-signature') {\n            throw new Error(`Direct artifact ${artifact.id} requires an ECDSA result`);\n        }\n        return result.signature;\n    }\n    return assembleIntentValidatorArtifact({\n        artifact,\n        context,\n        validatorContribution: runSigningStep({\n            plan: input.plan,\n            failureStage: 'validator-encode',\n            stageId: input.stage.stageId,\n            artifactId: artifact.id,\n            usage: artifact.usage,\n            operation: () => encodePlannedValidatorContribution({\n                artifact,\n                stage: input.stage,\n                results: input.results,\n            }),\n        }),\n        diagnostics: { plan: input.plan, stageId: input.stage.stageId },\n    });\n}\nfunction resolveReusedArtifact(artifactId, route, priorOutputs) {\n    const source = priorOutputs[`${route.stageId}:${route.artifactId}`];\n    if (typeof source === 'string')\n        return source;\n    if (source && route.selection === 'pre-claim' && 'preClaimSig' in source) {\n        return source.preClaimSig;\n    }\n    throw new Error(`Reused artifact ${route.artifactId} is unavailable for ${artifactId}`);\n}\n","import { InsufficientOwnerSignaturesError, MismatchedOwnerSignaturesError, UnknownOwnerError, } from '../../errors/execution.js';\nimport { encodeValidatorContribution } from '../../modules/validators/contribution.js';\nimport { encodeValidatorId } from '../../modules/validators/multi-factor.js';\nimport { assembleIntentValidatorArtifact } from './assemble.js';\nexport function assembleIndependentIntentArtifact(input) {\n    if (input.artifact.validatorCodec.kind === 'none') {\n        throw new Error('Independent signing requires a validator codec');\n    }\n    if (input.artifact.validatorCodec.kind === 'smart-session-state') {\n        throw new Error('Smart Session state cannot be signed independently');\n    }\n    const contributions = importOwnerContributions(input);\n    const codec = input.artifact.validatorCodec;\n    if (codec.kind === 'smart-session') {\n        throw new Error('Smart Session state cannot be signed independently');\n    }\n    const validatorContribution = input.artifact.validatorFactors\n        ? codec.kind !== 'nested-threshold'\n            ? (() => {\n                throw new Error('Independent factor signing requires a nested codec');\n            })()\n            : encodeIndependentFactors(codec, input.artifact.validatorFactors, contributions)\n        : encodeAtomicContributions(codec, contributions.map(({ contribution }) => contribution));\n    return assembleIntentValidatorArtifact({\n        artifact: input.artifact,\n        context: input.context,\n        validatorContribution,\n    });\n}\nfunction importOwnerContributions(input) {\n    const seen = new Set();\n    return input.signatures.map((value) => {\n        if (value.intentId !== input.intentId) {\n            throw new MismatchedOwnerSignaturesError({\n                context: { intentIds: [input.intentId, value.intentId] },\n            });\n        }\n        const signature = value.kind === 'multi-factor' ? value.signature : value;\n        if (signature.slots.length !== input.slotCount) {\n            throw new MismatchedOwnerSignaturesError({\n                context: { expectedSlotCount: input.slotCount },\n            });\n        }\n        const identity = signature.kind === 'ecdsa'\n            ? signature.signer.toLowerCase()\n            : signature.publicKey.toLowerCase();\n        const owner = input.owners.find((candidate) => candidate.identity.toLowerCase() === identity &&\n            (value.kind === 'multi-factor'\n                ? candidate.factorPublicId !== undefined &&\n                    sameValidatorId(candidate.factorPublicId, value.validatorId)\n                : candidate.factorId === undefined));\n        if (!owner) {\n            const matchingIdentity = input.owners.filter((candidate) => candidate.identity.toLowerCase() === identity);\n            if (matchingIdentity.length > 0 &&\n                (value.kind === 'multi-factor' ||\n                    matchingIdentity.some(({ factorId }) => factorId !== undefined))) {\n                throw new MismatchedOwnerSignaturesError({\n                    context: value.kind === 'multi-factor'\n                        ? { validatorId: value.validatorId }\n                        : { expectedKind: 'multi-factor' },\n                });\n            }\n            throw new UnknownOwnerError({\n                context: signature.kind === 'passkey'\n                    ? { publicKey: signature.publicKey }\n                    : { signer: signature.signer },\n            });\n        }\n        const contributionKey = `${owner.factorId ?? 'root'}:${identity}`;\n        if (seen.has(contributionKey))\n            throw new MismatchedOwnerSignaturesError({\n                context: { duplicateOwner: identity },\n            });\n        seen.add(contributionKey);\n        if ((signature.kind === 'ecdsa' && owner.kind !== 'ecdsa') ||\n            (signature.kind === 'passkey' && owner.kind !== 'webauthn')) {\n            throw new MismatchedOwnerSignaturesError({\n                context: { owner: identity },\n            });\n        }\n        const contribution = signature.kind === 'ecdsa'\n            ? {\n                kind: 'ecdsa',\n                ownerId: owner.ownerId,\n                signature: signature.slots[input.slotIndex],\n                encoding: 'validator-contribution',\n            }\n            : {\n                kind: 'webauthn',\n                ownerId: owner.ownerId,\n                publicKey: signature.publicKey,\n                signature: signature.slots[input.slotIndex].signature,\n                authenticatorData: signature.slots[input.slotIndex].webauthn.authenticatorData,\n                clientDataJSON: signature.slots[input.slotIndex].webauthn.clientDataJSON,\n                challengeIndex: signature.slots[input.slotIndex].webauthn.challengeIndex ?? 0,\n                typeIndex: signature.slots[input.slotIndex].webauthn.typeIndex ?? 0,\n                userVerificationRequired: signature.slots[input.slotIndex].webauthn\n                    .userVerificationRequired ?? false,\n            };\n        return {\n            ...(owner.factorId ? { factorId: owner.factorId } : {}),\n            contribution,\n        };\n    });\n}\nfunction sameValidatorId(left, right) {\n    try {\n        return (encodeValidatorId(left).toLowerCase() ===\n            encodeValidatorId(right).toLowerCase());\n    }\n    catch {\n        return false;\n    }\n}\nfunction encodeIndependentFactors(codec, factors, contributions) {\n    const factorContributions = factors.flatMap((factor) => {\n        const selected = contributions.flatMap((entry) => entry.factorId === factor.id ? [entry.contribution] : []);\n        if (selected.length === 0)\n            return [];\n        if (selected.length < factor.codec.threshold) {\n            throw new InsufficientOwnerSignaturesError({\n                required: factor.codec.threshold,\n                provided: selected.length,\n                validatorId: factor.publicId,\n            });\n        }\n        return [\n            {\n                kind: 'factor',\n                factorId: factor.id,\n                publicId: factor.publicId,\n                validator: factor.validator,\n                contribution: encodeValidatorContribution(factor.codec, selected),\n            },\n        ];\n    });\n    if (factorContributions.length < codec.threshold) {\n        throw new InsufficientOwnerSignaturesError({\n            required: codec.threshold,\n            provided: factorContributions.length,\n        });\n    }\n    return encodeValidatorContribution(codec, factorContributions);\n}\nfunction encodeAtomicContributions(codec, contributions) {\n    if (codec.kind === 'ordered-threshold' &&\n        contributions.length < codec.threshold) {\n        throw new InsufficientOwnerSignaturesError({\n            required: codec.threshold,\n            provided: contributions.length,\n        });\n    }\n    return encodeValidatorContribution(codec, contributions);\n}\n","/** The EIP-712 requests the local signing plan actually executes. */\nexport function eip712Requests(input) {\n    return input.requests.filter((request) => request.kind === 'eip712');\n}\n","import { executeSigningPlan } from '../execute.js';\nimport { assembleIntentStage } from './assemble.js';\nimport { eip712Requests, } from './types.js';\nexport function createIntentSigningPlan(input) {\n    const reuses = eip712Requests(input.intent).flatMap((request) => request.reuse\n        ? [\n            {\n                artifactId: request.artifactId,\n                sourceArtifactId: request.reuse.artifactId,\n                selection: request.reuse.selection,\n            },\n        ]\n        : []);\n    const plan = {\n        version: 1,\n        kind: 'intent-full',\n        payload: { kind: 'intent', id: input.intent.id },\n        configuredTopology: input.intent.configuredTopology,\n        effectiveSelection: input.intent.effectiveSelection,\n        preparedIntent: {\n            signatureMode: input.intent.preparedSignatureMode,\n            artifacts: input.intent.artifacts.map(({ id, usage, payloadId, cardinality, shape }) => ({\n                id,\n                usage,\n                payloadId,\n                cardinality,\n                shape,\n            })),\n            ...(reuses.length > 0 ? { reuses } : {}),\n        },\n        stages: input.stages.map((stage) => ({\n            id: stage.id,\n            checkpoint: stage.checkpoint,\n            priorOutputs: stage.priorOutputs,\n            taskTemplates: stage.tasks,\n            schedule: stage.schedule,\n            artifacts: stage.artifacts.map((artifact) => ({\n                ...artifact,\n                stageId: stage.id,\n            })),\n        })),\n        publicOutputs: input.intent.artifacts.map((artifact) => ({\n            id: artifact.id,\n            source: { kind: 'artifact', artifactId: artifact.id },\n            exposedForIndependentSigning: artifact.exposedForIndependentSigning,\n        })),\n    };\n    assertPreparedMode(input);\n    assertIntentRoutes(input, plan);\n    return plan;\n}\nexport function projectIndependentSigning(plan, signerIds, ownerIds) {\n    if (plan.kind !== 'intent-full') {\n        throw new Error('Independent signing requires a full intent plan');\n    }\n    const selected = new Set(signerIds);\n    const selectedOwners = ownerIds ? new Set(ownerIds) : undefined;\n    if (selected.size !== signerIds.length) {\n        throw new Error('Independent signer selection contains duplicates');\n    }\n    for (const signerId of selected) {\n        if (!plan.effectiveSelection.signerIds.includes(signerId)) {\n            throw new Error(`Independent signer ${signerId} is not in the plan`);\n        }\n    }\n    const stages = plan.stages.map((stage) => {\n        const taskTemplates = stage.taskTemplates.filter((task) => selected.has(task.signer.id) &&\n            (!selectedOwners ||\n                [...selectedOwners].some((ownerId) => task.id.includes(ownerId))));\n        const taskIds = new Set(taskTemplates.map(({ id }) => id));\n        return {\n            ...stage,\n            priorOutputs: [],\n            taskTemplates,\n            schedule: stage.schedule\n                .map((batch) => ({\n                ...batch,\n                taskIds: batch.taskIds.filter((taskId) => taskIds.has(taskId)),\n            }))\n                .filter(({ taskIds: ids }) => ids.length > 0),\n            artifacts: [],\n        };\n    });\n    const projected = {\n        ...plan,\n        kind: 'intent-independent',\n        effectiveSelection: {\n            ...plan.effectiveSelection,\n            signerIds: plan.effectiveSelection.signerIds.filter((id) => selected.has(id)),\n        },\n        stages,\n        publicOutputs: stages.flatMap((stage) => stage.taskTemplates.map((task) => ({\n            id: `${task.id}-contribution`,\n            source: { kind: 'task-result', taskId: task.id },\n            exposedForIndependentSigning: true,\n        }))),\n    };\n    return {\n        plan: projected,\n        projection: {\n            planKind: 'intent-independent',\n            sourceIntentId: plan.payload.id,\n            exposedArtifactIds: projected.publicOutputs.map(({ id }) => id),\n            selectedSignerIds: [...signerIds],\n        },\n    };\n}\nfunction assertIntentRoutes(input, plan) {\n    const artifacts = plan.stages.flatMap((stage) => stage.artifacts);\n    const requirements = new Map(input.intent.artifacts.map((artifact) => [artifact.id, artifact]));\n    if (requirements.size !== input.intent.artifacts.length) {\n        throw new Error('Intent artifact requirements contain duplicate ids');\n    }\n    for (const requirement of input.intent.artifacts) {\n        if (!artifacts.some(({ id }) => id === requirement.id)) {\n            throw new Error(`Intent artifact ${requirement.id} has no assembly route`);\n        }\n    }\n    for (const request of eip712Requests(input.intent)) {\n        const requirement = requirements.get(request.artifactId);\n        if (!requirement) {\n            throw new Error(`Intent request ${request.index} has no artifact requirement`);\n        }\n        const route = artifacts.find(({ id }) => id === request.artifactId);\n        if (!route) {\n            throw new Error(`Intent request ${request.index} has no assembly route`);\n        }\n        if (!request.reuse) {\n            if (requirement.payloadId !== request.payload.id ||\n                route.input.kind === 'reuse-artifact') {\n                throw new Error(`Intent request ${request.index} signing route is incompatible`);\n            }\n            continue;\n        }\n        if (route.input.kind !== 'reuse-artifact' ||\n            route.input.artifactId !== request.reuse.artifactId ||\n            route.input.selection !== request.reuse.selection) {\n            throw new Error(`Intent request ${request.index} reuse route is incompatible`);\n        }\n    }\n}\nfunction assertPreparedMode(input) {\n    const signed = eip712Requests(input.intent).filter(({ reuse }) => !reuse);\n    const claimArtifacts = input.intent.artifacts.filter(({ usage }) => usage === 'intent-pre-claim' || usage === 'intent-notarized-claim');\n    const expected = signed.length;\n    const produced = input.intent.artifacts.length - claimArtifacts.length;\n    if (produced < expected) {\n        throw new Error(`Prepared signature mode requires ${expected} signed artifacts, received ${produced}`);\n    }\n    const invalidShape = input.intent.artifacts.some(({ shape }) => input.intent.preparedSignatureMode === 'default'\n        ? shape !== 'hex'\n        : !['hex', 'session-claims'].includes(shape));\n    if (invalidShape) {\n        const expectedShape = input.intent.preparedSignatureMode === 'default'\n            ? 'hex'\n            : 'hex or session-claims';\n        throw new Error(`Prepared signature mode requires ${expectedShape} artifacts`);\n    }\n}\nexport async function executeIntentSigning(input) {\n    const plan = createIntentSigningPlan(input.planInput);\n    return executeSigningPlan({\n        plan,\n        payloads: input.planInput.payloads,\n        signerInvoker: input.context.signerInvoker,\n        checkpoints: input.checkpoints,\n        assembleStage: (stage) => assembleIntentStage(stage, input.context),\n    });\n}\n","import { encodePacked, hashMessage, pad, } from 'viem';\nimport { getChainById } from '../../chains/catalog.js';\nimport { getValidatorCapabilities } from '../../modules/validators/capabilities.js';\nimport { defineValidator } from '../../modules/validators/definition.js';\nimport { buildPermit2ClaimPolicyCalldata } from '../../modules/validators/policies/claim/permit2.js';\nimport { resolveAtomicValidator, resolveValidator, } from '../../modules/validators/resolve.js';\nimport { getSessionData } from '../../modules/validators/smart-sessions/digest.js';\nimport { getSmartSessionEmissaryAddress } from '../../modules/validators/smart-sessions/module.js';\nimport { resolvePermit2ClaimPolicy, selectPermit2ClaimPolicyForMessage, } from '../../modules/validators/smart-sessions/policies/claim.js';\nimport { webauthnStatelessCodecContext } from '../../modules/validators/webauthn.js';\nimport { getAccountSignatureEnvelope } from '../../signing/context.js';\nimport { createValidatorSigningTasks, signingTopology, } from '../../signing/plan.js';\nimport { createSignerInvocationPort } from '../../signing/signers/registry.js';\nimport { signatureSpansMultipleChains } from './origin-chain.js';\nexport function createIntentSessionSignerInvoker(prepared, fallback) {\n    const signers = {};\n    for (const resolved of Object.values(prepared.resolvedSessions ?? {})) {\n        const validator = defineValidator(resolved.session.owners, 'smart-session-validator');\n        const owners = validator.kind === 'multi-factor'\n            ? validator.validators.flatMap(({ owners: factorOwners }) => factorOwners)\n            : validator.owners;\n        for (const owner of owners) {\n            signers[owner.signerId] =\n                owner.kind === 'webauthn'\n                    ? { kind: 'webauthn', account: owner.account }\n                    : { kind: 'ecdsa', account: owner.account };\n        }\n    }\n    const session = createSignerInvocationPort({\n        signers,\n        resolveChain: (chain) => getChainById(chain.id),\n    });\n    return {\n        has: (signer) => session.has?.(signer) ?? fallback.has?.(signer) ?? false,\n        invoke: (signer, invocation) => session.has?.(signer)\n            ? session.invoke(signer, invocation)\n            : fallback.invoke(signer, invocation),\n    };\n}\nexport function buildSessionIntentPlanInput(prepared, context) {\n    const payloads = {};\n    const stages = [];\n    for (const request of prepared.signing.requests) {\n        if (request.kind !== 'eip712')\n            continue;\n        if (request.reuse) {\n            const { artifactId, selection } = request.reuse;\n            stages.push({\n                id: request.artifactId,\n                checkpoint: { kind: 'none', id: `${request.artifactId}:none` },\n                priorOutputs: [\n                    { stageId: artifactId, outputId: artifactId, selection },\n                ],\n                tasks: [],\n                schedule: [],\n                artifacts: [\n                    {\n                        id: request.artifactId,\n                        usage: request.payload.usage,\n                        input: {\n                            kind: 'reuse-artifact',\n                            stageId: artifactId,\n                            artifactId,\n                            selection,\n                        },\n                        validatorCodec: { kind: 'none' },\n                        erc7739: { kind: 'none' },\n                        accountEnvelope: { kind: 'none' },\n                        erc6492: { kind: 'none' },\n                    },\n                ],\n            });\n            continue;\n        }\n        // A smart session is enabled per chain and its signature carries that\n        // session's identity, so one signature cannot stand for legs on other\n        // chains. Refuse while preparing rather than sign a bundle whose later legs\n        // cannot execute.\n        if (signatureSpansMultipleChains(request.payload.typedData)) {\n            throw new Error('Cannot sign a chain-agnostic intent payload with a smart session: a session is enabled per chain, so the signature would validate only on the leg it was resolved against');\n        }\n        const session = requireSession(prepared, request.payload.chain.id);\n        // The encoding a session signature needs depends on what it authorises:\n        // a claim is notarized (paired with its pre-claim form when executions are\n        // verified), while a fill or target execution is authorised pre-claim.\n        const output = request.purpose === 'originAuthorization'\n            ? session.verifyExecutions\n                ? 'pair'\n                : 'notarized'\n            : request.purpose === 'destinationAuthorization'\n                ? session.verifyExecutions\n                    ? 'pre-claim'\n                    : 'notarized'\n                : 'pre-claim';\n        stages.push(buildSessionStage({\n            id: request.artifactId,\n            outputId: request.artifactId,\n            usage: request.payload.usage,\n            typedData: request.payload.typedData,\n            payloadId: request.payload.id,\n            chain: request.payload.chain,\n            session,\n            environment: requireSessionEnvironment(prepared),\n            context,\n            payloads,\n            output,\n            ...(request.purpose === 'destinationAuthorization' &&\n                session.verifyExecutions\n                ? { includeNotarized: true }\n                : {}),\n        }));\n    }\n    return { intent: prepared.signing, stages, payloads };\n}\nfunction buildSessionStage(input) {\n    const signing = sessionOwnerSigning(input.session, input.context.account.address);\n    const module = getSmartSessionEmissaryAddress(input.environment);\n    const tasks = [];\n    const artifacts = [];\n    const scheduleIds = [];\n    const checkpoint = input.session.enableData\n        ? {\n            kind: 'session-enabled',\n            id: `${input.id}:session-enabled`,\n            chain: input.chain,\n            account: input.context.account.address,\n            permissionId: input.session.session.permissionId,\n        }\n        : { kind: 'none', id: `${input.id}:none` };\n    const notarizedId = `${input.id}:notarized`;\n    if (input.output === 'pair' ||\n        input.output === 'notarized' ||\n        input.includeNotarized) {\n        const payloadId = notarizedPayload(input.context.account.address, input.payloadId);\n        input.payloads[payloadId] = {\n            kind: 'message',\n            message: { raw: payloadId },\n        };\n        const stageTasks = sessionTasks(`${notarizedId}:signer`, signing, input.chain, payloadId, 'session-notarized');\n        tasks.push(...stageTasks);\n        scheduleIds.push(...stageTasks.map(({ id }) => id));\n        artifacts.push({\n            id: input.output === 'notarized' ? input.outputId : notarizedId,\n            usage: input.output === 'notarized' ? input.usage : 'intent-notarized-claim',\n            input: {\n                kind: 'task-results',\n                taskIds: stageTasks.map(({ id }) => id),\n            },\n            validatorCodec: sessionCodec(input.session, module, signing.signerCodec, 'notarized', input.typedData),\n            ...(signing.validatorFactors\n                ? { validatorFactors: signing.validatorFactors }\n                : {}),\n            erc7739: { kind: 'none' },\n            accountEnvelope: sessionAccountEnvelope(getAccountSignatureEnvelope(input.context), module),\n            erc6492: { kind: 'none' },\n        });\n    }\n    if (input.output === 'pair' || input.output === 'pre-claim') {\n        input.payloads[input.payloadId] = {\n            kind: 'message',\n            message: { raw: input.payloadId },\n        };\n        const preClaimId = input.output === 'pre-claim' ? input.outputId : `${input.id}:pre-claim`;\n        const stageTasks = sessionTasks(`${preClaimId}:signer`, signing, input.chain, input.payloadId, 'session-pre-claim');\n        tasks.push(...stageTasks);\n        scheduleIds.push(...stageTasks.map(({ id }) => id));\n        artifacts.push({\n            id: preClaimId,\n            usage: input.output === 'pre-claim' ? input.usage : 'intent-pre-claim',\n            input: {\n                kind: 'task-results',\n                taskIds: stageTasks.map(({ id }) => id),\n            },\n            validatorCodec: sessionPreClaimCodec(input.session, module, signing.signerCodec, checkpoint.id),\n            ...(signing.validatorFactors\n                ? { validatorFactors: signing.validatorFactors }\n                : {}),\n            erc7739: { kind: 'none' },\n            accountEnvelope: { kind: 'none' },\n            erc6492: { kind: 'none' },\n        });\n    }\n    if (input.output === 'pair') {\n        artifacts.push({\n            id: input.outputId,\n            usage: input.usage,\n            input: {\n                kind: 'session-claim-pair',\n                preClaimArtifactId: `${input.id}:pre-claim`,\n                notarizedClaimArtifactId: notarizedId,\n            },\n            validatorCodec: { kind: 'none' },\n            erc7739: { kind: 'none' },\n            accountEnvelope: { kind: 'none' },\n            erc6492: { kind: 'none' },\n        });\n    }\n    return {\n        id: input.id,\n        checkpoint,\n        priorOutputs: [],\n        tasks,\n        schedule: [\n            {\n                id: `${input.id}:session-signers`,\n                execution: 'serial',\n                taskIds: scheduleIds,\n            },\n        ],\n        artifacts,\n    };\n}\nfunction sessionTasks(taskPrefix, signing, chain, payloadId, role) {\n    return createValidatorSigningTasks({\n        validator: signing.validator,\n        signerReferences: signing.signerReferences,\n        taskPrefix,\n        ecdsaInvocation: 'ecdsa-sign-message',\n        webauthnInvocation: 'webauthn-sign-hash',\n        role,\n    }).map((task) => ({\n        ...task,\n        chain,\n        payload: { source: 'plan-payload', payloadId },\n    }));\n}\nfunction sessionOwnerSigning(session, account) {\n    const validator = defineValidator(session.session.owners, 'smart-session-validator');\n    const owners = validatorOwners(validator);\n    const capabilities = getValidatorCapabilities(validator, resolveValidator(validator), 'smart-session-owner', 'intent', false);\n    return {\n        validator,\n        ...signingTopology(validator),\n        signerReferences: Object.fromEntries(owners.map((owner) => [\n            owner.signerId,\n            {\n                id: owner.signerId,\n                kind: owner.kind === 'webauthn'\n                    ? 'webauthn'\n                    : 'ecdsa',\n            },\n        ])),\n        signerCodec: withWebauthnContext(requireSessionSignerCodec(capabilities.contributionCodec), validator.kind === 'passkey', account),\n        ...(validator.kind === 'multi-factor'\n            ? {\n                validatorFactors: validator.validators.map((factor) => ({\n                    id: factor.id,\n                    publicId: factor.publicId,\n                    validator: resolveAtomicValidator(factor).address,\n                    codec: withFactorWebauthnContext(requireAtomicSignerCodec(getValidatorCapabilities(factor, resolveAtomicValidator(factor), 'smart-session-owner', 'intent', false).contributionCodec), factor),\n                })),\n            }\n            : {}),\n    };\n}\nfunction sessionCodec(session, validator, signerCodec, mode, typedData) {\n    return {\n        kind: 'smart-session',\n        validator: { kind: 'validator', address: validator },\n        mode,\n        permissionId: session.session.permissionId,\n        signerCodec,\n        ...(mode === 'notarized'\n            ? { claimPolicyData: claimPolicyData(session, typedData) }\n            : {}),\n    };\n}\nfunction sessionPreClaimCodec(session, validator, signerCodec, factId) {\n    const enabled = sessionCodec(session, validator, signerCodec, 'pre-claim');\n    if (!session.enableData)\n        return enabled;\n    return {\n        kind: 'smart-session-state',\n        factId,\n        whenEnabled: enabled,\n        whenDisabled: {\n            kind: 'smart-session',\n            validator: { kind: 'validator', address: validator },\n            mode: 'enable-and-use',\n            permissionId: session.session.permissionId,\n            signerCodec,\n            enableData: {\n                ...session.enableData,\n                session: getSessionData(session.session),\n            },\n        },\n    };\n}\nfunction requireSessionSignerCodec(codec) {\n    if (codec.kind === 'smart-session') {\n        throw new Error('A Smart Session owner cannot use a session validator');\n    }\n    return codec;\n}\nfunction requireAtomicSignerCodec(codec) {\n    if (codec.kind !== 'ordered-threshold') {\n        throw new Error('A Smart Session factor must use an atomic validator');\n    }\n    return codec;\n}\nfunction validatorOwners(validator) {\n    return validator.kind === 'multi-factor'\n        ? validator.validators.flatMap(({ owners }) => owners)\n        : validator.owners;\n}\nfunction withWebauthnContext(codec, webauthn, account) {\n    if (!webauthn || codec.kind !== 'ordered-threshold')\n        return codec;\n    return {\n        ...codec,\n        webauthn: {\n            account,\n            usePrecompile: false,\n            format: 'current',\n        },\n    };\n}\nfunction withFactorWebauthnContext(codec, factor) {\n    return factor.kind === 'passkey'\n        ? { ...codec, webauthn: webauthnStatelessCodecContext(factor) }\n        : codec;\n}\nfunction sessionAccountEnvelope(envelope, validator) {\n    if (envelope.kind === 'none')\n        return envelope;\n    return envelope.kind === 'kernel'\n        ? { ...envelope, validator, isRoot: false }\n        : { ...envelope, validator };\n}\nfunction notarizedPayload(account, payload) {\n    return hashMessage({\n        raw: encodePacked(['bytes32', 'bytes32'], [pad(account, { size: 32 }), payload]),\n    });\n}\nfunction claimPolicyData(session, typedData) {\n    if (!typedData ||\n        typedData.primaryType !== 'PermitBatchWitnessTransferFrom' ||\n        session.session.claimPolicies.length === 0) {\n        return undefined;\n    }\n    const message = typedData.message;\n    const policy = selectPermit2ClaimPolicyForMessage(session.session.claimPolicies, message);\n    return policy\n        ? buildPermit2ClaimPolicyCalldata(resolvePermit2ClaimPolicy(policy), message)\n        : undefined;\n}\nfunction requireSession(prepared, chainId) {\n    const session = prepared.resolvedSessions?.[chainId];\n    if (!session)\n        throw new Error(`Prepared session for chain ${chainId} is missing`);\n    return session;\n}\nfunction requireSessionEnvironment(prepared) {\n    if (!prepared.sessionEnvironment) {\n        throw new Error('Prepared Smart Session environment is missing');\n    }\n    return prepared.sessionEnvironment;\n}\n","import { IndependentSigningNotSupportedError, InvalidOwnerSigningOptionsError, UnknownOwnerError, UnsupportedSigningRequestError, } from '../../errors/execution.js';\nimport { encodeValidatorId } from '../../modules/validators/multi-factor.js';\nimport { buildQuorumMerkleTree, getQuorumMerkleRootSignableHash, } from '../../modules/validators/quorum.js';\nimport { createAccountSigningContext, getAccountSignatureEnvelope, getSigningValidatorCodec, getSigningValidatorFactors, } from '../../signing/context.js';\nimport { executeSigningPlan } from '../../signing/execute.js';\nimport { resolveAccountValidatorSignableHash } from '../../signing/hash.js';\nimport { assembleIndependentIntentArtifact, } from '../../signing/intent-plans/independent.js';\nimport { createIntentSigningPlan, executeIntentSigning, projectIndependentSigning, } from '../../signing/intent-plans/plan.js';\nimport { createValidatorSigningTasks } from '../../signing/plan.js';\nimport { resolveAccountTypedDataSigning, } from '../../signing/typed-data.js';\nimport { signatureSpansMultipleChains } from './origin-chain.js';\nimport { assembleProofVector, requestSetId } from './proofs.js';\nimport { buildSessionIntentPlanInput, createIntentSessionSignerInvoker, } from './session-signing.js';\nexport async function signIntent(context, prepared) {\n    const runtime = await context.account.forChain(prepared.accountChain);\n    const ownerSelection = prepared.input.signers?.kind === 'owner'\n        ? prepared.input.signers\n        : undefined;\n    const signerInvoker = prepared.resolvedSessions\n        ? createIntentSessionSignerInvoker(prepared, context.signerInvoker)\n        : context.signerInvoker;\n    const signing = createAccountSigningContext({\n        runtime,\n        purpose: 'intent',\n        signerInvoker,\n        ...(ownerSelection ? { selection: ownerSelection } : {}),\n    });\n    const planInput = prepared.resolvedSessions\n        ? buildSessionIntentPlanInput(prepared, signing)\n        : buildIntentPlanInput(prepared, signing);\n    const transcript = await executeIntentSigning({\n        planInput,\n        context: signing,\n        checkpoints: context.checkpoints,\n    });\n    const outputs = Object.assign({}, ...transcript.stages.map((stage) => stage.outputs));\n    return {\n        prepared,\n        proofs: await collectOrderedProofs(context, prepared, outputs),\n        transcript,\n    };\n}\n/**\n * Builds the proof vector in quote order, one entry per signing request.\n *\n * Delegation proofs are collected here rather than by a separate caller step:\n * a quote that asks for one is not signed without it, and there is no order to\n * reconstruct later from a bag of authorisations.\n */\nasync function collectOrderedProofs(context, prepared, outputs) {\n    const proofs = [];\n    for (const request of prepared.signing.requests) {\n        switch (request.kind) {\n            case 'eip712':\n                proofs.push(eip712Proof(outputs[request.artifactId], request.index));\n                break;\n            case 'eip7702': {\n                const authorization = await context.signDelegation({\n                    chainId: request.chainId,\n                    contract: request.contract,\n                });\n                proofs.push({\n                    kind: 'eip7702',\n                    nonce: authorization.nonce,\n                    signature: {\n                        r: authorization.r,\n                        s: authorization.s,\n                        yParity: (authorization.yParity ?? 0) === 1 ? 1 : 0,\n                    },\n                });\n                break;\n            }\n            default:\n                throw new UnsupportedSigningRequestError({\n                    index: request.index,\n                    payloadKind: request.kind === 'unsupported' ? request.payloadKind : request.kind,\n                });\n        }\n    }\n    return proofs;\n}\nfunction eip712Proof(artifact, index) {\n    if (typeof artifact === 'string') {\n        return { kind: 'eip712', signature: artifact };\n    }\n    // A session origin carries both encodings of the one message in one proof;\n    // the halves are never swapped, and they are never split across two slots.\n    if (artifact && 'preClaimSig' in artifact) {\n        return {\n            kind: 'eip712',\n            signature: {\n                preClaim: artifact.preClaimSig,\n                notarizedClaim: artifact.notarizedClaimSig,\n            },\n        };\n    }\n    throw new Error(`Intent proof for signing request ${index} is missing`);\n}\nexport async function signIntentAsOwner(context, prepared, selection) {\n    const { signing, planInput } = await createIndependentSigningInput(context, prepared);\n    const owner = findIndependentOwner(signing, selection);\n    const { plan } = projectIndependentSigning(createIntentSigningPlan(planInput), [selection.signerId], [`${owner.ownerId}`]);\n    const transcript = await executeSigningPlan({\n        plan,\n        payloads: planInput.payloads,\n        checkpoints: context.checkpoints,\n        signerInvoker: signing.signerInvoker,\n        assembleStage: () => ({}),\n    });\n    // Whether the plan packed the payloads into one Merkle ceremony is the\n    // plan's decision, not one to re-derive here: look for the stage it would\n    // have produced and fall back to the per-request stages when it did not.\n    const quorumRootStage = signing.validator.kind === 'quorum'\n        ? transcript.stages.find(({ stage: materialized }) => materialized.stageId === 'quorum-origins')\n        : undefined;\n    const quorumRootResult = quorumRootStage\n        ? Object.entries(quorumRootStage.results).find(([taskId]) => taskId.includes(owner.ownerId))?.[1]\n        : undefined;\n    const slots = independentSlots(prepared).map((request) => {\n        const stage = quorumRootStage\n            ? undefined\n            : transcript.stages.find(({ stage: materialized }) => materialized.stageId === request.artifactId);\n        const result = quorumRootResult ??\n            (stage\n                ? Object.entries(stage.results).find(([taskId]) => taskId.includes(owner.ownerId))?.[1]\n                : undefined);\n        return independentSlotResult(owner, result);\n    });\n    const signature = owner.kind === 'ecdsa'\n        ? {\n            kind: 'ecdsa',\n            signer: owner.identity,\n            slots: slots,\n        }\n        : {\n            kind: 'passkey',\n            publicKey: owner.identity,\n            slots: slots,\n        };\n    return owner.factorPublicId === undefined\n        ? { intentId: prepared.quote.intentId, ...signature }\n        : {\n            intentId: prepared.quote.intentId,\n            kind: 'multi-factor',\n            validatorId: owner.factorPublicId,\n            signature,\n        };\n}\nexport async function assembleIntent(context, prepared, signatures, options) {\n    const { signing, planInput } = await createIndependentSigningInput(context, prepared);\n    const plan = createIntentSigningPlan(planInput);\n    const owners = independentOwners(signing);\n    const slots = independentSlots(prepared);\n    const assembled = Object.fromEntries(slots.map((request, slotIndex) => {\n        const artifact = plan.stages\n            .flatMap(({ artifacts }) => artifacts)\n            .find(({ id }) => id === request.artifactId);\n        if (!artifact) {\n            throw new Error(`Intent ${request.artifactId} assembly route is missing`);\n        }\n        return [\n            request.artifactId,\n            assembleIndependentIntentArtifact({\n                intentId: prepared.quote.intentId,\n                slotIndex,\n                slotCount: slots.length,\n                signatures,\n                owners,\n                artifact,\n                context: signing,\n            }),\n        ];\n    }));\n    const local = new Map();\n    for (const request of prepared.signing.requests) {\n        if (request.kind !== 'eip712')\n            continue;\n        const source = request.reuse?.artifactId ?? request.artifactId;\n        const signature = assembled[source];\n        // Anything the owners could not produce — a target execution payload, a\n        // requested delegation — has to arrive as an indexed contribution instead\n        // of being quietly dropped from the vector.\n        if (!signature)\n            continue;\n        local.set(request.index, { kind: 'eip712', signature });\n    }\n    return {\n        prepared,\n        proofs: assembleProofVector({\n            intentId: prepared.quote.intentId,\n            requestSetId: requestSetId(prepared.quote.signingRequests),\n            requests: prepared.signing.requests,\n            local,\n            ...(options?.proofs ? { contributions: options.proofs } : {}),\n        }),\n        transcript: {\n            planKind: 'intent-full',\n            payloadId: plan.payload.id,\n            stages: [],\n        },\n    };\n}\n/**\n * The request slots an independent owner signs, in order. Reused slots are not\n * among them: they are satisfied by the signature of the slot they reuse.\n */\nfunction independentSlots(prepared) {\n    return prepared.signing.requests.filter((request) => request.kind === 'eip712' && request.exposedForIndependentSigning);\n}\nasync function createIndependentSigningInput(context, prepared) {\n    if (prepared.resolvedSessions) {\n        throw new IndependentSigningNotSupportedError();\n    }\n    const runtime = await context.account.forChain(prepared.accountChain);\n    const signing = createAccountSigningContext({\n        runtime,\n        purpose: 'intent',\n        signerInvoker: context.signerInvoker,\n        ...(prepared.input.signers?.kind === 'owner'\n            ? { selection: prepared.input.signers }\n            : {}),\n    });\n    if (!signing.validatorCapabilities.supportsIndependentSigning) {\n        throw new IndependentSigningNotSupportedError();\n    }\n    return {\n        signing,\n        planInput: buildIntentPlanInput(prepared, signing),\n    };\n}\nfunction independentOwners(context) {\n    if (context.validator.kind !== 'multi-factor') {\n        return context.validator.owners.map((owner) => independentOwner(owner));\n    }\n    return context.validator.validators.flatMap((factor) => factor.owners.map((owner) => independentOwner(owner, factor.id, factor.publicId)));\n}\nfunction findIndependentOwner(context, selection) {\n    if (context.validator.kind !== 'multi-factor') {\n        if (selection.validatorId !== undefined) {\n            throw new InvalidOwnerSigningOptionsError({\n                context: { validatorId: selection.validatorId },\n            });\n        }\n        const owner = independentOwners(context).find((candidate) => candidate.signerId === selection.signerId);\n        if (!owner)\n            throw unknownOwner(selection);\n        return owner;\n    }\n    if (selection.validatorId === undefined) {\n        throw new InvalidOwnerSigningOptionsError({\n            context: { validatorId: selection.validatorId },\n        });\n    }\n    const factor = context.validator.validators.find((candidate) => sameValidatorId(candidate.publicId, selection.validatorId));\n    if (!factor) {\n        throw new InvalidOwnerSigningOptionsError({\n            context: { validatorId: selection.validatorId },\n        });\n    }\n    const owner = independentOwners(context).find((candidate) => candidate.factorId === factor.id &&\n        candidate.signerId === selection.signerId);\n    if (!owner)\n        throw unknownOwner(selection);\n    return owner;\n}\nfunction sameValidatorId(left, right) {\n    try {\n        return (encodeValidatorId(left).toLowerCase() ===\n            encodeValidatorId(right).toLowerCase());\n    }\n    catch {\n        return false;\n    }\n}\nfunction unknownOwner(selection) {\n    const [kind, identity] = selection.signerId.split(':', 2);\n    return new UnknownOwnerError({\n        context: {\n            ...(kind === 'webauthn' ? { publicKey: identity } : { signer: identity }),\n            ...(selection.validatorId === undefined\n                ? {}\n                : { validatorId: selection.validatorId }),\n        },\n    });\n}\nfunction independentOwner(owner, factorId, factorPublicId) {\n    return {\n        ownerId: owner.id,\n        signerId: owner.signerId,\n        identity: owner.kind === 'webauthn'\n            ? owner.account.publicKey\n            : owner.account.address,\n        kind: owner.kind === 'webauthn' ? 'webauthn' : 'ecdsa',\n        ...(factorId ? { factorId } : {}),\n        ...(factorPublicId === undefined ? {} : { factorPublicId }),\n    };\n}\nfunction independentSlotResult(owner, result) {\n    if (owner.kind === 'ecdsa') {\n        if (result?.kind !== 'ecdsa-signature') {\n            throw new Error(`Independent owner ${owner.ownerId} did not sign`);\n        }\n        return result.signature;\n    }\n    if (result?.kind !== 'webauthn-assertion') {\n        throw new Error(`Independent owner ${owner.ownerId} did not sign`);\n    }\n    return {\n        signature: result.signature,\n        webauthn: {\n            authenticatorData: result.authenticatorData,\n            challengeIndex: result.challengeIndex,\n            clientDataJSON: result.clientDataJSON,\n            typeIndex: result.typeIndex,\n            userVerificationRequired: result.userVerificationRequired,\n        },\n    };\n}\nfunction buildIntentPlanInput(prepared, context) {\n    const payloads = {};\n    const stages = [];\n    // A chain-agnostic origin is deliberately excluded: every leaf here is hashed\n    // with its own chain id, so it would be bound to the leg the payload happens\n    // to name. Routing it down the plain branch instead reaches the one refusal\n    // in `resolveAccountTypedDataSigning`.\n    const signable = prepared.signing.requests.filter((request) => request.kind === 'eip712' && !request.reuse);\n    const reused = prepared.signing.requests.filter((request) => request.kind === 'eip712' && Boolean(request.reuse));\n    const quorumMerkle = context.validator.kind === 'quorum' &&\n        signable.length > 1 &&\n        !signable.some(({ payload }) => signatureSpansMultipleChains(payload.typedData))\n        ? buildQuorumMerkleTree(signable.map(({ payload }) => ({\n            account: context.account.address,\n            digest: resolveAccountValidatorSignableHash({\n                hash: payload.id,\n                chain: payload.chain,\n                context,\n            }),\n        })))\n        : undefined;\n    const quorumRootHash = quorumMerkle\n        ? getQuorumMerkleRootSignableHash({\n            validator: context.validatorCapabilities.compatibilityKey.moduleAddress,\n            root: quorumMerkle.root,\n        })\n        : undefined;\n    if (quorumMerkle && quorumRootHash) {\n        const first = signable[0];\n        const route = {\n            material: { kind: 'message', message: { raw: quorumRootHash } },\n            payloadKind: 'message',\n            ecdsaInvocation: 'ecdsa-sign-message',\n            webauthnInvocation: 'webauthn-sign-hash',\n            erc7739: { kind: 'none' },\n        };\n        payloads[first.payload.id] = route.material;\n        stages.push(quorumMerkleSigningStage({\n            requests: signable,\n            payloadId: first.payload.id,\n            context,\n            route,\n            proofs: quorumMerkle.operations,\n        }));\n    }\n    else {\n        for (const request of signable) {\n            const route = resolveAccountTypedDataSigning({\n                typedData: request.payload.typedData,\n                chain: request.payload.chain,\n                context,\n                validationHash: request.payload.id,\n                spansMultipleChains: signatureSpansMultipleChains(request.payload.typedData),\n            });\n            payloads[request.payload.id] = route.material;\n            stages.push(signingStage({\n                id: request.artifactId,\n                payloadId: request.payload.id,\n                chain: request.payload.chain,\n                usage: request.payload.usage,\n                context,\n                route,\n            }));\n        }\n    }\n    for (const request of reused) {\n        const reuse = request.reuse;\n        const stageId = quorumMerkle ? 'quorum-origins' : reuse.artifactId;\n        stages.push({\n            id: request.artifactId,\n            checkpoint: { kind: 'none', id: `${request.artifactId}:none` },\n            priorOutputs: [\n                {\n                    stageId,\n                    outputId: reuse.artifactId,\n                    selection: reuse.selection,\n                },\n            ],\n            tasks: [],\n            schedule: [],\n            artifacts: [\n                {\n                    id: request.artifactId,\n                    usage: request.payload.usage,\n                    input: {\n                        kind: 'reuse-artifact',\n                        stageId,\n                        artifactId: reuse.artifactId,\n                        selection: reuse.selection,\n                    },\n                    validatorCodec: { kind: 'none' },\n                    erc7739: { kind: 'none' },\n                    accountEnvelope: { kind: 'none' },\n                    erc6492: { kind: 'none' },\n                },\n            ],\n        });\n    }\n    return { intent: prepared.signing, stages, payloads };\n}\nfunction quorumMerkleSigningStage(input) {\n    const tasks = createValidatorSigningTasks({\n        validator: input.context.validator,\n        signerReferences: input.context.signerReferences,\n        taskPrefix: 'quorum-root',\n        ecdsaInvocation: input.route.ecdsaInvocation,\n        webauthnInvocation: input.route.webauthnInvocation,\n        selectedSignerIds: input.context.effectiveSigners.signerIds,\n    }).map((task) => ({\n        ...task,\n        payload: { source: 'plan-payload', payloadId: input.payloadId },\n    }));\n    const validatorCodec = getSigningValidatorCodec(input.context, input.route.payloadKind);\n    return {\n        id: 'quorum-origins',\n        checkpoint: { kind: 'none', id: 'quorum-origins:none' },\n        priorOutputs: [],\n        tasks,\n        schedule: [\n            {\n                id: 'quorum-root:signers',\n                execution: 'parallel',\n                taskIds: tasks.map(({ id }) => id),\n            },\n        ],\n        artifacts: input.requests.map((request, index) => ({\n            id: request.artifactId,\n            usage: request.payload.usage,\n            input: { kind: 'task-results', taskIds: tasks.map(({ id }) => id) },\n            validatorCodec,\n            quorumMerkleProof: input.proofs[index],\n            erc7739: { kind: 'none' },\n            accountEnvelope: getAccountSignatureEnvelope(input.context),\n            erc6492: { kind: 'none' },\n        })),\n    };\n}\nfunction signingStage(input) {\n    const direct = input.context.account.definition.kind === 'eoa';\n    const tasks = input.reuseStageId\n        ? []\n        : direct\n            ? eoaTask(input)\n            : createValidatorSigningTasks({\n                validator: input.context.validator,\n                signerReferences: input.context.signerReferences,\n                taskPrefix: input.id,\n                ecdsaInvocation: input.route.ecdsaInvocation,\n                webauthnInvocation: input.route.webauthnInvocation,\n                selectedSignerIds: input.context.effectiveSigners.signerIds,\n            }).map((task) => ({\n                ...task,\n                chain: input.chain,\n                payload: { source: 'plan-payload', payloadId: input.payloadId },\n            }));\n    const artifact = {\n        id: input.id,\n        usage: input.usage,\n        input: input.reuseStageId\n            ? {\n                kind: 'reuse-artifact',\n                stageId: input.reuseStageId,\n                artifactId: input.reuseStageId,\n                selection: 'whole',\n            }\n            : { kind: 'task-results', taskIds: tasks.map(({ id }) => id) },\n        validatorCodec: input.reuseStageId\n            ? { kind: 'none' }\n            : direct\n                ? { kind: 'none' }\n                : getSigningValidatorCodec(input.context, input.route.payloadKind),\n        ...(!direct &&\n            !input.reuseStageId &&\n            input.context.validator.kind === 'multi-factor'\n            ? {\n                validatorFactors: getSigningValidatorFactors(input.context, input.route.payloadKind),\n            }\n            : {}),\n        ...(input.quorumMerkleProof\n            ? { quorumMerkleProof: input.quorumMerkleProof }\n            : {}),\n        erc7739: input.route.erc7739,\n        accountEnvelope: direct\n            ? { kind: 'none' }\n            : getAccountSignatureEnvelope(input.context),\n        erc6492: { kind: 'none' },\n    };\n    return {\n        id: input.id,\n        checkpoint: { kind: 'none', id: `${input.id}:none` },\n        priorOutputs: input.reuseStageId\n            ? [\n                {\n                    stageId: input.reuseStageId,\n                    outputId: input.reuseStageId,\n                    selection: 'whole',\n                },\n            ]\n            : [],\n        tasks,\n        schedule: tasks.length === 0\n            ? []\n            : [\n                {\n                    id: `${input.id}:signers`,\n                    execution: input.context.validator.kind === 'multi-factor'\n                        ? 'serial'\n                        : 'parallel',\n                    taskIds: tasks.map(({ id }) => id),\n                },\n            ],\n        artifacts: [artifact],\n    };\n}\nfunction eoaTask(input) {\n    const signer = Object.values(input.context.signerReferences)[0];\n    if (!signer)\n        throw new Error('EOA signer is missing');\n    return [\n        {\n            id: `${input.id}:eoa`,\n            signer,\n            role: 'owner',\n            chain: input.chain,\n            invocationKind: 'ecdsa-sign-typed-data',\n            payload: { source: 'plan-payload', payloadId: input.payloadId },\n        },\n    ];\n}\n","import { chainIdFromReference } from '../../chains/caip2.js';\nexport async function submitIntent(context, signed) {\n    // Submission carries the intent id and the ordered proofs, nothing else: no\n    // signatures are acquired here, no mutable nonce state is read, and no\n    // sponsorship grant is requested: that was presented with the quote.\n    const response = await context.submissionClient.submitIntent({\n        intentId: signed.prepared.quote.intentId,\n        proofs: signed.proofs,\n        ...(signed.dryRun ? { dryRun: true } : {}),\n    });\n    return {\n        type: 'intent',\n        traceId: response.traceId,\n        intentId: response.intentId,\n        ...(signed.prepared.input.sourceChains\n            ? {\n                sourceChains: signed.prepared.input.sourceChains.map(({ id }) => id),\n            }\n            : {}),\n        targetChain: chainIdFromReference(signed.prepared.input.destination),\n    };\n}\n","import { prepareIntent } from './prepare.js';\nimport { signIntent } from './sign-transaction.js';\nimport { submitIntent } from './submit.js';\nexport async function sendIntent(context, input) {\n    const prepared = await prepareIntent(context, input);\n    // `signIntent` produces the complete ordered proof vector, including any\n    // EIP-7702 delegation the quote asked for, so there is no separate\n    // authorization step to fold in here.\n    const signed = await signIntent(context, prepared);\n    return submitIntent(context, signed);\n}\n","import { hexToBytes, isHex } from 'viem';\nimport { isManagedSwigNamespace, locateSwigById, } from '../../accounts/solana/address.js';\nimport { formatCaip2 } from '../../chains/caip2.js';\nimport { projectCompatibleIntentInput } from '../../clients/orchestrator/normalized.js';\nimport { InvalidSolanaTransactionArtifactError } from '../../errors/execution.js';\nimport { assertSolanaNotExpired, solanaChainId, } from './solana.js';\nfunction refuse(reason, intentId) {\n    throw new InvalidSolanaTransactionArtifactError(reason, intentId === undefined ? undefined : { intentId });\n}\nfunction assertInitAuthority(input) {\n    const { authorization, initAuthority } = input;\n    if (authorization.kind !== initAuthority.kind) {\n        refuse('the installed authority must be the configured Solana owner');\n    }\n    if (initAuthority.kind === 'secp256r1' &&\n        (authorization.kind !== 'secp256r1' ||\n            !/^0x0[23][0-9a-fA-F]{64}$/u.test(initAuthority.publicKey) ||\n            initAuthority.publicKey.toLowerCase() !==\n                authorization.publicKey.toLowerCase())) {\n        refuse('the installed passkey must be the configured 33-byte compressed P-256 key');\n    }\n    if (initAuthority.kind === 'secp256k1' &&\n        !/^0x(?:0[23][0-9a-fA-F]{64}|04[0-9a-fA-F]{128})$/u.test(initAuthority.publicKey)) {\n        refuse('the installed ECDSA authority must be a SEC1 secp256k1 public key');\n    }\n}\nexport function buildSolanaDeploymentRequest(input) {\n    const chainId = solanaChainId(input.chain);\n    const caip2 = formatCaip2(chainId);\n    if (!isManagedSwigNamespace(input.namespace)) {\n        refuse('the managed account namespace must be dev-v1 or prod-v1');\n    }\n    if (!isHex(input.swigId) || hexToBytes(input.swigId).length !== 32) {\n        refuse('the Swig id must be 32 bytes of hex');\n    }\n    const location = locateSwigById(hexToBytes(input.swigId));\n    if (location.swig !== input.swigAddress ||\n        location.wallet !== input.walletAddress) {\n        refuse('the Swig id does not derive the configured Swig and wallet');\n    }\n    assertInitAuthority(input);\n    // The Solana-only shape: no `evm` entry, so the id is sent explicitly, even\n    // for the Swig the managed EVM account derives.\n    const svm = {\n        type: 'swig',\n        address: input.walletAddress,\n        swigAccount: input.swigAddress,\n        authorization: input.authorization,\n        initData: {\n            authority: input.initAuthority,\n            id: input.swigId.toLowerCase(),\n        },\n    };\n    // Gas only: Solana routes refuse the other sponsorship categories. They are\n    // spelled out so the request says exactly what the approval input does.\n    const sponsorship = { gas: true, bridgeFees: false, swapFees: false };\n    return {\n        request: {\n            account: { svm },\n            // No recipient, execution or token: that is what makes this a creation.\n            destination: { vm: 'svm', chainId: caip2, tokenRequests: [] },\n            source: { selection: { chains: { only: [caip2] }, tokens: 'all' } },\n            options: { sponsorship },\n        },\n        normalized: {\n            account: { address: input.walletAddress, svm },\n            destinationChainId: chainId,\n            destinationExecutions: [],\n            tokenRequests: [],\n            accountAccessList: { chainIds: [chainId] },\n            options: { sponsorSettings: sponsorship },\n        },\n    };\n}\nfunction sameAuthority(actual, expected) {\n    if (!actual)\n        return false;\n    return expected.kind === 'secp256r1'\n        ? actual.kind === 'secp256r1' &&\n            actual.publicKey.toLowerCase() === expected.publicKey.toLowerCase()\n        : actual.kind === 'secp256k1' &&\n            actual.address.toLowerCase() === expected.address.toLowerCase();\n}\n/**\n * Checks a route creates exactly the configured Swig, with the configured\n * owner as its root, on the requested cluster — and asks for nothing else.\n * Creation is permanent, so anything unexpected is refused before submission.\n */\nfunction validateDeploymentQuote(quote, input) {\n    if (!quote.intentId) {\n        refuse('the quote must carry an intent id');\n    }\n    const reject = (reason) => refuse(reason, quote.intentId);\n    if (quote.purpose !== 'deployment') {\n        return reject('the quote must be a deployment route');\n    }\n    if (quote.signingRequests.length > 0) {\n        reject('a deployment route must ask for no signatures');\n    }\n    if (quote.requirements.length > 0) {\n        reject('a deployment route must have no requirements');\n    }\n    const chainId = formatCaip2(solanaChainId(input.chain));\n    const deployments = quote.plan.deployments;\n    const deployment = deployments[0];\n    const account = deployment?.account;\n    if (deployments.length !== 1 ||\n        !deployment ||\n        deployment.vm !== 'svm' ||\n        deployment.chainId !== chainId ||\n        !account ||\n        !('swigAccount' in account) ||\n        account.swigAccount !== input.swigAddress ||\n        account.wallet !== input.walletAddress) {\n        reject('the deployment must create exactly the configured Swig and wallet on the requested Solana chain');\n    }\n    if (!sameAuthority(account.authority, input.authorization)) {\n        reject('the deployment must install the configured Solana owner');\n    }\n    if (quote.deploymentCosts.some((cost) => cost.chainId !== chainId)) {\n        reject('every deployment cost must reference the requested Solana chain');\n    }\n    return quote;\n}\nexport async function prepareSolanaDeployment(context, input) {\n    const { request, normalized } = buildSolanaDeploymentRequest(input);\n    const response = await context.quoteClient.createQuote(request, {\n        intentInput: projectCompatibleIntentInput(normalized),\n        sponsored: true,\n    });\n    if (response.routes.length === 0) {\n        refuse('the orchestrator returned no quote');\n    }\n    const quotes = response.routes.map((route) => validateDeploymentQuote(route, input));\n    const quote = quotes[0];\n    assertSolanaNotExpired(context.now(), quote);\n    return { traceId: response.traceId, input, request, normalized, quote };\n}\nexport async function submitSolanaDeployment(context, prepared) {\n    assertSolanaNotExpired(context.now(), prepared.quote);\n    const response = await context.submissionClient.submitIntent({\n        intentId: prepared.quote.intentId,\n        proofs: [],\n    });\n    const chainId = solanaChainId(prepared.input.chain);\n    return {\n        type: 'intent',\n        traceId: response.traceId,\n        intentId: response.intentId,\n        sourceChains: [chainId],\n        targetChain: chainId,\n    };\n}\n","export function splitIntents(client, input) {\n    return client.splitIntents(input);\n}\n","import { isConnectionError, isRateLimited, isRetryable, RateLimitedError, } from '../../clients/orchestrator/errors.js';\nconst slowDelayMs = 2_000;\nexport function classifyIntentStatus(status) {\n    return {\n        traceId: status.traceId,\n        intentId: status.intentId,\n        purpose: status.purpose,\n        status: status.status,\n        // Spread so an unknown value stays an absent key rather than becoming\n        // `undefined` — the distinction these fields rest on.\n        ...(status.accounts ? { accounts: [...status.accounts] } : {}),\n        operations: [...status.operations],\n        ...(status.refunds ? { refunds: [...status.refunds] } : {}),\n        ...(status.details ? { details: status.details } : {}),\n        terminal: status.status === 'COMPLETED' || status.status === 'FAILED',\n    };\n}\nexport function getIntentRetryDelay(input) {\n    if (!isRetryable(input.error) &&\n        !isRateLimited(input.error) &&\n        !isConnectionError(input.error)) {\n        return undefined;\n    }\n    if (!(input.error instanceof RateLimitedError)) {\n        return { delay: input.fallback, backoff: true };\n    }\n    if (!input.error.retryAfter) {\n        return { delay: Math.max(slowDelayMs, input.minimum), backoff: false };\n    }\n    const seconds = Number(input.error.retryAfter);\n    if (!Number.isNaN(seconds)) {\n        return {\n            delay: Math.max(seconds * 1_000, input.minimum),\n            backoff: false,\n        };\n    }\n    const date = Date.parse(input.error.retryAfter);\n    return {\n        delay: Number.isNaN(date)\n            ? input.minimum\n            : Math.max(date - input.now, input.minimum),\n        backoff: false,\n    };\n}\n","import { IntentFailedError } from '../../errors/execution.js';\nimport { classifyIntentStatus, getIntentRetryDelay } from './status-policy.js';\nconst initialDelayMs = 500;\nconst slowAfterMs = 15_000;\nconst slowDelayMs = 2_000;\nconst initialErrorBackoffMs = 1_000;\nconst maximumErrorBackoffMs = 10_000;\nexport async function getIntentStatus(context, intentId, options) {\n    return classifyIntentStatus(await context.statusClient.getIntentStatus(intentId, options?.full ? { full: true } : undefined));\n}\nexport async function waitForIntentStatus(context, intentId) {\n    const startedAt = context.clock.now();\n    let nextDelay = initialDelayMs;\n    let errorBackoff = initialErrorBackoffMs;\n    for (;;) {\n        let status;\n        try {\n            status = await getIntentStatus(context, intentId);\n            errorBackoff = initialErrorBackoffMs;\n            nextDelay =\n                context.clock.now() - startedAt >= slowAfterMs\n                    ? slowDelayMs\n                    : initialDelayMs;\n            await context.clock.sleep(nextDelay);\n        }\n        catch (error) {\n            const retryDelay = getIntentRetryDelay({\n                error,\n                now: context.clock.now(),\n                minimum: nextDelay,\n                fallback: errorBackoff,\n            });\n            if (retryDelay === undefined)\n                throw error;\n            await context.clock.sleep(retryDelay.delay);\n            if (retryDelay.backoff) {\n                errorBackoff = Math.min(errorBackoff * 2, maximumErrorBackoffMs);\n            }\n            continue;\n        }\n        if (!status.terminal)\n            continue;\n        if (status.status === 'FAILED') {\n            // The refunds ride the ERROR, because this is the only path they can\n            // take: a refunded intent, or one whose HyperCore action was refused, is\n            // still `FAILED` — it did not do what was asked — so this throws and the\n            // caller never sees a returned status. Omitting them would hide the\n            // refund from `waitForExecution` for the exact case the field exists to\n            // answer; a refused trade's onchain operations all read COMPLETED, and\n            // the EXECUTION item in `operations` is what says whether a retry is safe.\n            throw new IntentFailedError({\n                context: {\n                    intentId,\n                    operations: status.operations,\n                    ...(status.refunds ? { refunds: status.refunds } : {}),\n                },\n            });\n        }\n        return status;\n    }\n}\n","import { entryPoint07Address, getUserOperationHash, } from 'viem/account-abstraction';\nexport function hashUserOperation(chain, operation) {\n    return getUserOperationHash({\n        userOperation: operation,\n        chainId: chain.id,\n        entryPointAddress: entryPoint07Address,\n        entryPointVersion: '0.7',\n    });\n}\n","import { concat, toHex, zeroAddress } from 'viem';\nimport { entryPoint07Address } from 'viem/account-abstraction';\nconst getNonceAbi = [\n    {\n        type: 'function',\n        name: 'getNonce',\n        stateMutability: 'view',\n        inputs: [\n            { name: 'sender', type: 'address' },\n            { name: 'key', type: 'uint192' },\n        ],\n        outputs: [{ name: 'nonce', type: 'uint256' }],\n    },\n];\nexport function getUserOperationNonceKey(input) {\n    if (input.requested !== undefined)\n        return input.requested;\n    switch (input.accountKind) {\n        case 'safe':\n            return BigInt(concat([input.validator, '0x00000000']));\n        case 'kernel':\n            return BigInt(concat(['0x0000', input.validator, '0x0000']));\n        case 'nexus':\n        case 'startale':\n        case 'hca': {\n            const validator = input.defaultValidator?.toLowerCase() === input.validator.toLowerCase()\n                ? zeroAddress\n                : input.validator;\n            const lane = (input.lane ?? 0n) % 16777215n;\n            return BigInt(concat([toHex(lane, { size: 3 }), '0x00', validator]));\n        }\n        case 'eoa':\n            throw new Error('EOA accounts do not support UserOperations');\n    }\n}\nexport async function readUserOperationNonce(input) {\n    return input.rpc.readContract({ chain: input.chain }, {\n        address: entryPoint07Address,\n        abi: getNonceAbi,\n        functionName: 'getNonce',\n        args: [input.sender, input.key],\n    });\n}\n","import { encodeMultiFactorContribution } from '../../modules/validators/multi-factor.js';\nimport { encodeOwnableMockSignature } from '../../modules/validators/ownable.js';\nimport { encodeQuorumMockSignature } from '../../modules/validators/quorum.js';\nimport { resolveValidator } from '../../modules/validators/resolve.js';\nimport { WEBAUTHN_MOCK_SIGNATURE, webauthnStatelessMockSignature, } from '../../modules/validators/webauthn.js';\nexport function getUserOperationStubSignature(runtime, context) {\n    if (!runtime.adapter.capabilities.supportsUserOperations) {\n        throw new Error(`Account ${runtime.construction.account.kind} does not support UserOperations`);\n    }\n    if (context.validator.kind === 'passkey')\n        return WEBAUTHN_MOCK_SIGNATURE;\n    if (context.validator.kind === 'quorum') {\n        return encodeQuorumMockSignature(context.validator);\n    }\n    if (context.validator.kind === 'multi-factor') {\n        return encodeMultiFactorContribution({\n            factorOrder: context.validator.validators.map(({ id }) => id),\n            threshold: context.validator.threshold,\n            contributions: context.validator.validators.map((validator) => ({\n                factorId: validator.id,\n                publicId: validator.publicId,\n                validator: resolveValidator(validator).address,\n                contribution: validator.kind === 'passkey'\n                    ? webauthnStatelessMockSignature()\n                    : encodeOwnableMockSignature(validator.owners.length),\n            })),\n        });\n    }\n    return encodeOwnableMockSignature(context.validator.owners.length);\n}\n","import { K1_DEFAULT_VALIDATOR_ADDRESS } from '../../accounts/adapters/startale.js';\nimport { resolveCalls } from '../../calls/resolve.js';\nimport { ENS_HCA_MODULE } from '../../modules/validators/ens.js';\nimport { OWNABLE_VALIDATOR_ADDRESS } from '../../modules/validators/ownable.js';\nimport { createAccountSigningContext, getSigningValidatorCodec, getSigningValidatorFactors, } from '../../signing/context.js';\nimport { createValidatorSigningTasks, signingTopology, } from '../../signing/plan.js';\nimport { hashUserOperation } from './hash.js';\nimport { getUserOperationNonceKey, readUserOperationNonce } from './nonce.js';\nimport { getUserOperationStubSignature } from './validator-account.js';\nexport async function prepareUserOperation(context, input) {\n    const runtime = await context.account.forChain(input.chain);\n    const signingContext = createAccountSigningContext({\n        runtime,\n        purpose: 'user-operation',\n        signerInvoker: context.signerInvoker,\n        ...(input.signers ? { selection: input.signers } : {}),\n    });\n    const calls = await resolveCalls(input.calls, {\n        account: runtime.identity.address,\n        chain: input.chain,\n        config: context.compatibilityConfig,\n    });\n    const nonce = await readUserOperationNonce({\n        rpc: context.rpc.forChain(input.chain),\n        chain: input.chain,\n        sender: runtime.identity.address,\n        key: getUserOperationNonceKey({\n            accountKind: runtime.construction.account.kind,\n            validator: signingContext.validatorCapabilities.compatibilityKey.moduleAddress,\n            defaultValidator: defaultUserOperationValidator(runtime.construction),\n            lane: BigInt(context.clock.now()),\n            ...(input.nonceKey === undefined ? {} : { requested: input.nonceKey }),\n        }),\n    });\n    const deployment = runtime.adapter.getDeploymentPlan(runtime.construction);\n    const gasPrice = await context.bundler.getGasPrice(input.chain);\n    let operation = {\n        sender: runtime.identity.address,\n        nonce,\n        ...(deployment.deployed || !deployment.factory || !deployment.factoryData\n            ? {}\n            : {\n                factory: deployment.factory,\n                factoryData: deployment.factoryData,\n            }),\n        callData: runtime.adapter.encodeCalls({\n            chain: input.chain,\n            calls,\n            mode: calls.length > 1 ? 'batch' : 'single',\n        }),\n        callGasLimit: input.gasLimit ?? 0n,\n        verificationGasLimit: 0n,\n        preVerificationGas: 0n,\n        maxFeePerGas: gasPrice.maxFeePerGas,\n        maxPriorityFeePerGas: gasPrice.maxPriorityFeePerGas,\n        signature: getUserOperationStubSignature(runtime, signingContext),\n    };\n    let paymasterIsFinal = false;\n    if (context.paymaster) {\n        const { isFinal, ...stub } = await context.paymaster.getStubData(input.chain, operation);\n        paymasterIsFinal = isFinal;\n        operation = {\n            ...operation,\n            ...stub,\n        };\n    }\n    const gas = await context.bundler.estimateGas(input.chain, operation);\n    const paymasterGas = {\n        ...(operation.paymasterVerificationGasLimit === undefined\n            ? {}\n            : {\n                paymasterVerificationGasLimit: operation.paymasterVerificationGasLimit,\n            }),\n        ...(operation.paymasterPostOpGasLimit === undefined\n            ? {}\n            : { paymasterPostOpGasLimit: operation.paymasterPostOpGasLimit }),\n    };\n    operation = {\n        ...operation,\n        ...gas,\n        ...paymasterGas,\n        ...(input.gasLimit === undefined ? {} : { callGasLimit: input.gasLimit }),\n    };\n    if (context.paymaster && !paymasterIsFinal) {\n        operation = {\n            ...operation,\n            ...(await context.paymaster.getData(input.chain, operation)),\n        };\n    }\n    const hash = hashUserOperation(input.chain, operation);\n    return {\n        input,\n        operation,\n        hash,\n        signing: buildUserOperationSigningPlanInput(signingContext, input.chain, hash),\n    };\n}\nfunction defaultUserOperationValidator(construction) {\n    switch (construction.account.kind) {\n        case 'nexus':\n            return OWNABLE_VALIDATOR_ADDRESS;\n        case 'startale':\n            return K1_DEFAULT_VALIDATOR_ADDRESS;\n        case 'hca':\n            return ENS_HCA_MODULE;\n        case 'safe':\n        case 'kernel':\n        case 'eoa':\n            return undefined;\n    }\n}\n/**\n * Builds the validator signing-plan input for a UserOperation hash. Shared by\n * preparation and reconstruction so both derive an identical signing plan.\n */\nexport function buildUserOperationSigningPlanInput(signingContext, chain, hash) {\n    const selectedSignerIds = signingContext.effectiveSigners.signerIds;\n    const tasks = createValidatorSigningTasks({\n        validator: signingContext.validator,\n        signerReferences: signingContext.signerReferences,\n        taskPrefix: 'user-operation',\n        ecdsaInvocation: 'ecdsa-sign-message',\n        webauthnInvocation: 'webauthn-sign-hash',\n        selectedSignerIds,\n    });\n    const topology = signingTopology(signingContext.validator, selectedSignerIds);\n    return {\n        hash,\n        chain,\n        configuredTopology: topology.configuredTopology,\n        effectiveSelection: topology.effectiveSelection,\n        tasks,\n        validatorCodec: getSigningValidatorCodec(signingContext),\n        ...(signingContext.validator.kind === 'multi-factor'\n            ? { validatorFactors: getSigningValidatorFactors(signingContext) }\n            : {}),\n    };\n}\n","import { createAccountSigningContext } from '../../signing/context.js';\nimport { hashUserOperation } from './hash.js';\nimport { buildUserOperationSigningPlanInput } from './prepare.js';\n/**\n * Rebuilds the internal PreparedUserOperation from a public prepared shape that\n * did not originate from this SDK instance (e.g. externally rebuilt, mutated to\n * add a paymaster, or replayed across instances). The signing plan is derived\n * from the account's static configuration, so this performs no RPC reads.\n */\nexport async function reconstructPreparedUserOperation(context, input) {\n    const runtime = await context.account.forChain(input.chain);\n    const signingContext = createAccountSigningContext({\n        runtime,\n        purpose: 'user-operation',\n        signerInvoker: context.signerInvoker,\n        ...(input.signers ? { selection: input.signers } : {}),\n    });\n    const hash = hashUserOperation(input.chain, input.operation);\n    return {\n        input: {\n            chain: input.chain,\n            calls: [],\n            ...(input.signers ? { signers: input.signers } : {}),\n        },\n        operation: input.operation,\n        hash,\n        signing: buildUserOperationSigningPlanInput(signingContext, input.chain, hash),\n    };\n}\n/**\n * Rebuilds the internal SignedUserOperation from a public signed shape that did\n * not originate from this SDK instance, so submission works with a rebuilt or\n * externally supplied signed UserOperation. Performs no RPC reads.\n */\nexport async function reconstructSignedUserOperation(context, input) {\n    const operation = { ...input.operation, signature: input.signature };\n    const prepared = await reconstructPreparedUserOperation(context, {\n        chain: input.chain,\n        operation,\n        ...(input.signers ? { signers: input.signers } : {}),\n    });\n    return {\n        prepared,\n        operation,\n        signature: input.signature,\n        transcript: {\n            planKind: 'user-operation',\n            payloadId: prepared.hash,\n            stages: [],\n        },\n    };\n}\n","import { encodePlannedValidatorContribution } from './contribution.js';\nimport { runSigningStep } from './error.js';\nimport { executeSigningPlan } from './execute.js';\nimport { createSingleStageSigningPlan } from './plan.js';\nexport function createUserOperationSigningPlan(input) {\n    return createSingleStageSigningPlan({\n        kind: 'user-operation',\n        payload: { kind: 'user-operation', id: input.hash },\n        configuredTopology: input.configuredTopology,\n        effectiveSelection: input.effectiveSelection,\n        stageId: 'user-operation',\n        chain: input.chain,\n        tasks: input.tasks,\n        artifacts: [\n            {\n                id: 'user-operation-signature',\n                usage: 'user-operation',\n                validatorCodec: input.validatorCodec,\n                ...(input.validatorFactors\n                    ? { validatorFactors: input.validatorFactors }\n                    : {}),\n                erc7739: { kind: 'none' },\n                accountEnvelope: { kind: 'none' },\n                erc6492: { kind: 'none' },\n            },\n        ],\n    });\n}\nexport async function signUserOperationPayload(input) {\n    const plan = createUserOperationSigningPlan(input.planInput);\n    const transcript = await executeSigningPlan({\n        plan,\n        payloads: {\n            [plan.payload.id]: {\n                kind: 'message',\n                message: { raw: input.planInput.hash },\n            },\n        },\n        signerInvoker: input.signerInvoker,\n        checkpoints: input.checkpoints,\n        assembleStage: ({ stagePlan, stage, results }) => {\n            const artifact = stagePlan.artifacts[0];\n            return {\n                [artifact.id]: runSigningStep({\n                    plan,\n                    failureStage: 'validator-encode',\n                    stageId: stage.stageId,\n                    artifactId: artifact.id,\n                    usage: artifact.usage,\n                    operation: () => encodePlannedValidatorContribution({\n                        artifact,\n                        stage,\n                        results,\n                    }),\n                }),\n            };\n        },\n    });\n    const signature = transcript.stages[0].outputs['user-operation-signature'];\n    return { signature, transcript };\n}\n","import { signUserOperationPayload } from '../../signing/user-operation.js';\nexport async function signUserOperation(context, prepared) {\n    const { signature, transcript } = await signUserOperationPayload({\n        planInput: prepared.signing,\n        signerInvoker: context.signerInvoker,\n        checkpoints: context.checkpoints,\n    });\n    return {\n        prepared,\n        operation: { ...prepared.operation, signature },\n        signature,\n        transcript,\n    };\n}\n","export async function submitUserOperation(context, signed) {\n    const operation = { ...signed.operation, signature: signed.signature };\n    return {\n        type: 'userop',\n        chain: signed.prepared.input.chain,\n        hash: await context.bundler.send(signed.prepared.input.chain, operation),\n    };\n}\n","import { prepareUserOperation } from './prepare.js';\nimport { signUserOperation } from './sign.js';\nimport { submitUserOperation } from './submit.js';\nexport async function sendUserOperation(context, input) {\n    const prepared = await prepareUserOperation(context, input);\n    const signed = await signUserOperation(context, prepared);\n    return submitUserOperation(context, signed);\n}\n","import { WaitForUserOperationReceiptTimeoutError } from 'viem/account-abstraction';\nimport { getChainById } from '../../chains/catalog.js';\nconst receiptTimeoutMs = 120_000;\nexport async function getUserOperationStatus(context, submitted) {\n    const receipt = await context.bundler.getReceipt(submitted.chain, submitted.hash);\n    return {\n        hash: submitted.hash,\n        ...(receipt ? { receipt } : {}),\n        terminal: receipt !== undefined,\n    };\n}\nexport async function waitForUserOperationStatus(context, submitted) {\n    const timeoutError = () => new WaitForUserOperationReceiptTimeoutError({ hash: submitted.hash });\n    return context.clock.timeout(pollForUserOperationStatus(context, submitted, timeoutError), receiptTimeoutMs, timeoutError);\n}\nasync function pollForUserOperationStatus(context, submitted, timeoutError) {\n    const startedAt = context.clock.now();\n    const blockTime = getChainById(submitted.chain.id).blockTime ?? 12_000;\n    const pollIntervalMs = Math.min(Math.max(Math.floor(blockTime / 2), 500), 4_000);\n    let waitedMs = 0;\n    for (;;) {\n        const status = await getUserOperationStatus(context, submitted);\n        if (status.terminal)\n            return status;\n        const elapsed = Math.max(context.clock.now() - startedAt, waitedMs);\n        const remaining = receiptTimeoutMs - elapsed;\n        if (remaining <= 0) {\n            throw timeoutError();\n        }\n        const delay = Math.min(pollIntervalMs, remaining);\n        await context.clock.sleep(delay);\n        waitedMs += delay;\n        if (Math.max(context.clock.now() - startedAt, waitedMs) >= receiptTimeoutMs) {\n            throw timeoutError();\n        }\n    }\n}\n","import { encodePacked, hashMessage, hashTypedData, pad, zeroHash, } from 'viem';\nimport { wrapKernelMessageHash } from '../accounts/kernel-signing.js';\nimport { defineValidator } from '../modules/validators/definition.js';\nimport { getPermissionId } from '../modules/validators/smart-sessions/digest.js';\nimport { getSmartSessionEmissaryAddress } from '../modules/validators/smart-sessions/module.js';\nimport { createAccountSigningContext, getAccountSignatureRoute, getSigningValidatorCodec, } from '../signing/context.js';\nimport { resolveAccountValidatorSignableHash } from '../signing/hash.js';\nimport { signAccountMessage } from '../signing/message.js';\nimport { createValidatorSigningTasks, signingTopology } from '../signing/plan.js';\nimport { resolveAccountTypedDataSigning, signAccountTypedData, } from '../signing/typed-data.js';\nexport async function signRuntimeMessage(input) {\n    if (input.session) {\n        return signSessionErc1271({\n            runtime: input.runtime,\n            signerInvoker: input.signerInvoker,\n            checkpoints: input.checkpoints,\n            chain: input.chain,\n            session: input.session,\n            contentHash: hashMessage(input.message),\n            nominalMessage: input.message,\n        });\n    }\n    const context = createAccountSigningContext({\n        runtime: input.runtime,\n        purpose: 'erc1271',\n        signerInvoker: input.signerInvoker,\n        ...(input.selection ? { selection: input.selection } : {}),\n    });\n    const topology = signingTopology(context.validator, input.selection?.signerIds);\n    const payload = hashMessage(input.message);\n    const signingMaterial = input.runtime.construction.account.kind === 'kernel' ||\n        context.validator.kind === 'quorum'\n        ? {\n            kind: 'message',\n            message: {\n                raw: resolveAccountValidatorSignableHash({\n                    hash: payload,\n                    chain: input.chain,\n                    context,\n                }),\n            },\n        }\n        : undefined;\n    const route = getAccountSignatureRoute(input.runtime, context);\n    return signAccountMessage({\n        context,\n        checkpoints: input.checkpoints,\n        planInput: {\n            message: input.message,\n            ...(signingMaterial ? { signingMaterial } : {}),\n            chain: input.chain,\n            ...topology,\n            tasks: createValidatorSigningTasks({\n                validator: context.validator,\n                signerReferences: context.signerReferences,\n                taskPrefix: 'message',\n                ecdsaInvocation: 'ecdsa-sign-message',\n                webauthnInvocation: 'webauthn-sign-hash',\n                ...(input.selection\n                    ? { selectedSignerIds: input.selection.signerIds }\n                    : {}),\n            }),\n            route,\n        },\n    });\n}\nexport async function signRuntimeTypedData(input) {\n    if (input.session) {\n        // Sessions sign an account-bound digest in direct (notarized) mode, the\n        // same shape signRuntimeMessage produces, so external ERC-1271 verifiers\n        // resolve the session validator directly.\n        const contentHash = hashTypedData(input.typedData);\n        return signSessionErc1271({\n            runtime: input.runtime,\n            signerInvoker: input.signerInvoker,\n            checkpoints: input.checkpoints,\n            chain: input.chain,\n            session: input.session,\n            contentHash,\n            nominalMessage: { raw: contentHash },\n        });\n    }\n    const context = createAccountSigningContext({\n        runtime: input.runtime,\n        purpose: 'erc1271',\n        signerInvoker: input.signerInvoker,\n        ...(input.selection ? { selection: input.selection } : {}),\n    });\n    const topology = signingTopology(context.validator, input.selection?.signerIds);\n    const route = resolveAccountTypedDataSigning({\n        typedData: input.typedData,\n        chain: input.chain,\n        context,\n    });\n    const accountRoute = getAccountSignatureRoute(input.runtime, context, route.erc7739, route.payloadKind);\n    return signAccountTypedData({\n        context,\n        checkpoints: input.checkpoints,\n        planInput: {\n            typedData: input.typedData,\n            signingMaterial: route.material,\n            chain: input.chain,\n            ...topology,\n            tasks: createValidatorSigningTasks({\n                validator: context.validator,\n                signerReferences: context.signerReferences,\n                taskPrefix: 'typed-data',\n                ecdsaInvocation: route.ecdsaInvocation,\n                webauthnInvocation: route.webauthnInvocation,\n                ...(input.selection\n                    ? { selectedSignerIds: input.selection.signerIds }\n                    : {}),\n            }),\n            route: accountRoute,\n        },\n    });\n}\n// Shared ERC-1271 signing for a session: the session owner signs an\n// account-bound digest (keccak of account ‖ contentHash) in the smart-session\n// \"notarized\" (direct) mode. Used by both message and typed-data signing so\n// they produce the identical on-chain-verifiable shape.\nasync function signSessionErc1271(input) {\n    assertDirectSessionSigning(input.session);\n    const selection = sessionOwnerSelection(input.session);\n    const context = createAccountSigningContext({\n        runtime: input.runtime,\n        purpose: 'erc1271',\n        signerInvoker: input.signerInvoker,\n        selection,\n    });\n    const topology = signingTopology(context.validator, selection.signerIds);\n    const accountHash = input.runtime.construction.account.kind === 'kernel'\n        ? wrapKernelMessageHash(input.contentHash, context.account.address)\n        : input.contentHash;\n    const route = getAccountSignatureRoute(input.runtime, context);\n    return signAccountMessage({\n        context,\n        checkpoints: input.checkpoints,\n        planInput: {\n            message: input.nominalMessage,\n            signingMaterial: {\n                kind: 'message',\n                message: {\n                    raw: hashMessage({\n                        raw: encodePacked(['bytes32', 'bytes32'], [pad(context.account.address, { size: 32 }), accountHash]),\n                    }),\n                },\n            },\n            chain: input.chain,\n            ...topology,\n            tasks: createValidatorSigningTasks({\n                validator: context.validator,\n                signerReferences: context.signerReferences,\n                taskPrefix: 'message',\n                ecdsaInvocation: 'ecdsa-sign-message',\n                webauthnInvocation: 'webauthn-sign-hash',\n                selectedSignerIds: selection.signerIds,\n            }),\n            route: {\n                ...route,\n                validatorCodec: {\n                    kind: 'smart-session',\n                    validator: {\n                        kind: 'validator',\n                        address: getSmartSessionEmissaryAddress(input.runtime.construction.sessions.environment),\n                    },\n                    mode: 'notarized',\n                    permissionId: getPermissionId(input.session.session),\n                    signerCodec: requireSessionOwnerCodec(getSigningValidatorCodec(context)),\n                },\n                accountEnvelope: smartSessionEnvelope(route.accountEnvelope, input.runtime.construction.sessions.environment),\n            },\n        },\n    });\n}\nfunction assertDirectSessionSigning(session) {\n    const allowedContents = session.session.erc7739Policies.allowedERC7739Content;\n    const allowsDirectSigning = allowedContents.some((content) => content.appDomainSeparator === zeroHash &&\n        content.contentNames.includes(''));\n    if (allowsDirectSigning)\n        return;\n    if (allowedContents.length === 0) {\n        throw new Error('This Smart Session has signing disabled');\n    }\n    throw new Error('Scoped Smart Session signing requires safe ERC-7739 emission, which is not available in this SDK');\n}\nfunction sessionOwnerSelection(session) {\n    const validator = defineValidator(session.session.owners, 'smart-session-validator');\n    return {\n        kind: 'owner',\n        validator,\n        signerIds: validator.kind === 'multi-factor'\n            ? validator.validators.flatMap((factor) => factor.owners.map(({ signerId }) => signerId))\n            : validator.owners.map(({ signerId }) => signerId),\n    };\n}\nfunction requireSessionOwnerCodec(codec) {\n    if (codec.kind === 'smart-session') {\n        throw new Error('A Smart Session owner cannot use a session validator');\n    }\n    return codec;\n}\nfunction smartSessionEnvelope(envelope, environment) {\n    if (envelope.kind === 'none')\n        return envelope;\n    const validator = getSmartSessionEmissaryAddress(environment);\n    return envelope.kind === 'kernel'\n        ? { ...envelope, validator, isRoot: false }\n        : { ...envelope, validator };\n}\n","import { hashMessage } from 'viem';\nimport { EoaSigningNotSupportedError } from '../accounts/error.js';\nimport { encodePlannedValidatorContribution } from './contribution.js';\nimport { runSigningStep } from './error.js';\nimport { executeSigningPlan } from './execute.js';\nimport { createSingleStageSigningPlan } from './plan.js';\nimport { wrapErc6492Signature } from './protocols/erc6492.js';\nexport function createMessageSigningPlan(input) {\n    return createSingleStageSigningPlan({\n        kind: 'account-message',\n        payload: { kind: 'message', id: hashMessage(input.message) },\n        configuredTopology: input.configuredTopology,\n        effectiveSelection: input.effectiveSelection,\n        stageId: 'message',\n        ...(input.checkpoint ? { checkpoint: input.checkpoint } : {}),\n        chain: input.chain,\n        tasks: input.tasks,\n        artifacts: [\n            {\n                id: 'message-signature',\n                usage: 'erc1271',\n                ...input.route,\n            },\n        ],\n    });\n}\nexport async function signAccountMessage(input) {\n    if (input.context.account.definition.kind === 'eoa') {\n        throw new EoaSigningNotSupportedError('packed signatures');\n    }\n    const plan = createMessageSigningPlan(input.planInput);\n    const transcript = await executeSigningPlan({\n        plan,\n        payloads: {\n            [plan.payload.id]: {\n                kind: 'message',\n                message: input.planInput.signingMaterial?.message ??\n                    { raw: plan.payload.id },\n            },\n        },\n        checkpoints: input.checkpoints,\n        signerInvoker: input.context.signerInvoker,\n        assembleStage: (stage) => assembleMessageStage(stage, input.context),\n    });\n    const signature = transcript.stages[0].outputs['message-signature'];\n    return { signature, transcript };\n}\nexport function assembleMessageStage(input, context) {\n    const artifact = input.stagePlan.artifacts[0];\n    if (!artifact)\n        throw new Error('Message plan has no artifact');\n    if (artifact.erc7739.kind !== 'none') {\n        throw new Error('ERC-7739 is not a message-signing operation');\n    }\n    const step = (failureStage, operation) => runSigningStep({\n        plan: input.plan,\n        failureStage,\n        stageId: input.stage.stageId,\n        artifactId: artifact.id,\n        usage: artifact.usage,\n        operation,\n    });\n    const contribution = step('validator-encode', () => encodePlannedValidatorContribution({\n        artifact,\n        stage: input.stage,\n        results: input.results,\n    }));\n    const accountSignature = artifact.accountEnvelope.kind === 'none'\n        ? contribution\n        : step('account-envelope', () => context.accountAdapter.encodeSignatureEnvelope({\n            account: context.account,\n            envelope: artifact.accountEnvelope,\n            validatorContribution: contribution,\n            purpose: 'erc1271',\n        }));\n    const erc6492 = artifact.erc6492;\n    if (erc6492.kind === 'none') {\n        return { [artifact.id]: accountSignature };\n    }\n    const deployed = input.stage.facts.find((fact) => fact.kind === 'account-deployed');\n    return {\n        [artifact.id]: deployed?.kind === 'account-deployed' && deployed.deployed\n            ? accountSignature\n            : step('protocol-operation', () => wrapErc6492Signature({\n                factory: erc6492.factory,\n                factoryData: erc6492.factoryData,\n                signature: accountSignature,\n            })),\n    };\n}\n","export function getAppFeeBalances(client) {\n    return client.getAppFeeBalances();\n}\n","import { formatCaip2, isEvmCaip2, toEvmChainReference, } from '../../chains/caip2.js';\nexport async function getPortfolio(input) {\n    // The catalog's `testnet` flag is authoritative even for chains newer than\n    // the SDK's viem version, while the portfolio endpoint accepts only EIP-155.\n    const catalog = await input.client.getChainCatalog();\n    const chainIds = catalog\n        .getSupportedChainIds()\n        .filter((chainId) => catalog.isTestnet(chainId) === input.onTestnets &&\n        isEvmCaip2(formatCaip2(chainId)));\n    const accountChainId = chainIds[0];\n    if (accountChainId === undefined) {\n        throw new Error('No EVM chain is available for portfolio account resolution');\n    }\n    const runtime = await input.account.forChain(toEvmChainReference(accountChainId));\n    return input.client.getPortfolio({\n        account: runtime.identity.address,\n        chainIds,\n    });\n}\n","import { toSession } from '../../modules/validators/smart-sessions/resolve.js';\nexport async function createSession(input) {\n    const catalog = await input.orchestrator.getChainCatalog();\n    const wrappedNativeToken = catalog.getWrappedNativeToken(input.definition.chain.id)?.address;\n    // Fail fast: without the wrapped-native address we can't add the native-wrap\n    // `deposit()` permission, and a silently under-scoped session would\n    // sign/enable fine but break native-wrap intents later.\n    if (!wrappedNativeToken) {\n        throw new Error(`createSession: the orchestrator's /chains has no wrapped-native token for chain ${input.definition.chain.id}. The chain must be supported and advertise its wrappedNativeToken.`);\n    }\n    return toSession(input.definition, {\n        wrappedNativeToken,\n        environment: input.environment,\n    });\n}\n","import { attachAccount, composeSdk } from './accounts.js';\nimport { toOrchestratorSplitRequest, toPublicSplitResult, toPublicTransactionStatus, } from './project-mappers.js';\n/**\n * Stateful entry point that holds shared configuration (auth, provider,\n * bundler, paymaster) and creates accounts from it, delegating all work to the\n * SDK-core composition.\n */\nclass RhinestoneSDK {\n    #sdk;\n    // Retained shared-config slots. The composition owns the resolved values;\n    // these mirror the published field surface and let the instance answer\n    // config questions without re-reaching into the composition internals.\n    authProvider;\n    endpointUrl;\n    provider;\n    bundler;\n    paymaster;\n    useDevContracts;\n    headers;\n    hyperliquid;\n    /**\n     * Create a Rhinestone SDK instance.\n     * @param options Shared configuration applied to every account created by this instance\n     */\n    constructor(options) {\n        const input = options;\n        this.provider = input.provider;\n        this.bundler = input.bundler;\n        this.paymaster = input.paymaster;\n        this.endpointUrl = input.endpointUrl;\n        this.useDevContracts = input.useDevContracts;\n        this.headers = input.headers;\n        this.hyperliquid = input.hyperliquid;\n        this.#sdk = composeSdk(input);\n        this.authProvider = this.#sdk.snapshot.authProvider;\n    }\n    /**\n     * Create an account using this instance's shared configuration.\n     * @param config Per-account configuration (owners, account type, modules, sessions)\n     * @returns The account instance\n     * @example\n     * ```ts\n     * import { RhinestoneSDK } from '@rhinestone/sdk'\n     * import { privateKeyToAccount } from 'viem/accounts'\n     *\n     * const owner = privateKeyToAccount('0x...')\n     *\n     * const sdk = new RhinestoneSDK({\n     *   auth: { mode: 'apiKey', apiKey: process.env.RHINESTONE_API_KEY! },\n     * })\n     *\n     * const account = await sdk.createAccount({\n     *   evm: { owners: { type: 'ecdsa', accounts: [owner] } },\n     * })\n     * ```\n     */\n    async createAccount(config) {\n        return attachAccount(this.#sdk, config);\n    }\n    /**\n     * Get the current status of a submitted intent.\n     * @param intentId The intent ID returned when the transaction was submitted\n     * @param options Pass `{ full: true }` to also get the recorded `details`\n     * block. Polling stays lean without it.\n     * @returns The intent status\n     */\n    getIntentStatus(intentId, options) {\n        return this.#sdk.composition.project\n            .getIntentStatus(intentId, options)\n            .then(toPublicTransactionStatus);\n    }\n    /**\n     * Split a transaction into multiple intents across chains.\n     * @param input The intents to split\n     * @returns The split-intents result\n     */\n    splitIntents(input) {\n        return this.#sdk.composition.project\n            .splitIntents(toOrchestratorSplitRequest(input))\n            .then(toPublicSplitResult);\n    }\n    /**\n     * Get the integrator's accrued app-fee balance, as USD totals.\n     *\n     * App fees are earned by the integrator identified by this instance's API key\n     * (project-scoped, not tied to any account) and valued in USD at the moment\n     * each fee is collected, so the balance is not affected by later price\n     * movements of the collected tokens.\n     * @returns The withdrawable and pending app-fee balances in USD\n     */\n    getAppFeeBalances() {\n        return this.#sdk.composition.project.getAppFeeBalances();\n    }\n    /**\n     * Create a smart session, resolving the chain's wrapped-native token from the\n     * orchestrator's chain catalog (`GET /chains`) so native-token wrapping is\n     * permitted automatically. Project-scoped — needs the API key but no account.\n     * For a fully offline build, use the standalone `toSession` and pass\n     * `wrappedNativeToken` yourself.\n     * @param definition The session definition\n     * @returns The resolved session\n     */\n    createSession(definition) {\n        return this.#sdk.composition.project.createSession(definition);\n    }\n}\nexport { RhinestoneSDK };\n","import { materializeRpcReader } from '../clients/rpc/compatibility.js';\nimport { getSessionDetails as buildSessionDetails, SESSION_LOCK_TAG, } from '../modules/validators/smart-sessions/authorization.js';\nimport { toCrossChainPermissionInput } from '../modules/validators/smart-sessions/cross-chain-permits.js';\nimport { getPermissionId, getSessionData, } from '../modules/validators/smart-sessions/digest.js';\nimport { SMART_SESSION_EMISSARY_ADDRESS, SMART_SESSION_EMISSARY_ADDRESS_DEV, } from '../modules/validators/smart-sessions/module.js';\nimport { ARG_POLICY_ADDRESS, INTENT_EXECUTION_POLICY_ADDRESS, SPENDING_LIMITS_POLICY_ADDRESS, SUDO_POLICY_ADDRESS, TIME_FRAME_POLICY_ADDRESS, UNIVERSAL_ACTION_POLICY_ADDRESS, USAGE_LIMIT_POLICY_ADDRESS, VALUE_LIMIT_POLICY_ADDRESS, } from '../modules/validators/smart-sessions/policies/addresses.js';\nimport { toSession as resolveSession, SMART_SESSIONS_FALLBACK_TARGET_FLAG, SMART_SESSIONS_FALLBACK_TARGET_SELECTOR_FLAG, } from '../modules/validators/smart-sessions/resolve.js';\nimport { readSessionEnabled, readSessionNonce, } from '../modules/validators/smart-sessions/state.js';\nimport { FYND_CHAIN_IDS, fynd, } from '../modules/validators/smart-sessions/swap/fynd.js';\nimport { rhinestoneSwap } from '../modules/validators/smart-sessions/swap/rhinestone.js';\nimport { resolveZeroExSettler, ZEROX_CHAIN_IDS, zeroEx, } from '../modules/validators/smart-sessions/swap/zero-ex.js';\nfunction environment(useDevContracts) {\n    return useDevContracts === true ? 'development' : 'production';\n}\nfunction toSession(definition, options = {}) {\n    return resolveSession(definition, {\n        environment: environment(options.useDevContracts),\n    });\n}\nasync function getSessionDetails(account, sessions, provider, useDevContracts) {\n    const runtimeEnvironment = environment(useDevContracts);\n    return buildSessionDetails({\n        account,\n        sessions: sessions,\n        environment: runtimeEnvironment,\n        readNonce: async (session) => {\n            const reader = materializeRpcReader({ chain: session.chain, provider });\n            return readSessionNonce({\n                rpc: reader.rpc,\n                chain: reader.chain,\n                account,\n                lockTag: SESSION_LOCK_TAG,\n                environment: runtimeEnvironment,\n            });\n        },\n    });\n}\nasync function isSessionEnabled(account, provider, session, useDevContracts) {\n    const reader = materializeRpcReader({ chain: session.chain, provider });\n    return readSessionEnabled({\n        rpc: reader.rpc,\n        chain: reader.chain,\n        account,\n        session: session,\n        environment: environment(useDevContracts),\n    });\n}\nexport { ARG_POLICY_ADDRESS, FYND_CHAIN_IDS, fynd, getPermissionId, getSessionData, getSessionDetails, INTENT_EXECUTION_POLICY_ADDRESS, isSessionEnabled, resolveZeroExSettler, rhinestoneSwap, SMART_SESSION_EMISSARY_ADDRESS, SMART_SESSION_EMISSARY_ADDRESS_DEV, SMART_SESSIONS_FALLBACK_TARGET_FLAG, SMART_SESSIONS_FALLBACK_TARGET_SELECTOR_FLAG, SPENDING_LIMITS_POLICY_ADDRESS, SUDO_POLICY_ADDRESS, TIME_FRAME_POLICY_ADDRESS, toCrossChainPermissionInput, toSession, UNIVERSAL_ACTION_POLICY_ADDRESS, USAGE_LIMIT_POLICY_ADDRESS, VALUE_LIMIT_POLICY_ADDRESS, \n// Venue-scoped swap sessions (RHI-6286)\nZEROX_CHAIN_IDS, zeroEx, };\n"],"mappings":";;;;;;;;;;;;;;;;;;AA2CA,IAAM,uBAAuB;AAE7B,IAAM,kCACJ;AAgCF,SAAS,2BACP,aACA,UACA,MACe;AACf,MAAI,OAAO,WAAW,YAAa,QAAO;AAC1C,QAAM,SAAS,OAAO,UAAU;AAChC,MAAI,CAAC,OAAQ,QAAO;AACpB,QAAM,YAAY,OAAO,GAAG,IAAI,MAAM;AACtC,SAAO,oBAAoB,IAAI,IAAI,WAAW,EAAE,MAAM,IAAI,YAAY,WAAW,IAAI,SAAS,GAAG,MAAM;AACzG;AAEO,IAAM,uBAAN,MAA2B;AAAA,EAQhC,YAAY,QAA4B;AACtC,yBAAqB,MAAM;AAC3B,SAAK,cAAc,OAAO,eAAe;AACzC,SAAK,WA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B;AAAA,YAC5B,YAAY,KAAK;AAAA,YACjB,QAAQ,KAAK;AAAA,YACb,OAAAA;AAAA,UACF,CAAC;AAAA,QACH;AAAA,MACF,CAAC;AAAA,IACH;AAAA,EACF;AACF;AAoBA,eAAsB,oCACpBC,UACA;AACA,QAAM,sBAAsB,yBAAyBA,SAAQ,SAAS,QAAQ;AAC9E,QAAM,WAAW,oBAAoB,QAAQ,MAAM;AACnD,MAAI,CAAC,UAAU,QAAQ;AACrB,UAAM,IAAI,MAAM,iEAAiE;AAAA,EACnF;AAEA,aAAW,WAAW,UAAU;AAC9B,mBAAe,OAAO;AACtB,QAAI,QAAQ,YAAY,2BAA2B;AACjD,YAAM,IAAI,MAAM,+DAA+D;AAAA,IACjF;AAAA,EACF;AAIA,QAAMC,WAAU,MAAM,IAAI,cAAc,EAAE,QAAQ,qBAAqB,CAAC,EAAE,cAAc;AAAA,IACtF,KAAK;AAAA,MACH,UAAU,EAAE,SAASD,SAAQ,eAAe;AAAA,MAC5C,QAAQ;AAAA,QACN,MAAM;AAAA,QACN,UAAU,CAAC,oBAAoBA,SAAQ,UAAU,CAAC;AAAA,MACpD;AAAA,MACA,UAAU,EAAE,SAAS,KAAK;AAAA,IAC5B;AAAA,EACF,CAAC;AAED,QAAM,UAAU,MAAM,oBAAoB;AAAA,IACxC,YAAYA,SAAQ;AAAA,IACpB,QAAQA,SAAQ;AAAA,IAChB,UAAUA,SAAQ;AAAA,IAClB;AAAA,EACF,CAAC;AAMD,QAAM,SAAS,MAAMC,SAAQ,gBAAgB;AAAA,IAC3C,GAAG;AAAA,IACH,aAAa;AAAA,MACX,GAAG,oBAAoB;AAAA,MACvB;AAAA,IACF;AAAA,EACF,CAAC;AACD,SAAO,mBAAmB,UAAU,OAAO,MAAM;AACnD;","names":["options","isAddress","crypto","array","pad","crypto","_32n","object","_0n","_1n","_0n","_1n","gcd","Fp","Fp","_1n","_0n","_1n","_0n","_1n","window","wbits","_0n","Fp","Fn","_0n","_1n","_2n","_8n","Fp","Fn","uvRatio","p","randomBytes","adjustScalarBytes","options","size","eddsa","_0n","_1n","_2n","_3n","_5n","_8n","_1n","mod","_0n","isBytes","abytes","anumber","anumber","padding","isBytes","alphabet","abytes","bytesToHex","concatBytes","evmAccount","account","account","hexToBytes","account","environment","account","account","account","bytesToHex","hexToBytes","isAddress","chain","chainId","id","concat","hexToBytes","toHex","chain","account","chain","hexToBytes","concat","toHex","account","setupOps","delegations","destination","serializeBigInts","record","chainId","types","array","isAddress","chainId","executions","chainId","source","add","executions","chainId","options","source","base58","padding","account","chain","toSponsorship","chainId","options","account","source","isAddress","executions","recipient","refuse","hexToBytes","bytesToHex","bytesToHex","hexToBytes","isAddress","isAddressEqual","chain","getChainById","chainId","keccak256","encodeAbiParameters","environment","environment","custom","encodeAbiParameters","encodeAbiParameters","encodeAbiParameters","concat","encodeAbiParameters","toHex","toHex","concat","encodeAbiParameters","concat","encodeAbiParameters","toHex","toHex","encodeAbiParameters","account","concat","concat","toHex","bytesToHex","encodeAbiParameters","hexToBytes","keccak256","hexToBytes","bytesToHex","account","keccak256","encodeAbiParameters","encodeAbiParameters","keccak256","keccak256","chain","account","keccak256","encodeAbiParameters","concat","decodeAbiParameters","encodeFunctionData","encodePacked","keccak256","pad","encodeAbiParameters","encodePacked","toBytes","toHex","encodeFunctionData","encodePacked","encodeFunctionData","encodePacked","decodeAbiParameters","pad","keccak256","encodePacked","concat","encodeFunctionData","concat","decodeAbiParameters","decodeFunctionData","encodeAbiParameters","encodeFunctionData","keccak256","parseAbi","toHex","zeroAddress","encodeFunctionData","parseAbi","encodeAbiParameters","concat","zeroAddress","decodeAbiParameters","decodeFunctionData","keccak256","toHex","concat","decodeFunctionData","encodeAbiParameters","encodeFunctionData","encodePacked","getContractAddress","parseAbi","size","zeroAddress","decodeFunctionData","parseAbi","encodeFunctionData","size","zeroAddress","encodeAbiParameters","accountInitData","getContractAddress","concat","encodePacked","concat","decodeFunctionData","encodeAbiParameters","encodeFunctionData","encodePacked","getContractAddress","keccak256","parseAbi","zeroAddress","encodeAbiParameters","decodeFunctionData","parseAbi","keccak256","encodePacked","encodeFunctionData","zeroAddress","encodeAbiParameters","getContractAddress","concat","zeroAddress","concat","decodeFunctionData","encodeAbiParameters","encodeFunctionData","encodePacked","keccak256","parseAbi","slice","zeroAddress","zeroHash","account","chainId","zeroHash","encodeFunctionData","parseAbi","zeroAddress","encodeAbiParameters","decodeFunctionData","accountInitData","keccak256","encodePacked","concat","slice","keccak256","account","chain","size","account","options","account","size","options","market","hashTypedData","keccak256","stringToHex","options","fail","chain","chainId","concat","zeroHash","encodeAbiParameters","encodePacked","maxUint256","size","zeroAddress","zeroHash","encodeAbiParameters","keccak256","concat","encodeAbiParameters","encodePacked","keccak256","toHex","keccak256","concat","encodeAbiParameters","encodePacked","toHex","chainId","isAddressEqual","isAddress","isHex","size","array","environment","chain","isAddressEqual","keccak256","encodeAbiParameters","bytesToHex","hexToBytes","encodePacked","size","encodeAbiParameters","zeroHash","maxUint256","zeroAddress","zeroHash","concat","encodeAbiParameters","keccak256","toFunctionSelector","zeroHash","chain","encodeAbiParameters","encodePacked","isHex","padHex","toHex","zeroHash","isHex","padHex","toHex","nodeIndex","environment","zeroHash","encodeAbiParameters","encodePacked","zeroHash","types","zeroHash","types","seconds","toFunctionSelector","toFunctionSelector","toFunctionSelector","toFunctionSelector","toFunctionSelector","toFunctionSelector","environment","options","chainId","environment","token","options","environment","toFunctionSelector","zeroHash","keccak256","encodeAbiParameters","chain","chainId","source","chain","chainId","hashTypedData","refuse","account","keccak256","stringToHex","account","chainId","account","chain","solana","ctx","chainId","options","internal","environment","source","swigId","refuse","hexToBytes","bytesToHex","isAddressEqual","unsupported","isAddress","destination","adaptSessionSelection","getChainById","isAddressEqual","chainId","chainId","chainId","chainId","chain","getChainById","headers","chainId","body","chain","account","isObject","options","account","evmExecution","source","chain","options","chainId","fetch","custom","entryPoint07Address","chainId","chainId","custom","chain","entryPoint07Address","createPublicClient","chain","createPublicClient","getChainById","encodeAbiParameters","hashStruct","maxUint256","account","environment","maxUint256","hashStruct","isAddressEqual","zeroAddress","isAddressEqual","account","encodeAbiParameters","hashTypedData","keccak256","hashTypedData","keccak256","encodeAbiParameters","chain","chainId","hashTypedData","isAddressEqual","hashTypedData","concatHex","domainSeparator","encodeAbiParameters","keccak256","stringToHex","account","concat","decodeAbiParameters","encodeAbiParameters","size","slice","concat","encodeAbiParameters","concat","encodeAbiParameters","hashStruct","keccak256","toHex","types","keccak256","toHex","hashStruct","encodeAbiParameters","concat","hashTypedData","hashTypedData","isAddressEqual","chainId","keccak256","stringToHex","canonical","keccak256","stringToHex","source","encodePacked","pad","chain","getChainById","requireSession","account","validatorOwners","encodePacked","pad","chainId","signerInvoker","options","source","owner","sameValidatorId","hexToBytes","isHex","chainId","isHex","hexToBytes","account","seconds","slowDelayMs","options","entryPoint07Address","chain","concat","toHex","zeroAddress","entryPoint07Address","chain","getChainById","encodePacked","hashMessage","hashTypedData","pad","zeroHash","hashMessage","hashMessage","hashMessage","hashTypedData","encodePacked","pad","zeroHash","environment","chainId","options","destination","chainId","chain","account","signRequestedDelegations","referenceChain","zeroAddress","isAddressEqual","environment","delegations","getChainById","validatorOwners","isAddress","account","swigAccount","captured","options","toSession","options","chainId","domainChainId","toSession","chain","options","account"]}