{"version":3,"sources":["../src/smart-session-signatures.ts","../../auth-protocol/src/account-verification-wire.ts","../../auth-protocol/src/smart-session.ts","../../auth-protocol/src/index.ts","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/api/accounts.js","../../../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/src/crypto.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@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/accounts/solana/address.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/chains/non-evm.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/errors/execution.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/accounts/solana/keys.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/accounts/solana/passkey.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/config/removed-inputs.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/config/legacy.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/modules/validators/signer-id.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/modules/validators/definition.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/modules/validators/ownable.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/modules/validators/social-recovery.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/config/defaults.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/config/resolve.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/accounts/error.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/config/validate.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/errors/capability.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/api/account.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/chains/caip2.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/chains/catalog.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/chains/tokens.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/clients/orchestrator/errors.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/accounts/construction.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/modules/plan.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/modules/intent-executor.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/modules/normalize.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/modules/validators/smart-sessions/module.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/modules/validators/ens.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/modules/validators/ordering.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/modules/validators/multi-factor.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/modules/validators/quorum.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/modules/validators/webauthn.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/modules/validators/resolve.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/accounts/passkey-install.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/accounts/deployment.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/accounts/adapters/eoa.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/accounts/adapters/hca.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/accounts/erc7579-calls.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/accounts/adapters/shared.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/modules/erc7579-abi.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/accounts/adapters/kernel.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/accounts/adapters/nexus.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/accounts/adapters/safe.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/modules/legacy-core.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/accounts/adapters/startale.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/modules/validators/k1.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/accounts/registry.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/config/account-runtime.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/hypercore/errors.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/hypercore/market.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/hypercore/orders.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/hypercore/resolve.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/transactions/intents/account.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/transactions/intents/compatibility.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/transactions/intents/normalize.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/transactions/intents/prepare.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/calls/resolve.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/clients/orchestrator/serialization.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/clients/orchestrator/sponsorship-approval.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/signing/error.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/signing/plan.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/transactions/intents/origin-chain.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/transactions/intents/quotes.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/transactions/intents/request.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/transactions/intents/session-routing.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/modules/validators/smart-sessions/mock-signature.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/modules/validators/smart-sessions/signature.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/modules/validators/smart-sessions/digest.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/modules/validators/smart-sessions/fast-lz.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/modules/validators/smart-sessions/one-time-use.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/modules/validators/smart-sessions/policies/addresses.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/modules/validators/policies/claim/permit2.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/modules/validators/policies/claim/types.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/modules/validators/smart-sessions/refusals.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/modules/validators/smart-sessions/resolve.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/modules/validators/permissions.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/modules/validators/smart-sessions/policies/time-frame.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/modules/validators/smart-sessions/cross-chain-permits.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/modules/validators/smart-sessions/policies/claim.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/modules/validators/policies/claim/arbiters.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/modules/validators/smart-sessions/policies/encode.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/modules/validators/smart-sessions/policies/permit2-approval.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/modules/validators/smart-sessions/settlement/fees.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/modules/validators/smart-sessions/swap/rules.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/modules/validators/smart-sessions/swap/stable-floor.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/modules/validators/smart-sessions/settlement/same-chain.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/modules/validators/smart-sessions/swap/rhinestone.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/modules/validators/smart-sessions/swap/fynd.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/modules/validators/smart-sessions/swap/zero-ex.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/modules/validators/smart-sessions/swap/scope.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/modules/validators/smart-sessions/settlement/scope.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/modules/validators/smart-sessions/settlement/cctp.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/modules/validators/smart-sessions/settlement/served.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/modules/validators/smart-sessions/settlement/eco.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/modules/validators/smart-sessions/settlement/floor.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/modules/validators/smart-sessions/settlement/lz.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/modules/validators/smart-sessions/settlement/oft.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/modules/validators/smart-sessions/signing.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/modules/validators/smart-sessions/erc7739.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/transactions/intents/sessions.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/transactions/intents/solana.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/signing/signers/ecdsa.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/signing/signers/wallet-chain.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/transactions/intents/solana-instructions.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/api/project-mappers.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/api/signer-selection.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/api/transaction-input.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/api/compose.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/clients/bundler/client.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/clients/json-rpc.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/clients/rpc/transport.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/clients/rpc/providers.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/clients/bundler/endpoints.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/clients/orchestrator/auth.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/clients/orchestrator/chain-catalog.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/clients/orchestrator/fetch.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/clients/orchestrator/mappers.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/clients/orchestrator/client.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/clients/paymaster/client.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/clients/paymaster/endpoints.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/clients/rpc/client.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/modules/read-core.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/modules/validators/smart-sessions/authorization.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/modules/validators/smart-sessions/state.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/signing/context.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/modules/validators/capabilities.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/signing/eip7702.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/signing/execute.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/signing/session-enable.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/signing/typed-data.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/modules/validators/contribution.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/signing/contribution.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/accounts/kernel-signing.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/signing/hash.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/signing/protocols/erc6492.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/signing/protocols/erc7739.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/signing/signers/webauthn.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/signing/signers/registry.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/transactions/intents/proofs.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/signing/intent-plans/assemble.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/signing/intent-plans/independent.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/signing/intent-plans/types.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/signing/intent-plans/plan.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/transactions/intents/session-signing.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/transactions/intents/sign-transaction.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/transactions/intents/submit.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/transactions/intents/send.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/transactions/intents/solana-deployment.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/transactions/intents/split.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/transactions/intents/status-policy.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/transactions/intents/status.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/transactions/user-operations/hash.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/transactions/user-operations/nonce.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/transactions/user-operations/validator-account.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/transactions/user-operations/prepare.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/transactions/user-operations/reconstruct.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/signing/user-operation.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/transactions/user-operations/sign.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/transactions/user-operations/submit.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/transactions/user-operations/send.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/transactions/user-operations/status.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/api/direct-signing.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/signing/message.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/api/queries/app-fees.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/api/queries/portfolio.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/api/queries/session.js","../../../node_modules/.pnpm/@rhinestone+sdk@3.0.0_jose@6.2.2_viem@2.55.8_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.6.6_/node_modules/@rhinestone/sdk/dist/src/api/sdk.js"],"sourcesContent":["import { encodeAbiParameters, keccak256, type Address, type Chain, type Hex, type LocalAccount } from \"viem\";\nimport { restoreSmartSession, smartSessionChainIds, type SerializedSmartSessions } from \"@1auth/auth-protocol\";\nimport { RhinestoneSDK, type PreparedTransactionData, type Session, type SigningRequest, type SigningProof, type SignerSet } from \"@rhinestone/sdk\";\nimport type { SessionKeyHandle } from \"./types\";\n\ntype PreparedSessionIntent = { intentOp: string; targetChain: number };\n\nfunction parsePreparedTransaction(value: string): PreparedTransactionData {\n  const envelope: unknown = JSON.parse(value, (_key, nested) =>\n    typeof nested === \"string\" && nested.startsWith(\"__bigint:\") ? BigInt(nested.slice(9)) : 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 value = request.payload.typedData.domain?.chainId;\n  const chainId = typeof value === \"number\" || typeof value === \"bigint\" || typeof value === \"string\" && /^\\d+$/.test(value) ? Number(value) : NaN;\n  if (!Number.isSafeInteger(chainId) || chainId <= 0) throw new Error(\"Headless signing request is missing an EVM typed-data chain id\");\n  return chainId;\n}\n\nfunction toLegacySignatures(requests: SigningRequest[], proofs: SigningProof[]) {\n  if (proofs.length !== requests.length) throw new Error(`Expected ${requests.length} headless proofs, received ${proofs.length}`);\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    const proof = proofs[index];\n    if (!proof || proof.kind !== \"eip712\") throw new Error(`Missing EIP-712 proof for ${request.purpose}`);\n    const signature = proof.signature;\n    if (request.purpose === \"originAuthorization\") {\n      originSignatures.push(typeof signature === \"string\" ? signature : { preClaimSig: signature.preClaim, notarizedClaimSig: signature.notarizedClaim });\n    } else if (request.purpose === \"destinationAuthorization\") {\n      if (destinationSignature || typeof signature !== \"string\") throw new Error(\"Invalid destination headless proof\");\n      destinationSignature = signature;\n    } else if (request.purpose === \"targetExecutionAuthorization\") {\n      if (targetExecutionSignature || typeof signature !== \"string\") throw new Error(\"Invalid target execution headless proof\");\n      targetExecutionSignature = signature;\n    } else throw new Error(`Unsupported headless signing purpose: ${request.purpose}`);\n  });\n  if (!destinationSignature) throw new Error(\"Missing destination headless proof\");\n  return { originSignatures, destinationSignature, targetExecutionSignature };\n}\n\nexport interface BuildSmartSessionHeadlessSignaturesOptions {\n  signer: LocalAccount;\n  accountAddress: Address;\n  sessionKeyHandle: SessionKeyHandle;\n  prepared: PreparedSessionIntent;\n  /** Exact compiled sessions returned by headless batch-prepare. */\n  sessions: SerializedSmartSessions;\n  /** Inject core's registry to avoid forking its cache in this lazy chunk. */\n  getChain: (chainId: number) => Promise<Chain>;\n}\n\nasync function buildSessionSigners(options: BuildSmartSessionHeadlessSignaturesOptions, requests: SigningRequest[]): Promise<SignerSet> {\n  const handle = options.sessionKeyHandle;\n  if (handle.sessionKeyAddress.toLowerCase() !== options.signer.address.toLowerCase()) throw new Error(\"Session key does not match the granted owner\");\n  const required = new Set([options.prepared.targetChain, ...requests.map(requestChainId)]);\n  const serialized = [...required].map((chainId) => {\n    const session = options.sessions?.[chainId];\n    if (!session) throw new Error(`Prepared session for chain ${chainId} is missing`);\n    if (session.chainId !== chainId) throw new Error(`Prepared session chain ${session.chainId} does not match chain ${chainId}`);\n    if (session.owners.type !== \"ecdsa\" || session.owners.accounts.length !== 1 || session.owners.accounts[0]?.toLowerCase() !== handle.sessionKeyAddress.toLowerCase()) throw new Error(`Prepared session owner for chain ${chainId} does not match the grant`);\n    // The SDK's getPermissionId only reads the field; derive it independently.\n    const derived = keccak256(encodeAbiParameters(\n      [{ type: \"address\" }, { type: \"bytes\" }, { type: \"bytes32\" }],\n      [session.sessionValidator, session.sessionValidatorInitData, session.salt],\n    ));\n    const expected = handle.permissionIdsByChain?.[chainId] ?? handle.permissionId;\n    if (derived.toLowerCase() !== expected.toLowerCase() || session.permissionId.toLowerCase() !== derived.toLowerCase()) throw new Error(`Prepared session permission ID for chain ${chainId} does not match the grant`);\n    return session;\n  });\n  // Claim metadata may refer to chains without signing requests of their own.\n  const ids = new Set(serialized.flatMap(smartSessionChainIds));\n  const chains = new Map(await Promise.all([...ids].map(async (id) => [id, await options.getChain(id)] as const)));\n  return {\n    type: \"session\",\n    sessions: Object.fromEntries(serialized.map((session) => [session.chainId, {\n      session: restoreSmartSession(session, {\n        owner: options.signer,\n        getChain: (id) => {\n          const chain = chains.get(id);\n          if (!chain) throw new Error(`Prepared session chain ${id} is missing`);\n          return chain;\n        },\n      }) as Session,\n    }])),\n  };\n}\n\n/** Signs the server's compiled authorization without recompiling the grant. */\nexport async function buildSmartSessionHeadlessSignatures(options: BuildSmartSessionHeadlessSignaturesOptions) {\n  const preparedTransaction = parsePreparedTransaction(options.prepared.intentOp);\n  const requests = preparedTransaction.quotes?.best?.signingRequests;\n  if (!requests?.length) throw new Error(\"Prepared headless intent is missing quotes.best.signingRequests\");\n  for (const request of requests) {\n    requestChainId(request);\n    if (request.purpose === \"delegationAuthorization\") throw new Error(\"Unsupported headless signing purpose: delegationAuthorization\");\n  }\n  const signers = await buildSessionSigners(options, requests);\n  // Local signing uses RPC state reads only; this placeholder never goes to the orchestrator.\n  const account = await new RhinestoneSDK({ auth: { mode: \"apiKey\", apiKey: \"local-signing-only\" } }).createAccount({\n    evm: { initData: { address: options.accountAddress }, owners: { type: \"ecdsa\", accounts: [options.signer] }, sessions: { enabled: true } },\n  });\n  // Signing the full artifact preserves origin sessions on cross-chain routes.\n  const signed = await account.signTransaction({\n    ...preparedTransaction,\n    transaction: { ...preparedTransaction.transaction, signers } as PreparedTransactionData[\"transaction\"],\n  });\n  return toLegacySignatures(requests, signed.proofs);\n}\n","import type { AccountVerificationData } from \"./index\";\n\n// Wire format only: no account recipe or ownership assertion is persisted here.\nexport const ACCOUNT_VERIFICATION_TRANSPORT_VERSION = 1;\nexport const MAX_ACCOUNT_FACTORY_DATA_BYTES = 65_536;\nexport const MAX_ACCOUNT_VERIFICATION_RESPONSE_BYTES =\n  MAX_ACCOUNT_FACTORY_DATA_BYTES * 2 + 1024;\n\nexport function isVerificationAddress(value: unknown): value is `0x${string}` {\n  return typeof value === \"string\" && /^0x[0-9a-fA-F]{40}$/.test(value);\n}\n\nexport function isVerificationFactoryData(\n  value: unknown\n): value is `0x${string}` {\n  return (\n    typeof value === \"string\" &&\n    value.length >= 10 &&\n    value.length <= MAX_ACCOUNT_FACTORY_DATA_BYTES * 2 + 2 &&\n    /^0x(?:[0-9a-fA-F]{2})+$/.test(value)\n  );\n}\n\n/** Strict canonical wire decoder. Data remains untrusted after decoding. */\nexport function parseAccountVerificationData(\n  value: unknown\n): AccountVerificationData | null {\n  if (!value || typeof value !== \"object\" || Array.isArray(value)) return null;\n  const row = value as Record<string, unknown>;\n  const keys = [\n    \"transportVersion\",\n    \"address\",\n    \"chainId\",\n    \"factoryAddress\",\n    \"factoryData\",\n  ];\n  if (\n    Object.keys(row).length !== keys.length ||\n    !keys.every((key) => Object.prototype.hasOwnProperty.call(row, key))\n  )\n    return null;\n  if (\n    row.transportVersion !== ACCOUNT_VERIFICATION_TRANSPORT_VERSION ||\n    !isVerificationAddress(row.address) ||\n    row.address !== row.address.toLowerCase() ||\n    !isVerificationAddress(row.factoryAddress) ||\n    row.factoryAddress !== row.factoryAddress.toLowerCase() ||\n    /^0x0{40}$/.test(row.factoryAddress) ||\n    !Number.isSafeInteger(row.chainId) ||\n    (row.chainId as number) <= 0 ||\n    !isVerificationFactoryData(row.factoryData) ||\n    row.factoryData !== row.factoryData.toLowerCase()\n  )\n    return null;\n  return {\n    transportVersion: 1,\n    address: row.address,\n    chainId: row.chainId as number,\n    factoryAddress: row.factoryAddress,\n    factoryData: row.factoryData,\n  };\n}\n","/**\n * Wire form of a compiled SmartSession (`Session` from `@rhinestone/sdk`).\n *\n * An installed grant's authority is the compiled session, not the definition\n * it was built from: catalog and SDK changes would compile a definition to a\n * different session. The passkey service persists this form at install and\n * hands it to the wallet's session-key signer, which restores and signs with\n * it without compiling anything.\n *\n * Bigints are decimal strings and every chain is `{ id }`. The codec carries no\n * SDK or viem import, so consumers inject `getChain` and the owner account.\n */\n\ntype Hex = `0x${string}`;\n\n/** Compiled session generation persisted with a grant; `null` means a grant installed before it was recorded. */\nexport const SESSION_COMPILERS = {\n  legacy: \"legacy-2026-09\",\n  scoped: \"scoped-2026-10\",\n} as const;\n\nexport type SessionCompiler = (typeof SESSION_COMPILERS)[keyof typeof SESSION_COMPILERS];\n\nexport interface SerializedResolvedPolicy {\n  policy: Hex;\n  initData: Hex;\n}\n\nexport interface SerializedResolvedAction {\n  actionTargetSelector: Hex;\n  actionTarget: Hex;\n  actionPolicies: SerializedResolvedPolicy[];\n}\n\ninterface SerializedChainToken {\n  chainId: number;\n  address: Hex;\n}\n\nexport interface SerializedPermit2ClaimPolicy {\n  type: \"permit2\";\n  spenders?: Hex[];\n  sourceTokens?: SerializedChainToken[];\n  destinationTokens?: SerializedChainToken[];\n  recipients?: Array<{ chainId: number; address: Hex | \"any\" }>;\n  recipientIsAccount?: boolean;\n  permitDeadline?: { min?: string; max?: string };\n  fillDeadline?: Array<{ chainId: number; min?: string; max?: string }>;\n  originOps?: Array<{ chainId: number; required: boolean }>;\n}\n\nexport interface SerializedSmartSession {\n  chainId: number;\n  permissionId: Hex;\n  owners: { type: \"ecdsa\"; accounts: Hex[]; threshold?: number };\n  sessionValidator: Hex;\n  sessionValidatorInitData: Hex;\n  salt: Hex;\n  hasExplicitPermissions: boolean;\n  erc7739Policies: {\n    allowedERC7739Content: Array<{ appDomainSeparator: Hex; contentNames: string[] }>;\n    erc1271Policies: SerializedResolvedPolicy[];\n  };\n  actions: SerializedResolvedAction[];\n  claimPolicies: SerializedPermit2ClaimPolicy[];\n  settlementLayers?: string[];\n  settlementCoverage?: { dropped: Array<{ layer: string; reason: string }> };\n  permit2Sources?: Array<{ chainId: number; token: Hex; maxAmount?: string }>;\n  access?: { kind: \"scoped\" | \"open\"; reason: string };\n  lifetimeBudget?: true;\n}\n\n/** Compiled sessions of one grant, keyed by decimal chain id. */\nexport type SerializedSmartSessions = Record<string, SerializedSmartSession>;\n\ninterface ChainRef {\n  id: number;\n}\n\ninterface AccountRef {\n  address: string;\n}\n\n/** The structural `Session` both pinned SDK generations compile. */\nexport interface CompiledSmartSession<TChain extends ChainRef = ChainRef, TAccount extends AccountRef = AccountRef> {\n  chain: TChain;\n  owners: { type: string; accounts: readonly TAccount[]; threshold?: number };\n  hasExplicitPermissions: boolean;\n  permissionId: Hex;\n  sessionValidator: Hex;\n  sessionValidatorInitData: Hex;\n  salt: Hex;\n  erc7739Policies: {\n    allowedERC7739Content: readonly { appDomainSeparator: Hex; contentNames: readonly string[] }[];\n    erc1271Policies: readonly SerializedResolvedPolicy[];\n  };\n  actions: readonly {\n    actionTargetSelector: Hex;\n    actionTarget: Hex;\n    actionPolicies: readonly SerializedResolvedPolicy[];\n  }[];\n  claimPolicies: readonly {\n    type: \"permit2\";\n    spenders?: readonly Hex[];\n    sourceTokens?: readonly { chain: TChain; address: Hex }[];\n    destinationTokens?: readonly { chain: TChain; address: Hex }[];\n    recipients?: readonly { chain: TChain; address: Hex | \"any\" }[];\n    recipientIsAccount?: boolean;\n    permitDeadline?: { min?: bigint; max?: bigint };\n    fillDeadline?: readonly { chain: TChain; min?: bigint; max?: bigint }[];\n    originOps?: readonly { chain: TChain; required: boolean }[];\n  }[];\n  swap?: unknown;\n  settlementLayers?: readonly string[];\n  settlementCoverage?: { dropped: readonly { layer: string; reason: string }[] };\n  permit2Sources?: readonly { chain: TChain; token: Hex; maxAmount?: bigint }[];\n  access?: { kind: \"scoped\" | \"open\"; reason: string };\n  lifetimeBudget?: true;\n  oneTimeUse?: unknown;\n}\n\nconst optional = <T, R>(value: T | undefined, map: (value: T) => R): R | undefined =>\n  value === undefined ? undefined : map(value);\n\nconst withoutUndefined = <T extends object>(value: T): T =>\n  Object.fromEntries(Object.entries(value).filter(([, entry]) => entry !== undefined)) as T;\n\nconst policies = (list: readonly SerializedResolvedPolicy[]) =>\n  list.map(({ policy, initData }) => ({ policy, initData }));\n\n/**\n * Serializes a compiled session. Refuses a `swap` scope or `oneTimeUse` id,\n * which 1auth never compiles and this form does not carry.\n */\nexport function serializeSmartSession(session: CompiledSmartSession): SerializedSmartSession {\n  if (session.swap !== undefined) throw new Error(\"A swap-scoped session cannot be serialized\");\n  if (session.oneTimeUse !== undefined) throw new Error(\"A one-time-use session cannot be serialized\");\n  if (session.owners.type !== \"ecdsa\") throw new Error(\"Only an ECDSA-owned session can be serialized\");\n  const chainToken = ({ chain, address }: { chain: ChainRef; address: Hex }) => ({ chainId: chain.id, address });\n  return withoutUndefined({\n    chainId: session.chain.id,\n    permissionId: session.permissionId,\n    owners: withoutUndefined({\n      type: \"ecdsa\" as const,\n      accounts: session.owners.accounts.map((account) => account.address as Hex),\n      threshold: session.owners.threshold,\n    }),\n    sessionValidator: session.sessionValidator,\n    sessionValidatorInitData: session.sessionValidatorInitData,\n    salt: session.salt,\n    hasExplicitPermissions: session.hasExplicitPermissions,\n    erc7739Policies: {\n      allowedERC7739Content: session.erc7739Policies.allowedERC7739Content.map((content) => ({\n        appDomainSeparator: content.appDomainSeparator,\n        contentNames: [...content.contentNames],\n      })),\n      erc1271Policies: policies(session.erc7739Policies.erc1271Policies),\n    },\n    actions: session.actions.map((action) => ({\n      actionTargetSelector: action.actionTargetSelector,\n      actionTarget: action.actionTarget,\n      actionPolicies: policies(action.actionPolicies),\n    })),\n    claimPolicies: session.claimPolicies.map((claim) => withoutUndefined({\n      type: \"permit2\" as const,\n      spenders: optional(claim.spenders, (list) => [...list]),\n      sourceTokens: optional(claim.sourceTokens, (list) => list.map(chainToken)),\n      destinationTokens: optional(claim.destinationTokens, (list) => list.map(chainToken)),\n      recipients: optional(claim.recipients, (list) => list.map(({ chain, address }) => ({ chainId: chain.id, address }))),\n      recipientIsAccount: claim.recipientIsAccount,\n      permitDeadline: optional(claim.permitDeadline, ({ min, max }) => withoutUndefined({\n        min: optional(min, String),\n        max: optional(max, String),\n      })),\n      fillDeadline: optional(claim.fillDeadline, (list) => list.map(({ chain, min, max }) => withoutUndefined({\n        chainId: chain.id,\n        min: optional(min, String),\n        max: optional(max, String),\n      }))),\n      originOps: optional(claim.originOps, (list) => list.map(({ chain, required }) => ({ chainId: chain.id, required }))),\n    })),\n    settlementLayers: optional(session.settlementLayers, (list) => [...list]),\n    settlementCoverage: optional(session.settlementCoverage, ({ dropped }) => ({\n      dropped: dropped.map(({ layer, reason }) => ({ layer, reason })),\n    })),\n    permit2Sources: optional(session.permit2Sources, (list) => list.map(({ chain, token, maxAmount }) => withoutUndefined({\n      chainId: chain.id,\n      token,\n      maxAmount: optional(maxAmount, String),\n    }))),\n    access: optional(session.access, ({ kind, reason }) => ({ kind, reason })),\n    lifetimeBudget: session.lifetimeBudget,\n  });\n}\n\n/**\n * Restores a serialized session for signing, enabling or disabling. `owner`\n * replaces the serialized owner address and must be that same address: the\n * owner is in `sessionValidatorInitData`, so a different key cannot sign.\n */\nexport function restoreSmartSession<TChain extends ChainRef, TAccount extends AccountRef>(\n  serialized: SerializedSmartSession,\n  options: { getChain: (chainId: number) => TChain; owner: TAccount },\n): CompiledSmartSession<TChain, TAccount> {\n  const [ownerAddress, ...others] = serialized.owners.accounts;\n  if (!ownerAddress || others.length > 0) throw new Error(\"A serialized session must have exactly one owner\");\n  if (ownerAddress.toLowerCase() !== options.owner.address.toLowerCase()) {\n    throw new Error(\"Serialized session owner does not match the signer\");\n  }\n  const chain = (chainId: number) => {\n    const resolved = options.getChain(chainId);\n    if (resolved.id !== chainId) throw new Error(`Chain ${chainId} resolved to chain ${resolved.id}`);\n    return resolved;\n  };\n  const chainToken = ({ chainId, address }: SerializedChainToken) => ({ chain: chain(chainId), address });\n  return withoutUndefined({\n    chain: chain(serialized.chainId),\n    owners: withoutUndefined({\n      type: \"ecdsa\" as const,\n      accounts: [options.owner],\n      threshold: serialized.owners.threshold,\n    }),\n    hasExplicitPermissions: serialized.hasExplicitPermissions,\n    permissionId: serialized.permissionId,\n    sessionValidator: serialized.sessionValidator,\n    sessionValidatorInitData: serialized.sessionValidatorInitData,\n    salt: serialized.salt,\n    erc7739Policies: {\n      allowedERC7739Content: serialized.erc7739Policies.allowedERC7739Content.map((content) => ({\n        appDomainSeparator: content.appDomainSeparator,\n        contentNames: [...content.contentNames],\n      })),\n      erc1271Policies: policies(serialized.erc7739Policies.erc1271Policies),\n    },\n    actions: serialized.actions.map((action) => ({\n      actionTargetSelector: action.actionTargetSelector,\n      actionTarget: action.actionTarget,\n      actionPolicies: policies(action.actionPolicies),\n    })),\n    claimPolicies: serialized.claimPolicies.map((claim) => withoutUndefined({\n      type: \"permit2\" as const,\n      spenders: optional(claim.spenders, (list) => [...list]),\n      sourceTokens: optional(claim.sourceTokens, (list) => list.map(chainToken)),\n      destinationTokens: optional(claim.destinationTokens, (list) => list.map(chainToken)),\n      recipients: optional(claim.recipients, (list) => list.map(({ chainId, address }) => ({ chain: chain(chainId), address }))),\n      recipientIsAccount: claim.recipientIsAccount,\n      permitDeadline: optional(claim.permitDeadline, ({ min, max }) => withoutUndefined({\n        min: optional(min, BigInt),\n        max: optional(max, BigInt),\n      })),\n      fillDeadline: optional(claim.fillDeadline, (list) => list.map(({ chainId, min, max }) => withoutUndefined({\n        chain: chain(chainId),\n        min: optional(min, BigInt),\n        max: optional(max, BigInt),\n      }))),\n      originOps: optional(claim.originOps, (list) => list.map(({ chainId, required }) => ({ chain: chain(chainId), required }))),\n    })),\n    settlementLayers: optional(serialized.settlementLayers, (list) => [...list]),\n    settlementCoverage: optional(serialized.settlementCoverage, ({ dropped }) => ({\n      dropped: dropped.map(({ layer, reason }) => ({ layer, reason })),\n    })),\n    permit2Sources: optional(serialized.permit2Sources, (list) => list.map(({ chainId, token, maxAmount }) => withoutUndefined({\n      chain: chain(chainId),\n      token,\n      maxAmount: optional(maxAmount, BigInt),\n    }))),\n    access: optional(serialized.access, ({ kind, reason }) => ({ kind, reason })),\n    lifetimeBudget: serialized.lifetimeBudget,\n  });\n}\n\n/** Every chain a serialized session references, so an async chain registry can be read before {@link restoreSmartSession}. */\nexport function smartSessionChainIds(serialized: SerializedSmartSession): number[] {\n  const ids = new Set<number>([serialized.chainId]);\n  for (const claim of serialized.claimPolicies) {\n    for (const list of [claim.sourceTokens, claim.destinationTokens, claim.recipients, claim.fillDeadline, claim.originOps]) {\n      for (const entry of list ?? []) ids.add(entry.chainId);\n    }\n  }\n  for (const source of serialized.permit2Sources ?? []) ids.add(source.chainId);\n  return [...ids];\n}\n","/**\n * Types shared by the SDK and apps/passkey, and the postMessage contracts the\n * legacy /dialog routes speak with released SDKs (0.13/0.14).\n */\n\nexport { swapQuoters, isSwapQuoterFilter, sameQuoterFilter, quoterFilterNarrows, type SwapQuoter, type SwapQuoterFilter } from \"./quoters\";\n\nexport const AUTH_CEREMONY_REUSE_MS = 4 * 60 * 1000;\n\nexport const PASSKEY_IDENTITY_RESULT = \"PASSKEY_IDENTITY_RESULT\" as const;\nexport const PASSKEY_IDENTITY_ACTION = \"PASSKEY_IDENTITY_ACTION\" as const;\nexport const PASSKEY_AUTH_FALLBACK = \"PASSKEY_AUTH_FALLBACK\" as const;\nexport const PASSKEY_AUTH_REMEMBER_USER = \"PASSKEY_AUTH_REMEMBER_USER\" as const;\nexport const PASSKEY_AUTH_COMPLETE = \"PASSKEY_AUTH_COMPLETE\" as const;\nexport const PASSKEY_AUTH_REGISTRATION_READY =\n  \"PASSKEY_AUTH_REGISTRATION_READY\" as const;\nexport const PASSKEY_AUTH_REGISTRATION_CTA =\n  \"PASSKEY_AUTH_REGISTRATION_CTA\" as const;\n// Host acknowledgement that its transparent trusted-click overlay is mounted\n// over the dialog's CTA. Until this lands the dialog's own button cannot start\n// a ceremony (an iframe click carries no host user activation), so the dialog\n// keeps it disabled rather than presenting a button that silently does nothing.\nexport const PASSKEY_AUTH_REGISTRATION_ARMED =\n  \"PASSKEY_AUTH_REGISTRATION_ARMED\" as const;\nexport const PASSKEY_AUTH_REGISTRATION_COMMITTED =\n  \"PASSKEY_AUTH_REGISTRATION_COMMITTED\" as const;\nexport const PASSKEY_RECOVERY_REGISTRATION_PREPARE =\n  \"PASSKEY_RECOVERY_REGISTRATION_PREPARE\" as const;\nexport const PASSKEY_RECOVERY_REGISTRATION_PREPARED =\n  \"PASSKEY_RECOVERY_REGISTRATION_PREPARED\" as const;\nexport const PASSKEY_RECOVERY_REGISTRATION_CTA =\n  \"PASSKEY_RECOVERY_REGISTRATION_CTA\" as const;\nexport const PASSKEY_RECOVERY_REGISTRATION_LISTENING =\n  \"PASSKEY_RECOVERY_REGISTRATION_LISTENING\" as const;\nexport const PASSKEY_RECOVERY_REGISTRATION_COMMITTED =\n  \"PASSKEY_RECOVERY_REGISTRATION_COMMITTED\" as const;\nexport const PASSKEY_RECOVERY_REGISTRATION_RESULT =\n  \"PASSKEY_RECOVERY_REGISTRATION_RESULT\" as const;\nexport const PASSKEY_RECOVERY_REGISTRATION_CANCEL =\n  \"PASSKEY_RECOVERY_REGISTRATION_CANCEL\" as const;\nexport const PASSKEY_RECOVERY_BACKUP_PREPARE =\n  \"PASSKEY_RECOVERY_BACKUP_PREPARE\" as const;\nexport const PASSKEY_RECOVERY_BACKUP_PREPARED =\n  \"PASSKEY_RECOVERY_BACKUP_PREPARED\" as const;\nexport const PASSKEY_RECOVERY_BACKUP_CTA =\n  \"PASSKEY_RECOVERY_BACKUP_CTA\" as const;\nexport const PASSKEY_RECOVERY_BACKUP_ARMED =\n  \"PASSKEY_RECOVERY_BACKUP_ARMED\" as const;\nexport const PASSKEY_RECOVERY_BACKUP_COMMITTED =\n  \"PASSKEY_RECOVERY_BACKUP_COMMITTED\" as const;\nexport const PASSKEY_RECOVERY_BACKUP_RESULT =\n  \"PASSKEY_RECOVERY_BACKUP_RESULT\" as const;\nexport const PASSKEY_RECOVERY_BACKUP_CANCEL =\n  \"PASSKEY_RECOVERY_BACKUP_CANCEL\" as const;\n\nexport const PASSKEY_INIT = \"PASSKEY_INIT\" as const;\nexport const PASSKEY_READY = \"PASSKEY_READY\" as const;\nexport const PASSKEY_RENDERED = \"PASSKEY_RENDERED\" as const;\nexport const PASSKEY_RESIZE = \"PASSKEY_RESIZE\" as const;\nexport const PASSKEY_VIEWPORT_INFO = \"PASSKEY_VIEWPORT_INFO\" as const;\nexport const PASSKEY_SYNC_THEME = \"PASSKEY_SYNC_THEME\" as const;\nexport const PASSKEY_CLOSE = \"PASSKEY_CLOSE\" as const;\nexport const PASSKEY_DISCONNECT = \"PASSKEY_DISCONNECT\" as const;\nexport const PASSKEY_REGISTER_RESULT = \"PASSKEY_REGISTER_RESULT\" as const;\nexport const PASSKEY_LOGIN_RESULT = \"PASSKEY_LOGIN_RESULT\" as const;\nexport const PASSKEY_AUTHENTICATE_RESULT =\n  \"PASSKEY_AUTHENTICATE_RESULT\" as const;\nexport const PASSKEY_SIGNING_RESULT = \"PASSKEY_SIGNING_RESULT\" as const;\nexport const PASSKEY_PRESIGNED_RESULT = \"PASSKEY_PRESIGNED_RESULT\" as const;\nexport const PASSKEY_RECOVERY_RESULT = \"PASSKEY_RECOVERY_RESULT\" as const;\nexport const PASSKEY_REFRESH_QUOTE = \"PASSKEY_REFRESH_QUOTE\" as const;\nexport const PASSKEY_REFRESH_COMPLETE = \"PASSKEY_REFRESH_COMPLETE\" as const;\nexport const PASSKEY_REFRESH_ERROR = \"PASSKEY_REFRESH_ERROR\" as const;\nexport const PASSKEY_PREPARE_ERROR = \"PASSKEY_PREPARE_ERROR\" as const;\nexport const TRANSACTION_STATUS = \"TRANSACTION_STATUS\" as const;\nexport const PASSKEY_EOA_RESULT = \"PASSKEY_EOA_RESULT\" as const;\nexport const PASSKEY_EOA_CLOSE = \"PASSKEY_EOA_CLOSE\" as const;\nexport const PASSKEY_GRANT_PERMISSION_RESULT =\n  \"PASSKEY_GRANT_PERMISSION_RESULT\" as const;\nexport const PASSKEY_GRANT_EXTENSION_TOKEN_REQUEST =\n  \"PASSKEY_GRANT_EXTENSION_TOKEN_REQUEST\" as const;\nexport const PASSKEY_GRANT_EXTENSION_TOKEN_RESPONSE =\n  \"PASSKEY_GRANT_EXTENSION_TOKEN_RESPONSE\" as const;\nexport const PASSKEY_GRANT_APP_ORIGIN_OPTIONS_REQUEST =\n  \"PASSKEY_GRANT_APP_ORIGIN_OPTIONS_REQUEST\" as const;\nexport const PASSKEY_GRANT_APP_ORIGIN_OPTIONS_RESPONSE =\n  \"PASSKEY_GRANT_APP_ORIGIN_OPTIONS_RESPONSE\" as const;\nexport const PASSKEY_GRANT_APP_ORIGIN_EXECUTION_REQUEST =\n  \"PASSKEY_GRANT_APP_ORIGIN_EXECUTION_REQUEST\" as const;\nexport const PASSKEY_GRANT_APP_ORIGIN_EXECUTION_RESPONSE =\n  \"PASSKEY_GRANT_APP_ORIGIN_EXECUTION_RESPONSE\" as const;\n\nexport type AuthWebAuthnMode = \"centralized\" | \"app-origin\";\nexport type AuthIntent = \"auto\" | \"login\" | \"create-account\";\nexport type CredentialBucket = \"none\" | \"one\" | \"many\";\n\n/** Origin-bound identity proof issued after verified email or OAuth login. */\nexport type VerifiedIdentity = {\n  kind: \"email\";\n  identityHandle: string;\n  emailToken: string;\n  email: string;\n  recoveryRequested?: boolean;\n};\n\n/** Identity outcomes emitted by the identity-only dialog. */\nexport type AuthIdentity =\n  | VerifiedIdentity\n  | { kind: \"stored-session\"; accountAddress: string };\n\nexport type AuthFlowStartRequest = {\n  identity:\n    | { kind: \"verified\"; identityHandle: string }\n    | { kind: \"discoverable\" };\n  webauthnMode: AuthWebAuthnMode;\n  intent: AuthIntent;\n  clientId?: string;\n  rpId?: string;\n};\n\nexport type PublicKeyCredentialDescriptorJSON = {\n  id: string;\n  type: \"public-key\";\n  transports?: string[];\n};\n\n/** Runtime-light registration option shape used on the 1auth JSON wire. */\nexport type RegistrationOptionsJSON = {\n  challenge: string;\n  rp: { name: string; id?: string };\n  user: { id: string; name: string; displayName: string };\n  pubKeyCredParams: Array<{ type: \"public-key\"; alg: number }>;\n  timeout?: number;\n  excludeCredentials?: PublicKeyCredentialDescriptorJSON[];\n  authenticatorSelection?: {\n    authenticatorAttachment?: \"cross-platform\" | \"platform\";\n    residentKey?: \"discouraged\" | \"preferred\" | \"required\";\n    requireResidentKey?: boolean;\n    userVerification?: \"discouraged\" | \"preferred\" | \"required\";\n  };\n  attestation?: \"direct\" | \"enterprise\" | \"indirect\" | \"none\";\n  extensions?: Record<string, unknown>;\n  [key: string]: unknown;\n};\n\n/** Runtime-light authentication option shape used on the 1auth JSON wire. */\nexport type AuthenticationOptionsJSON = {\n  challenge: string;\n  timeout?: number;\n  rpId?: string;\n  allowCredentials?: PublicKeyCredentialDescriptorJSON[];\n  userVerification?: \"discouraged\" | \"preferred\" | \"required\";\n  extensions?: Record<string, unknown>;\n  [key: string]: unknown;\n};\n\nexport type AuthFlowStartResult =\n  | { action: \"register\"; options: RegistrationOptionsJSON }\n  | {\n      action: \"authenticate\";\n      options: AuthenticationOptionsJSON;\n      accountAddress?: string;\n    }\n  | {\n      action: \"recover\";\n      accountAddress: string;\n      reason: \"no-active-passkeys\";\n    };\n\nexport type AuthFallbackAction = \"retry\" | \"add-device\" | \"recover\" | \"cancel\";\n\nexport type RecoveryRegistrationCtaBounds = {\n  left: number;\n  top: number;\n  width: number;\n  height: number;\n};\n\nexport type RecoveryRegistrationResult = {\n  credentialId: string;\n  publicKeyX: string;\n  publicKeyY: string;\n  credentialToken: string;\n  keyId: number;\n  replace: false;\n  transports: string[];\n};\n\nexport type AuthProtocolError = {\n  code: string;\n  message: string;\n  details?: Record<string, unknown>;\n};\n\nexport type RecoveryRegistrationError = {\n  name: string;\n  message: string;\n};\n\ntype CorrelatedEnvelope = {\n  requestId: string;\n  modalNonce: string;\n};\n\ntype SuccessfulEnvelope<\n  TType extends string,\n  TData = never,\n> = CorrelatedEnvelope & { type: TType; success: true } & ([TData] extends [\n    never,\n  ]\n    ? { data?: never }\n    : { data: TData });\n\ntype FailedEnvelope<TType extends string, TError> = CorrelatedEnvelope & {\n  type: TType;\n  success: false;\n  error: TError;\n  data?: never;\n};\n\n/** Messages sent from the host page into an authentication dialog. */\nexport type AuthHostMessage =\n  | (CorrelatedEnvelope & {\n      type: typeof PASSKEY_AUTH_FALLBACK;\n      error: string;\n    })\n  | (CorrelatedEnvelope & {\n      type: typeof PASSKEY_AUTH_REMEMBER_USER;\n      address: string;\n    })\n  | (CorrelatedEnvelope & { type: typeof PASSKEY_AUTH_COMPLETE })\n  | (CorrelatedEnvelope & { type: typeof PASSKEY_AUTH_REGISTRATION_READY })\n  | (CorrelatedEnvelope & { type: typeof PASSKEY_AUTH_REGISTRATION_ARMED })\n  | (CorrelatedEnvelope & { type: typeof PASSKEY_AUTH_REGISTRATION_COMMITTED })\n  | (CorrelatedEnvelope & {\n      type: typeof PASSKEY_RECOVERY_REGISTRATION_COMMITTED;\n    })\n  | SuccessfulEnvelope<typeof PASSKEY_RECOVERY_REGISTRATION_PREPARED>\n  | FailedEnvelope<\n      typeof PASSKEY_RECOVERY_REGISTRATION_PREPARED,\n      RecoveryRegistrationError\n    >\n  | SuccessfulEnvelope<\n      typeof PASSKEY_RECOVERY_REGISTRATION_RESULT,\n      RecoveryRegistrationResult\n    >\n  | FailedEnvelope<\n      typeof PASSKEY_RECOVERY_REGISTRATION_RESULT,\n      RecoveryRegistrationError\n    >\n  | (CorrelatedEnvelope & { type: typeof PASSKEY_RECOVERY_BACKUP_ARMED })\n  | (CorrelatedEnvelope & { type: typeof PASSKEY_RECOVERY_BACKUP_COMMITTED })\n  | SuccessfulEnvelope<\n      typeof PASSKEY_RECOVERY_BACKUP_PREPARED,\n      AuthenticationOptionsJSON & { expectedGuardianAddress: string }\n    >\n  | FailedEnvelope<\n      typeof PASSKEY_RECOVERY_BACKUP_PREPARED,\n      RecoveryRegistrationError\n    >\n  | SuccessfulEnvelope<\n      typeof PASSKEY_RECOVERY_BACKUP_RESULT,\n      { credentialId: string; prfFirst: number[] }\n    >\n  | FailedEnvelope<\n      typeof PASSKEY_RECOVERY_BACKUP_RESULT,\n      RecoveryRegistrationError\n    >;\n\n/** Messages sent from an authentication dialog to the host page. */\nexport type AuthDialogMessage =\n  | SuccessfulEnvelope<typeof PASSKEY_IDENTITY_RESULT, AuthIdentity>\n  | FailedEnvelope<typeof PASSKEY_IDENTITY_RESULT, AuthProtocolError>\n  | SuccessfulEnvelope<\n      typeof PASSKEY_IDENTITY_ACTION,\n      { action: AuthFallbackAction }\n    >\n  | SuccessfulEnvelope<\n      typeof PASSKEY_AUTH_REGISTRATION_CTA,\n      RecoveryRegistrationCtaBounds\n    >\n  | SuccessfulEnvelope<\n      typeof PASSKEY_RECOVERY_REGISTRATION_PREPARE,\n      { accountAddress: string }\n    >\n  | SuccessfulEnvelope<\n      typeof PASSKEY_RECOVERY_REGISTRATION_CTA,\n      RecoveryRegistrationCtaBounds\n    >\n  | SuccessfulEnvelope<typeof PASSKEY_RECOVERY_REGISTRATION_LISTENING>\n  | SuccessfulEnvelope<typeof PASSKEY_RECOVERY_REGISTRATION_CANCEL>\n  | SuccessfulEnvelope<typeof PASSKEY_RECOVERY_BACKUP_PREPARE>\n  | SuccessfulEnvelope<typeof PASSKEY_RECOVERY_BACKUP_CTA, RecoveryRegistrationCtaBounds>\n  | SuccessfulEnvelope<typeof PASSKEY_RECOVERY_BACKUP_CANCEL>;\n\nexport interface WebAuthnSignature {\n  authenticatorData: string;\n  clientDataJSON: string;\n  challengeIndex: number;\n  typeIndex: number;\n  r: string;\n  s: string;\n  topOrigin: string | null;\n}\n\n/** Passkey identity returned after server-side verification. */\nexport interface PasskeyCredentials {\n  credentialId: string;\n  publicKeyX: string;\n  publicKeyY: string;\n  /** Server-owned on-chain slot. Optional for compatibility with pre-slot SDK consumers. */\n  keyId?: number;\n}\n\n/**\n * Host → dialog init. Every dialog route shares these envelope fields and\n * reads its own payload fields on top; unknown fields are ignored.\n */\nexport type PasskeyInitMessage<\n  TPayload extends object = Record<string, unknown>,\n> = TPayload & {\n  type: typeof PASSKEY_INIT;\n  mode?: \"popup\" | \"popup-standalone\" | \"iframe\" | \"redirect\";\n  fullViewport?: boolean;\n  blindSigning?: boolean;\n  requestId?: string;\n  modalNonce?: string;\n  telemetry?: unknown;\n};\n\n/**\n * `PASSKEY_SIGNING_RESULT` data. The dialog sends `approved` (and `signedHash`\n * for message signing), or `error` when it refuses a transparent signature.\n */\nexport type SigningResultData = {\n  approved?: boolean;\n  signedHash?: string;\n  error?: string;\n};\n\nexport type GrantPermissionJsonValue =\n  | string\n  | number\n  | boolean\n  | null\n  | GrantPermissionJsonValue[]\n  | { [key: string]: GrantPermissionJsonValue };\n\nexport type GrantPermissionPayload = {\n  accountAddress?: `0x${string}`;\n  username?: string;\n  targetChain?: number;\n  targetChains?: number[];\n  sourceChains?: number[];\n  sessionKeyAddress: `0x${string}`;\n  /** v2 SmartSession `Permission<Abi>[]` payloads from `definePermissions()`. */\n  permissions: Array<Record<string, GrantPermissionJsonValue>>;\n  /** Cross-chain bridge/claim permits from `createCrossChainPermission()`. */\n  crossChainPermits?: Array<Record<string, GrantPermissionJsonValue>>;\n  validUntil?: number;\n  validAfter?: number;\n  maxUses?: number;\n  contracts?: Array<{\n    address: string;\n    name?: string;\n    abi?: GrantPermissionJsonValue[];\n  }>;\n  credentialId?: string;\n};\n\n/** Payload fields of the grant-permission dialog's `PASSKEY_INIT`. */\nexport type GrantPermissionInit = {\n  clientId?: string;\n  sponsor?: boolean;\n  appOrigin?: {\n    sessionToken: string;\n    webauthnMode?: AuthWebAuthnMode;\n    clientId?: string;\n  };\n  grant: GrantPermissionPayload;\n  auth: { accessToken: string };\n};\n\nexport type GrantExtensionTokenRequest = {\n  type: typeof PASSKEY_GRANT_EXTENSION_TOKEN_REQUEST;\n  requestId: string;\n  intentOp: string;\n};\n\nexport type GrantExtensionTokenResponse = {\n  type: typeof PASSKEY_GRANT_EXTENSION_TOKEN_RESPONSE;\n  requestId: string | undefined;\n  success: boolean;\n  token?: string;\n  error?: string;\n};\n\nexport type GrantAppOriginOptionsRequest = {\n  type: typeof PASSKEY_GRANT_APP_ORIGIN_OPTIONS_REQUEST;\n  requestId: string;\n  challenge: string;\n  binding: string;\n};\n\nexport type GrantAppOriginOptionsResponse = {\n  type: typeof PASSKEY_GRANT_APP_ORIGIN_OPTIONS_RESPONSE;\n  requestId: string | undefined;\n  success: boolean;\n  error?: string;\n};\n\nexport type GrantAppOriginExecutionRequest = {\n  type: typeof PASSKEY_GRANT_APP_ORIGIN_EXECUTION_REQUEST;\n  requestId: string;\n  challenge: string;\n  binding: string;\n  transaction: Record<string, unknown>;\n};\n\nexport type GrantAppOriginExecutionResponse = {\n  type: typeof PASSKEY_GRANT_APP_ORIGIN_EXECUTION_RESPONSE;\n  requestId: string | undefined;\n  success: boolean;\n  result?: Record<string, unknown>;\n  error?: string;\n};\n\nconst MAX_CORRELATION_LENGTH = 256;\nconst MAX_ERROR_NAME_LENGTH = 128;\nconst MAX_ERROR_CODE_LENGTH = 128;\nconst MAX_ERROR_MESSAGE_LENGTH = 2_048;\nconst ADDRESS_PATTERN = /^0x[0-9a-fA-F]{40}$/;\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n  return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction isBoundedString(value: unknown, maximum: number): value is string {\n  return (\n    typeof value === \"string\" && value.length > 0 && value.length <= maximum\n  );\n}\n\nfunction hasCorrelation(\n  value: Record<string, unknown>,\n): value is Record<string, unknown> & CorrelatedEnvelope {\n  return (\n    isBoundedString(value.requestId, MAX_CORRELATION_LENGTH) &&\n    isBoundedString(value.modalNonce, MAX_CORRELATION_LENGTH)\n  );\n}\n\nfunction isProtocolError(value: unknown): value is AuthProtocolError {\n  return (\n    isRecord(value) &&\n    isBoundedString(value.code, MAX_ERROR_CODE_LENGTH) &&\n    isBoundedString(value.message, MAX_ERROR_MESSAGE_LENGTH) &&\n    (value.details === undefined || isRecord(value.details))\n  );\n}\n\nfunction isRecoveryError(value: unknown): value is RecoveryRegistrationError {\n  return (\n    isRecord(value) &&\n    isBoundedString(value.name, MAX_ERROR_NAME_LENGTH) &&\n    isBoundedString(value.message, MAX_ERROR_MESSAGE_LENGTH)\n  );\n}\n\nfunction isVerifiedIdentity(value: unknown): value is VerifiedIdentity {\n  return (\n    isRecord(value) &&\n    value.kind === \"email\" &&\n    isBoundedString(value.identityHandle, 8_192) &&\n    isBoundedString(value.emailToken, 8_192) &&\n    isBoundedString(value.email, 320) &&\n    (value.recoveryRequested === undefined ||\n      typeof value.recoveryRequested === \"boolean\")\n  );\n}\n\nfunction isAuthIdentity(value: unknown): value is AuthIdentity {\n  return (\n    isVerifiedIdentity(value) ||\n    (isRecord(value) &&\n      value.kind === \"stored-session\" &&\n      typeof value.accountAddress === \"string\" &&\n      ADDRESS_PATTERN.test(value.accountAddress))\n  );\n}\n\nfunction isFallbackAction(value: unknown): value is AuthFallbackAction {\n  return (\n    value === \"retry\" ||\n    value === \"add-device\" ||\n    value === \"recover\" ||\n    value === \"cancel\"\n  );\n}\n\nfunction isCtaBounds(value: unknown): value is RecoveryRegistrationCtaBounds {\n  if (!isRecord(value)) return false;\n  const bounds = [value.left, value.top, value.width, value.height];\n  return (\n    bounds.every(\n      (entry) => typeof entry === \"number\" && Number.isFinite(entry),\n    ) &&\n    (value.left as number) >= 0 &&\n    (value.top as number) >= 0 &&\n    (value.width as number) >= 44 &&\n    (value.height as number) >= 32\n  );\n}\n\nfunction isRecoveryResult(value: unknown): value is RecoveryRegistrationResult {\n  return (\n    isRecord(value) &&\n    isBoundedString(value.credentialId, 8_192) &&\n    isBoundedString(value.publicKeyX, 256) &&\n    isBoundedString(value.publicKeyY, 256) &&\n    isBoundedString(value.credentialToken, 8_192) &&\n    Number.isSafeInteger(value.keyId) &&\n    (value.keyId as number) >= 0 &&\n    value.replace === false &&\n    Array.isArray(value.transports) &&\n    value.transports.length <= 16 &&\n    value.transports.every((transport) => isBoundedString(transport, 64))\n  );\n}\n\nfunction isBackupOptions(value: unknown): boolean {\n  return (\n    isRecord(value) &&\n    isBoundedString(value.challenge, 8_192) &&\n    (value.rpId === undefined || isBoundedString(value.rpId, 253)) &&\n    isBoundedString(value.expectedGuardianAddress, 42) &&\n    ADDRESS_PATTERN.test(value.expectedGuardianAddress) &&\n    Array.isArray(value.allowCredentials) &&\n    value.allowCredentials.length === 1\n  );\n}\n\nfunction isBackupResult(value: unknown): boolean {\n  return (\n    isRecord(value) &&\n    isBoundedString(value.credentialId, 8_192) &&\n    Array.isArray(value.prfFirst) &&\n    value.prfFirst.length === 32 &&\n    value.prfFirst.every(\n      (entry) => Number.isInteger(entry) && entry >= 0 && entry <= 255,\n    )\n  );\n}\n\n/** Validate an untrusted host-page message before dispatch. */\nexport function isAuthHostMessage(value: unknown): value is AuthHostMessage {\n  if (!isRecord(value) || !hasCorrelation(value)) return false;\n\n  switch (value.type) {\n    case PASSKEY_AUTH_FALLBACK:\n      return isBoundedString(value.error, MAX_ERROR_MESSAGE_LENGTH);\n    case PASSKEY_AUTH_REMEMBER_USER:\n      return (\n        typeof value.address === \"string\" && ADDRESS_PATTERN.test(value.address)\n      );\n    case PASSKEY_AUTH_COMPLETE:\n    case PASSKEY_AUTH_REGISTRATION_READY:\n    case PASSKEY_AUTH_REGISTRATION_ARMED:\n    case PASSKEY_AUTH_REGISTRATION_COMMITTED:\n    case PASSKEY_RECOVERY_REGISTRATION_COMMITTED:\n    case PASSKEY_RECOVERY_BACKUP_ARMED:\n    case PASSKEY_RECOVERY_BACKUP_COMMITTED:\n      return true;\n    case PASSKEY_RECOVERY_REGISTRATION_PREPARED:\n      return value.success === true\n        ? value.data === undefined\n        : value.success === false && isRecoveryError(value.error);\n    case PASSKEY_RECOVERY_REGISTRATION_RESULT:\n      return value.success === true\n        ? isRecoveryResult(value.data)\n        : value.success === false && isRecoveryError(value.error);\n    case PASSKEY_RECOVERY_BACKUP_PREPARED:\n      return value.success === true\n        ? isBackupOptions(value.data)\n        : value.success === false && isRecoveryError(value.error);\n    case PASSKEY_RECOVERY_BACKUP_RESULT:\n      return value.success === true\n        ? isBackupResult(value.data)\n        : value.success === false && isRecoveryError(value.error);\n    default:\n      return false;\n  }\n}\n\n/** Validate an untrusted authentication-dialog message before dispatch. */\nexport function isAuthDialogMessage(\n  value: unknown,\n): value is AuthDialogMessage {\n  if (!isRecord(value) || !hasCorrelation(value)) return false;\n\n  switch (value.type) {\n    case PASSKEY_IDENTITY_RESULT:\n      return value.success === true\n        ? isAuthIdentity(value.data)\n        : value.success === false && isProtocolError(value.error);\n    case PASSKEY_IDENTITY_ACTION:\n      return (\n        value.success === true &&\n        isRecord(value.data) &&\n        isFallbackAction(value.data.action)\n      );\n    case PASSKEY_AUTH_REGISTRATION_CTA:\n      return value.success === true && isCtaBounds(value.data);\n    case PASSKEY_RECOVERY_REGISTRATION_PREPARE:\n      return (\n        value.success === true &&\n        isRecord(value.data) &&\n        typeof value.data.accountAddress === \"string\" &&\n        ADDRESS_PATTERN.test(value.data.accountAddress)\n      );\n    case PASSKEY_RECOVERY_REGISTRATION_CTA:\n    case PASSKEY_RECOVERY_BACKUP_CTA:\n      return value.success === true && isCtaBounds(value.data);\n    case PASSKEY_RECOVERY_REGISTRATION_LISTENING:\n    case PASSKEY_RECOVERY_REGISTRATION_CANCEL:\n    case PASSKEY_RECOVERY_BACKUP_PREPARE:\n    case PASSKEY_RECOVERY_BACKUP_CANCEL:\n      return value.success === true && value.data === undefined;\n    default:\n      return false;\n  }\n}\n\nconst HOSTNAME_LABEL_PATTERN = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;\n\n/** Normalize a WebAuthn RP ID to one canonical DNS hostname. */\nexport function normalizeWebAuthnRpId(raw: string): string {\n  const value = raw.trim().toLowerCase();\n  if (\n    value.length === 0 ||\n    value.includes(\"://\") ||\n    value.includes(\"/\") ||\n    value.includes(\"@\") ||\n    value.includes(\":\") ||\n    value.includes(\"*\") ||\n    value.startsWith(\".\") ||\n    value.endsWith(\".\")\n  ) {\n    throw new Error(\"INVALID_WEBAUTHN_RP_ID\");\n  }\n  const labels = value.split(\".\");\n  if (\n    labels.length < 2 ||\n    labels.some((label) => !HOSTNAME_LABEL_PATTERN.test(label)) ||\n    /^\\d+(?:\\.\\d+){3}$/.test(value) ||\n    value.includes(\":\")\n  ) {\n    throw new Error(\"INVALID_WEBAUTHN_RP_ID\");\n  }\n  return value;\n}\n\n/** Normalize one exact WebAuthn ceremony origin while preserving significant ports. */\nexport function normalizeWebAuthnRpOrigin(\n  raw: string,\n  options: { allowHttpLocalhost?: boolean } = {},\n): string {\n  let parsed: URL;\n  try {\n    parsed = new URL(raw.trim());\n  } catch {\n    throw new Error(\"INVALID_WEBAUTHN_RP_ORIGIN\");\n  }\n  const hostname = parsed.hostname.toLowerCase();\n  const localhost = hostname === \"localhost\";\n  if (\n    parsed.username ||\n    parsed.password ||\n    parsed.pathname !== \"/\" ||\n    parsed.search ||\n    parsed.hash ||\n    hostname.includes(\"*\") ||\n    hostname.includes(\":\") ||\n    /^\\d+(?:\\.\\d+){3}$/.test(hostname) ||\n    (parsed.protocol !== \"https:\" &&\n      !(options.allowHttpLocalhost && localhost && parsed.protocol === \"http:\"))\n  ) {\n    throw new Error(\"INVALID_WEBAUTHN_RP_ORIGIN\");\n  }\n  if (!localhost) normalizeWebAuthnRpId(hostname);\n  return parsed.origin.toLowerCase();\n}\n\n/** Return whether an exact origin's hostname is the RP ID or its subdomain. */\nexport function webAuthnOriginBelongsToRpId(\n  origin: string,\n  rpId: string,\n): boolean {\n  const hostname = new URL(origin).hostname.toLowerCase();\n  const normalizedRpId = normalizeWebAuthnRpId(rpId);\n  return hostname === normalizedRpId || hostname.endsWith(`.${normalizedRpId}`);\n}\n\n/** Normalize and validate the atomic server-owned RP ID/origin configuration. */\nexport function normalizeWebAuthnRpConfiguration(input: {\n  rpId: string | null;\n  rpOrigins: readonly string[];\n  allowHttpLocalhost?: boolean;\n}): { rpId: string | null; rpOrigins: string[] } {\n  if (input.rpId === null) {\n    if (input.rpOrigins.length > 0)\n      throw new Error(\"INVALID_WEBAUTHN_RP_ORIGIN\");\n    return { rpId: null, rpOrigins: [] };\n  }\n  const rpId = normalizeWebAuthnRpId(input.rpId);\n  const rpOrigins = [\n    ...new Set(\n      input.rpOrigins.map((origin) =>\n        normalizeWebAuthnRpOrigin(origin, {\n          allowHttpLocalhost: input.allowHttpLocalhost,\n        }),\n      ),\n    ),\n  ].sort();\n  if (rpOrigins.length === 0) throw new Error(\"INVALID_WEBAUTHN_RP_ORIGIN\");\n  if (rpOrigins.some((origin) => !webAuthnOriginBelongsToRpId(origin, rpId))) {\n    throw new Error(\"WEBAUTHN_ORIGIN_OUTSIDE_RP_ID\");\n  }\n  return { rpId, rpOrigins };\n}\n\n/** Persisted deployment transport only, not an ownership or recipe assertion. */\nexport type AccountVerificationData = {\n  transportVersion: 1;\n  address: `0x${string}`;\n  chainId: number;\n  factoryAddress: `0x${string}`;\n  factoryData: `0x${string}`;\n};\nexport {\n  ACCOUNT_VERIFICATION_TRANSPORT_VERSION,\n  MAX_ACCOUNT_FACTORY_DATA_BYTES,\n  MAX_ACCOUNT_VERIFICATION_RESPONSE_BYTES,\n  isVerificationAddress,\n  isVerificationFactoryData,\n  parseAccountVerificationData,\n} from \"./account-verification-wire\";\nexport * from \"./solana-setup\";\nexport * from \"./solana-recovery\";\n/** Public Solana locators only, not an ownership or readiness assertion. */\nexport type SolanaAccountVerificationData = {\n  transportVersion: 1;\n  account: `0x${string}`;\n  chain: \"solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp\" | \"solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1\";\n  wallet: string;\n  swigAccount: string;\n};\nexport {\n  SOLANA_ACCOUNT_VERIFICATION_VERSION,\n  MAX_SOLANA_VERIFICATION_RESPONSE_BYTES,\n  isSolanaVerificationChain,\n  isSolanaVerificationAddress,\n  parseSolanaAccountVerificationData,\n} from \"./solana-verification-wire\";\nexport * from \"./smart-session\";\n","import { isAddress } from 'viem';\nimport { locateSwigWallet } from '../accounts/solana/address.js';\nimport { compressP256PublicKey } from '../accounts/solana/passkey.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 { 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 use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n * See utils.ts for details.\n * @module\n */\ndeclare const globalThis: Record<string, any> | undefined;\nexport const crypto: any =\n  typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : 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","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: 'A source call `provides` a token other than `source.token`. Source calls run on the source chain and can only make more of the source token available.',\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 by an earlier SDK generation or 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 { bytesToHex, hexToBytes } from 'viem';\n// source: SEC 2 v2 §2.4.1 — secp256k1 field prime p = 2^256 - 2^32 - 977, curve y² = x³ + 7.\nconst SECP256K1_P = 2n ** 256n - 2n ** 32n - 977n;\nconst SECP256K1_B = 7n;\nconst HEX = /^0x(?:[0-9a-fA-F]{2})+$/u;\n/**\n * SEC1-compresses a public key on any short-Weierstrass curve with 32-byte\n * coordinates: a 64-byte x‖y or a 65-byte `0x04`-prefixed key gets the prefix\n * from y's parity, and a 33-byte compressed key passes through. `undefined` for\n * any other shape. The point is not checked to lie on a curve.\n */\nexport function compressSec1PublicKey(publicKey) {\n    const bytes = hexToBytes(publicKey);\n    if (bytes.length === 33 && (bytes[0] === 2 || bytes[0] === 3)) {\n        return publicKey;\n    }\n    const point = uncompressedPoint(bytes);\n    if (!point)\n        return undefined;\n    const prefix = point[63] % 2 === 0 ? 0x02 : 0x03;\n    return bytesToHex(new Uint8Array([prefix, ...point.subarray(0, 32)]));\n}\n/** Whether `value` is a 33-byte SEC1-compressed key in lowercase hex. */\nexport function isCompressedSec1PublicKey(value) {\n    return typeof value === 'string' && /^0x0[23][0-9a-f]{64}$/u.test(value);\n}\n/** Whether `value` is hex of exactly 20 bytes: an EVM address, never a public key. */\nexport function isEvmAddressLength(value) {\n    return typeof value === 'string' && /^0x[0-9a-fA-F]{40}$/u.test(value);\n}\n/**\n * The canonical form of a secp256k1 public key — compressed, lowercase hex —\n * from 33-byte compressed, 65-byte uncompressed or 64-byte x‖y hex. An\n * uncompressed key must lie on secp256k1, since compressing drops the y that\n * would reveal a key from another curve; a compressed key is shape-checked\n * only. `undefined` when `value` is not such a key.\n */\nexport function canonicalSecp256k1PublicKey(value) {\n    if (typeof value !== 'string' || !HEX.test(value))\n        return undefined;\n    const bytes = hexToBytes(value);\n    const point = uncompressedPoint(bytes);\n    if (point && !onSecp256k1(point))\n        return undefined;\n    return compressSec1PublicKey(value)?.toLowerCase();\n}\nfunction uncompressedPoint(bytes) {\n    if (bytes.length === 64)\n        return bytes;\n    if (bytes.length === 65 && bytes[0] === 4)\n        return bytes.subarray(1);\n    return undefined;\n}\nfunction onSecp256k1(point) {\n    const x = BigInt(bytesToHex(point.subarray(0, 32)));\n    const y = BigInt(bytesToHex(point.subarray(32)));\n    if (x >= SECP256K1_P || y >= SECP256K1_P)\n        return false;\n    return (y * y - (x * x * x + SECP256K1_B)) % SECP256K1_P === 0n;\n}\n","import { InvalidSolanaTransactionArtifactError } from '../../errors/execution.js';\nimport { compressSec1PublicKey } from './keys.js';\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 compressed = compressSec1PublicKey(publicKey);\n    if (!compressed) {\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    return compressed;\n}\n/**\n * The canonical form of a P-256 public key in any encoding\n * {@link compressP256PublicKey} accepts: compressed, lowercase hex. `undefined`\n * when `value` is not such a key, so each caller refuses with its own error.\n */\nexport function canonicalP256PublicKey(value) {\n    if (typeof value !== 'string' || !/^0x(?:[0-9a-fA-F]{2})+$/u.test(value)) {\n        return undefined;\n    }\n    return compressSec1PublicKey(value)?.toLowerCase();\n}\n","export function assertNoRemovedApiKey(input) {\n    if ('apiKey' in input) {\n        throw new Error(\"Top-level `apiKey` was removed; use auth: { mode: 'apiKey', apiKey } instead\");\n    }\n}\nexport function assertSdkAuthInput(input) {\n    assertNoRemovedApiKey(input);\n    if (!input.auth) {\n        throw new Error('RhinestoneSDK requires `auth` in config');\n    }\n}\n","import { assertNoRemovedApiKey, assertSdkAuthInput } from './removed-inputs.js';\nexport function captureLegacySdkConfig(input, authProvider) {\n    assertSdkAuthInput(input);\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    assertNoRemovedApiKey(input);\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';\nimport { assertNoRemovedApiKey, assertSdkAuthInput } from './removed-inputs.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    const auth = input.auth;\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                version: selectValue(account.version, 'startale-current-version'),\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    assertSdkAuthInput(input);\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    assertNoRemovedApiKey(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    assertNoRemovedApiKey(input);\n    return resolveAccountWithDefaults(input, standaloneDefaults[profile], 'production');\n}\nfunction materializeSdkInvocationConfig(sdk, compatibility) {\n    assertNoRemovedApiKey(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 { 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 { compressP256PublicKey } from '../accounts/solana/passkey.js';\nimport { parseCaip2, toEvmChainReference } from '../chains/caip2.js';\nimport { getChainById, getChainReference } from '../chains/catalog.js';\nimport { normalizeTokenAddress } from '../chains/tokens.js';\nimport { isSolanaAccountAlreadyCreated, isSolanaAuthorityChangeRefused, } from '../clients/orchestrator/errors.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 { SOLANA_AUTHORITY_SPONSORSHIP, solanaChainId, } from '../transactions/intents/solana.js';\nimport { normalizeSolanaInstructions } from '../transactions/intents/solana-instructions.js';\nimport { toPublicTransactionStatus } from './project-mappers.js';\nimport { adaptSignerSelection, adaptUserOperationSignerSelection, } from './signer-selection.js';\nimport { isCrossChainSolanaOrigin, isSolanaAuthorityChange, isSolanaInstructionExecution, isSolanaOrigin, normalizeAuthorityChange, normalizeTransaction, } from './transaction-input.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: prepared.intentInput,\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    if (action.kind === 'authority') {\n        const { change } = action;\n        return {\n            kind: 'solana-authority',\n            ...binding,\n            accountAddress: input.walletAddress,\n            action: change.action,\n            keyType: change.keyType,\n            key: change.key,\n            ...(change.permission ? { permission: change.permission } : {}),\n        };\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: prepared.intentInput,\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        approvalInput: 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}\n/**\n * Refuses an artifact from an earlier SDK or wire generation before its\n * transaction is read, then validates the transaction against the current\n * model.\n */\nfunction assertPreparedArtifact(prepared, config) {\n    assertPreparedBinding(prepared?.request);\n    normalizeTransaction(prepared.transaction, config);\n}\n/** The same-chain fee token an intent-path deployment or setup spends. */\nfunction setupSourceToken(options, chain) {\n    const source = options?.source;\n    if (source === undefined)\n        return {};\n    if (typeof source !== 'object' ||\n        source === null ||\n        Object.keys(source).some((key) => key !== 'token') ||\n        typeof source.token !== 'string' ||\n        !isAddress(source.token)) {\n        throw new UnsupportedAccountCapabilityError(`\\`source\\` must be \\`{ token }\\`, a token address on ${chain.name ?? `chain ${chain.id}`} that pays for the setup.`, { field: 'source.token', chainId: chain.id });\n    }\n    return { sourceToken: source.token };\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        assertPreparedArtifact(prepared, publicConfig);\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 options = params;\n            return workflowsFor(ctx).deploy(ctx, toEvmChainReference(chain.id), {\n                ...(options?.sponsored !== undefined\n                    ? { sponsored: options.sponsored }\n                    : {}),\n                ...setupSourceToken(options, chain),\n            });\n        }),\n        async getAuthorityStatus(transaction) {\n            const origin = requireSolana();\n            const ctx = context('prepare-intent');\n            return origin.authorityStatus(ctx.sdk, workflowsFor(ctx), normalizeAuthorityChange(transaction, publicConfig));\n        },\n        isDeployed(chain) {\n            const ctx = context('is-deployed');\n            return workflowsFor(ctx).isDeployed(ctx, toEvmChainReference(chain.id));\n        },\n        setup(chain, options) {\n            const ctx = context('setup');\n            return workflowsFor(ctx).setup(ctx, toEvmChainReference(chain.id), setupSourceToken(options, chain));\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 target = initiallyNormalized.destination;\n            const normalized = !isSolanaOrigin(initiallyNormalized) &&\n                target.chain.kind === 'svm' &&\n                target.recipient === undefined &&\n                solana\n                ? Object.freeze({\n                    ...initiallyNormalized,\n                    destination: Object.freeze({\n                        ...target,\n                        recipient: solana.walletAddress,\n                    }),\n                })\n                : initiallyNormalized;\n            if (isSolanaOrigin(normalized)) {\n                const origin = requireSolana();\n                const workflows = workflowsFor(ctx);\n                let execution;\n                if (isCrossChainSolanaOrigin(normalized) &&\n                    normalized.destination.calls?.length) {\n                    origin.assertDestinationCallsSupported();\n                    const { destination } = normalized;\n                    const chainId = destination.chain.id;\n                    const resolved = await workflows.resolveSolanaEvmDestination(ctx, {\n                        chain: toEvmChainReference(chainId),\n                        calls: destination.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                                ...(destination.gasLimit === undefined\n                                    ? {}\n                                    : { gasLimit: destination.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: target.hyperCore,\n                account: workflowsFor(ctx).getAddress(ctx, referenceChain()),\n                ...(ctx.sdk.hyperliquid ? { hyperliquid: ctx.sdk.hyperliquid } : {}),\n            });\n            const prepared = await workflowsFor(ctx).prepareIntent(ctx, adaptTransaction(ctx, normalized, hyperCoreAction));\n            return toPreparedTransactionData(prepared, normalized, preparedIntents);\n        },\n        getTransactionMessages(preparedTransaction, options) {\n            assertPreparedArtifact(preparedTransaction, publicConfig);\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            assertPreparedArtifact(preparedTransaction, publicConfig);\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            assertPreparedArtifact(preparedTransaction, publicConfig);\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            assertPreparedArtifact(preparedTransaction, 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            assertPreparedArtifact(signedTransaction, 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, options) {\n            const ctx = context('get-session-details');\n            return workflowsFor(ctx).getSessionDetails(ctx, sessions, options);\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, candidate, execution) => {\n        const transaction = normalizeTransaction(candidate, 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        if (isSolanaAuthorityChange(transaction)) {\n            // Always sponsored and fee-free, and never through a paired EVM account:\n            // the change is to this Swig alone.\n            const { action, key, permission } = transaction.destination.authority;\n            return {\n                chain: transaction.destination.chain,\n                accountAddress: source.walletAddress,\n                authority,\n                walletAddress: source.walletAddress,\n                swigAddress: source.swigAddress,\n                namespace,\n                endpoint: sdk.orchestratorUrl,\n                sponsorSettings: { ...SOLANA_AUTHORITY_SPONSORSHIP },\n                action: {\n                    kind: 'authority',\n                    change: {\n                        action,\n                        keyType: key.type,\n                        key: key.publicKey,\n                        ...(action === 'add' ? { permission } : {}),\n                    },\n                },\n            };\n        }\n        const fees = transaction;\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            ...(fees.appFees ? { appFees: fees.appFees } : {}),\n            ...(fees.protocolFees ? { protocolFees: fees.protocolFees } : {}),\n            ...(() => {\n                const sponsorSettings = toSponsorSettings(transaction.sponsored);\n                return sponsorSettings ? { sponsorSettings } : {};\n            })(),\n        };\n        if (isCrossChainSolanaOrigin(transaction)) {\n            const { destination } = transaction;\n            // Resolved here rather than in `normalizeTransaction` so the prepare and\n            // reconstruct paths agree on the same recipient.\n            const recipient = destination.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 `destination.recipient`.', { vm: 'solana', field: 'destination.recipient' });\n            }\n            return {\n                ...common,\n                chain: transaction.source.chain,\n                action: {\n                    kind: 'transfer',\n                    mint: transaction.source.token,\n                    ...(destination.amount === undefined\n                        ? {}\n                        : { amount: destination.amount }),\n                    ...(transaction.source.maxAmount === undefined\n                        ? {}\n                        : { sourceLimit: transaction.source.maxAmount }),\n                    delivery: {\n                        kind: 'cross-chain',\n                        chainId: destination.chain.id,\n                        token: destination.token,\n                        recipient,\n                        ...(execution ? { execution } : {}),\n                    },\n                },\n            };\n        }\n        if (isSolanaInstructionExecution(transaction)) {\n            const { destination } = transaction;\n            return {\n                ...common,\n                chain: destination.chain,\n                action: {\n                    kind: 'instructions',\n                    instructions: normalizeSolanaInstructions(destination.instructions),\n                    ...(destination.addressLookupTables\n                        ? { addressLookupTables: destination.addressLookupTables }\n                        : {}),\n                    ...(transaction.source ? { feeToken: transaction.source.token } : {}),\n                },\n            };\n        }\n        const { destination, source: spend } = transaction;\n        return {\n            ...common,\n            chain: destination.chain,\n            action: {\n                kind: 'transfer',\n                mint: destination.token,\n                ...(destination.amount === undefined\n                    ? {}\n                    : { amount: destination.amount }),\n                ...(spend.maxAmount === undefined\n                    ? {}\n                    : { sourceLimit: spend.maxAmount }),\n                delivery: { kind: 'same-chain', recipient: destination.recipient },\n            },\n        };\n    };\n    const resolve = (sdk, workflows, prepared, intentId, explicitQuote) => {\n        assertPreparedBinding(prepared.request);\n        const transaction = normalizeTransaction(prepared.transaction, publicConfig);\n        const destinationCalls = isCrossChainSolanaOrigin(transaction)\n            ? transaction.destination.calls\n            : undefined;\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 (destinationCalls?.length)\n            assertDestinationCallsSupported();\n        const stored = prepared.intentInput;\n        const storedExecution = stored.destination.vm === 'evm' ? stored.destination.execution : undefined;\n        const evm = stored.account.evm;\n        const execution = destinationCalls?.length && storedExecution && evm\n            ? {\n                calls: storedExecution.calls.map(({ to, value, data }) => ({\n                    target: to,\n                    value: BigInt(value),\n                    data,\n                })),\n                ...(storedExecution.gasLimit === undefined\n                    ? {}\n                    : { gasLimit: BigInt(storedExecution.gasLimit) }),\n                account: {\n                    kind: evm.type,\n                    address: evm.address,\n                    setupOps: evm.type === 'erc7579' ? (evm.initData?.setupOps ?? []) : [],\n                    ...(evm.delegations?.default\n                        ? { delegationContract: evm.delegations.default.contract }\n                        : {}),\n                },\n            }\n            : undefined;\n        const input = transfer(sdk, 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    const authorityStatus = async (sdk, workflows, transaction) => {\n        const change = transaction.destination.authority;\n        try {\n            await workflows.prepareSolanaIntent(transfer(sdk, transaction));\n            return { status: 'notApplied' };\n        }\n        catch (error) {\n            if (!isSolanaAuthorityChangeRefused(error) ||\n                (error.swigAddress !== undefined &&\n                    error.swigAddress !== source.swigAddress)) {\n                throw error;\n            }\n            if (change.action === 'add' &&\n                error.reason === 'authority_exists' &&\n                error.roleId !== undefined) {\n                if (error.permission === change.permission) {\n                    return { status: 'applied', roleId: error.roleId };\n                }\n                return {\n                    status: 'conflict',\n                    roleId: error.roleId,\n                    ...(error.permission ? { permission: error.permission } : {}),\n                };\n            }\n            if (change.action === 'remove' &&\n                error.reason === 'authority_not_found') {\n                return { status: 'applied' };\n            }\n            throw error;\n        }\n    };\n    return {\n        walletAddress: source.walletAddress,\n        assertDestinationCallsSupported,\n        authorityStatus,\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            assertPreparedBinding(signedTransaction.request);\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        getAuthorityStatus: async (transaction) => solana.authorityStatus(sdk, workflows, normalizeAuthorityChange(transaction, publicConfig)),\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 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) {\n    if (isSolanaOrigin(transaction)) {\n        throw new UnsupportedAccountCapabilityError('Solana-origin transactions run through the managed Solana account.', { vm: 'solana' });\n    }\n    const { source, destination: target } = transaction;\n    const destination = 'kind' in target.chain\n        ? parseCaip2(target.chain.caip2)\n        : getChainReference(target.chain.id);\n    const destinationChainId = destination.kind === 'evm' ? destination.id : undefined;\n    const sourceChain = source?.chain\n        ? toEvmChainReference(source.chain.id)\n        : undefined;\n    const evmTarget = target;\n    return {\n        destination,\n        ...(source && sourceChain\n            ? {\n                source: {\n                    chain: sourceChain,\n                    token: source.token,\n                    ...(source.maxAmount === undefined\n                        ? {}\n                        : { maxAmount: source.maxAmount }),\n                    ...(source.auxiliaryFunds === undefined\n                        ? {}\n                        : { auxiliaryFunds: source.auxiliaryFunds }),\n                    ...(source.calls\n                        ? {\n                            calls: source.calls.map((call) => ({\n                                call: adaptCall(call, sourceChain.id),\n                                ...(call.provides ? { provides: call.provides } : {}),\n                            })),\n                        }\n                        : {}),\n                },\n            }\n            : {}),\n        calls: (evmTarget.calls ?? []).map((call) => adaptCall(call, destinationChainId)),\n        ...(evmTarget.token === undefined\n            ? {}\n            : {\n                token: destinationChainId === undefined\n                    ? evmTarget.token\n                    : normalizeTokenAddress(evmTarget.token, destinationChainId, false),\n            }),\n        ...(evmTarget.amount === undefined ? {} : { amount: evmTarget.amount }),\n        ...(evmTarget.recipient\n            ? {\n                recipient: adaptRecipient(context, evmTarget.recipient, destination, transaction.eip7702InitSignature, transaction.experimental_accountOverride?.setupOps),\n            }\n            : {}),\n        ...(evmTarget.gasLimit === undefined\n            ? {}\n            : { gasLimit: evmTarget.gasLimit }),\n        ...(transaction.eip7702InitSignature\n            ? { eip7702InitSignature: transaction.eip7702InitSignature }\n            : {}),\n        options: {\n            ...(transaction.appFees ? { appFees: transaction.appFees } : {}),\n            ...(transaction.protocolFees\n                ? { protocolFees: transaction.protocolFees }\n                : {}),\n            ...(transaction.customDeadline === undefined\n                ? {}\n                : { customDeadline: transaction.customDeadline }),\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                    ...(sourceChain ? [sourceChain.id] : []),\n                ]);\n                const quoters = narrowQuoterPin(derived, transaction.quoters);\n                return quoters ? { quoters } : {};\n            })(),\n            ...(hyperCoreAction ? { hyperCore: { action: hyperCoreAction } } : {}),\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.signers, [\n                            ...(sourceChain ? [sourceChain.id] : []),\n                            ...(destinationChainId === undefined\n                                ? []\n                                : [destinationChainId]),\n                        ]),\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(signers, chainIds) {\n    if ('sessions' in signers) {\n        return Object.fromEntries(Object.entries(signers.sessions).map(([chainId, selection]) => [\n            Number(chainId),\n            selection,\n        ]));\n    }\n    return Object.fromEntries([...new Set(chainIds)].map((chainId) => [\n        chainId,\n        {\n            session: signers.session,\n            ...(signers.enableData ? { enableData: signers.enableData } : {}),\n        },\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","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 { 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 { 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}\nconst SOLANA_AUTHORITY_CHANGE_REFUSAL_REASONS = [\n    'acting_permission',\n    'authority_exists',\n    'authority_not_found',\n    'authority_ambiguous',\n    'root_role',\n    'unsupported_authority',\n    'lockout',\n];\n/**\n * The orchestrator refused a Swig authority (passkey or secp256k1 key) add or\n * remove against the Swig's current roles. Nothing was signed or submitted.\n *\n * After an uncertain outcome (a failed wait, a network error on submit), call\n * `getAuthorityStatus` with the same change: it reads this refusal for you. An\n * add refused with `authority_exists` and the same `permission` already\n * landed, while a different or absent `permission` is a conflict to resolve; a\n * remove refused with `authority_not_found` already landed.\n *\n * `reason` is absent when the orchestrator sent a reason this SDK version does\n * not know; the raw context stays readable on `issues[].context`.\n */\nclass SolanaAuthorityChangeRefusedError extends ValidationError {\n    reason;\n    /** The Swig state account the change targeted. */\n    swigAddress;\n    /** The role the refusal names: the existing, acting or target role. */\n    roleId;\n    /** Every role carrying the key, on `authority_ambiguous`. */\n    roleIds;\n    /** The existing role's permission, on `authority_exists` when readable. */\n    permission;\n    constructor(params) {\n        super(params);\n        if (params.reason !== undefined)\n            this.reason = params.reason;\n        if (params.swigAddress !== undefined)\n            this.swigAddress = params.swigAddress;\n        if (params.roleId !== undefined)\n            this.roleId = params.roleId;\n        if (params.roleIds !== undefined)\n            this.roleIds = params.roleIds;\n        if (params.permission !== undefined)\n            this.permission = params.permission;\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}\nfunction roleIdValue(value) {\n    return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0\n        ? value\n        : undefined;\n}\nfunction parseSolanaAuthorityChangeRefusedError(base, issues) {\n    const context = issues.find((issue) => issue.context?.code === 'SWIG_AUTHORITY_CHANGE_REFUSED')?.context;\n    if (!context) {\n        return undefined;\n    }\n    const reason = oneOf(context.reason, SOLANA_AUTHORITY_CHANGE_REFUSAL_REASONS);\n    const swigAddress = stringValue(context.swig);\n    const roleId = roleIdValue(context.roleId);\n    const roleIds = Array.isArray(context.roleIds)\n        ? context.roleIds.map(roleIdValue)\n        : undefined;\n    const permission = oneOf(context.permission, [\n        'all',\n        'allButManageAuthority',\n        'manageAuthority',\n    ]);\n    return new SolanaAuthorityChangeRefusedError({\n        ...base,\n        issues,\n        ...(reason === undefined ? {} : { reason }),\n        ...(swigAddress ? { swigAddress } : {}),\n        ...(roleId === undefined ? {} : { roleId }),\n        ...(roleIds?.every((id) => id !== undefined)\n            ? { roleIds: roleIds }\n            : {}),\n        ...(permission === undefined ? {} : { permission }),\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 (parseSolanaAuthorityChangeRefusedError(base, issues) ??\n                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}\n/** Whether `error` is the orchestrator refusing a Swig authority add or remove. */\nfunction isSolanaAuthorityChangeRefused(error) {\n    return error instanceof SolanaAuthorityChangeRefusedError;\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, isSolanaAuthorityChangeRefused, isRateLimited, isSimulationFailed, isSponsorLimitExceeded, isInsufficientSponsorBalance, isSponsorError, OrchestratorError, ValidationError, SolanaAccountNotCreatedError, SolanaAccountAlreadyCreatedError, SolanaAuthorityChangeRefusedError, InsufficientLiquidityError, SponsorLimitExceededError, InsufficientSponsorBalanceError, NotFoundError, UnauthorizedError, ForbiddenError, KeyScopeDeniedError, ConflictError, UnprocessableContentError, RateLimitedError, SettlementQuoteError, SettlementExecutionError, SimulationFailedError, ExternalServiceTimeoutError, RelayerMarketUnavailableError, InternalServerError, };\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 { encodeAddressEnvelope, encodeInstallModule, encodeUninstallModule, primaryOwnerAddresses, } from './shared.js';\nexport { K1_DEFAULT_VALIDATOR_ADDRESS };\n// The contract's EIP-712 domain version equals its release version.\nexport function startaleEip712Domain(account, chainId, version) {\n    return {\n        name: 'Startale',\n        version,\n        chainId,\n        verifyingContract: account,\n        salt: zeroHash,\n    };\n}\n// Current default (1.0.1): new implementation + factory, same bootstrap, K1\n// default validator, and proxy creation code as 1.0.0. `version: '1.0.0'` opts\n// back into the previous contracts so existing accounts keep their address.\nconst STARTALE_DEPLOYMENTS = {\n    '1.0.0': {\n        implementation: '0x000000b8f5f723a680d3d7ee624fe0bc84a6e05a',\n        factory: '0x0000003b3e7b530b4f981ae80d9350392defef90',\n    },\n    '1.0.1': {\n        implementation: '0x000006b2874cf8a9bbe24fa1c3a32225ae826951',\n        factory: '0x00000be75c267efe9ddd7044d1f236959af4c15f',\n    },\n};\nconst STARTALE_VERSION_DEFAULTS = {\n    'startale-current-version': '1.0.1',\n};\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}\n// A persisted `{ factory, factoryData }` pins the version by its factory, so it\n// recomputes against the implementation that factory deploys. Otherwise the\n// configured version applies (the only signal for address-only `initData`).\nfunction startaleVersion(input) {\n    if (input.account.kind !== 'startale') {\n        throw new Error('Expected Startale account');\n    }\n    if (input.initData && 'factory' in input.initData) {\n        const factory = input.initData.factory.toLowerCase();\n        const pinned = Object.keys(STARTALE_DEPLOYMENTS).find((version) => STARTALE_DEPLOYMENTS[version].factory === factory);\n        if (pinned)\n            return pinned;\n    }\n    return selectedValue(input.account.version, STARTALE_VERSION_DEFAULTS);\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    const deployment = STARTALE_DEPLOYMENTS[startaleVersion(input)];\n    let factory = deployment.factory;\n    let factoryData;\n    let salt;\n    let initializationCallData;\n    if (input.initData && 'factory' in input.initData) {\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' }], [deployment.implementation, 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: {\n                kind: 'startale',\n                validator,\n                version: startaleVersion(construction),\n            },\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 EVM address holding collateral and positions, not the SDK account handle\n * @param options where to reach Hyperliquid's info endpoint\n * @returns one entry per open position; empty when the account holds none\n * @example\n * const positions = await getPerpPositions(account.getAddress('evm'))\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 EVM address holding the position, not the SDK account handle\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 { 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}\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-singular-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 or SDK generation.\n *\n * Called before anything reads the artifact's transaction or quotes, so an\n * older shape fails with this typed error rather than being validated, or\n * reinterpreted, against the current transaction model.\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 { 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 { hashTypedData, keccak256, stringToHex, } from 'viem';\nimport { resolveCalls } from '../../calls/resolve.js';\nimport { isHyperCoreWireId, toEvmChainReference } from '../../chains/caip2.js';\nimport { isSponsoredIntentInput } from '../../clients/orchestrator/sponsorship-approval.js';\nimport { UnsupportedAccountCapabilityError } from '../../errors/capability.js';\nimport { InvalidSourceCallsError, 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 { constrainSessionIntent } from './session-routing.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    input = constrainSessionIntent(input, runtime.identity.address);\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 preClaimCalls = sessions?.preClaimCalls ?? [];\n    if (preClaimCalls.length > 0 && !input.source) {\n        throw new UnsupportedAccountCapabilityError('Enabling the smart session runs a call on the source chain before the claim, and this transaction names no `source`. Add a `source`, or enable the session first.', { field: 'source' });\n    }\n    const ownerSelection = input.signers?.kind === 'owner' ? input.signers : undefined;\n    const { request, intentInput } = 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: sessions?.destinationBurn && calls.length > 0\n            ? [sessions.destinationBurn, ...calls]\n            : calls,\n        sourceCalls: [...preClaimCalls, ...source.calls],\n        providedFunds: source.providedFunds,\n    });\n    const response = await context.quoteClient.createQuote(request, {\n        intentInput,\n        sponsored: isSponsoredIntentInput(intentInput),\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        intentInput,\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    if (!input.source) {\n        throw new Error(`An intent to ${input.destination.caip2} requires an EVM source chain: the destination hosts no account runtime`);\n    }\n    return input.source.chain;\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 source = input.source;\n    if (!source?.calls?.length)\n        return { calls: [], providedFunds: 0n };\n    const calls = await resolveCalls(source.calls.map(({ call }) => call), {\n        account: runtime.identity.address,\n        chain: source.chain,\n        config: context.compatibilityConfig,\n    });\n    let providedFunds = 0n;\n    for (const sourceCall of source.calls) {\n        for (const provided of sourceCall.provides ?? []) {\n            if (provided.token.toLowerCase() !== source.token.toLowerCase()) {\n                throw new InvalidSourceCallsError({ chainId: source.chain.id });\n            }\n            providedFunds += provided.amount;\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}\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 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 { UnsupportedSponsorshipApprovalError } from '../../errors/execution.js';\nimport { serializeBigInts } from './serialization.js';\n// The sponsorship approval contract `sdk-3.0.0-caucasus`: the\n// approval input an intent-scoped grant commits to is the singular Caucasus\n// quote body itself, validated field by field. The orchestrator recomputes it\n// from the body it received, so any field outside this allowlist is refused\n// rather than hashed: a stripped extra field would let two different requests\n// share one grant. docs/sponsorship-approval.md is the published form.\nexport const SPONSORSHIP_APPROVAL_CONTRACT = 'sdk-3.0.0-caucasus';\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 optionalString(value, field) {\n    if (value !== undefined)\n        string(value, field);\n}\nconst CAIP2 = /^(eip155|solana|tron|hypercore|stellar):[-_a-zA-Z0-9]{1,32}$/u;\nfunction chainId(value, field) {\n    if (!CAIP2.test(string(value, field)))\n        unsupported(field);\n}\nfunction calls(value, field) {\n    for (const [index, call] of array(value, field).entries()) {\n        const entry = object(call, `${field}.${index}`, ['to', 'value', 'data']);\n        string(entry.to, `${field}.${index}.to`);\n        string(entry.value, `${field}.${index}.value`);\n        string(entry.data, `${field}.${index}.data`);\n    }\n}\nfunction evmExecution(value, field) {\n    const execution = object(value, field, ['calls', 'gasLimit']);\n    calls(execution.calls, `${field}.calls`);\n    optionalString(execution.gasLimit, `${field}.gasLimit`);\n}\nfunction delegations(value, field) {\n    const entry = object(value, field, ['default', 'chains']);\n    if (entry.default !== undefined) {\n        const target = object(entry.default, `${field}.default`, ['contract']);\n        string(target.contract, `${field}.default.contract`);\n    }\n    if (entry.chains !== undefined) {\n        if (!isObject(entry.chains))\n            unsupported(`${field}.chains`);\n        for (const [key, target] of Object.entries(entry.chains)) {\n            chainId(key, `${field}.chains.${key}`);\n            string(object(target, `${field}.chains.${key}`, ['contract']).contract, `${field}.chains.${key}.contract`);\n        }\n    }\n}\n/**\n * A typed EVM account (`account.evm`) or recipient. Only the account carries a\n * signature mode; a recipient never signs.\n */\nfunction evmAccount(value, field, options) {\n    if (!isObject(value))\n        unsupported(field);\n    const signature = options.signatureMode ? ['signatureMode'] : [];\n    const entry = value.type === undefined && !options.signatureMode\n        ? object(value, field, ['address'])\n        : value.type === 'eoa'\n            ? object(value, field, ['type', 'address', 'delegations', ...signature])\n            : value.type === 'erc7579'\n                ? object(value, field, [\n                    'type',\n                    'address',\n                    'initData',\n                    'delegations',\n                    'simulation',\n                    ...signature,\n                ])\n                : unsupported(`${field}.type`);\n    string(entry.address, `${field}.address`);\n    if (entry.signatureMode !== undefined &&\n        typeof entry.signatureMode !== 'number' &&\n        typeof entry.signatureMode !== 'string') {\n        unsupported(`${field}.signatureMode`);\n    }\n    if (entry.initData !== undefined) {\n        const init = object(entry.initData, `${field}.initData`, ['setupOps']);\n        for (const [index, op] of array(init.setupOps, `${field}.initData.setupOps`).entries()) {\n            const setup = object(op, `${field}.initData.setupOps.${index}`, [\n                'to',\n                'data',\n            ]);\n            string(setup.to, `${field}.initData.setupOps.${index}.to`);\n            string(setup.data, `${field}.initData.setupOps.${index}.data`);\n        }\n    }\n    if (entry.delegations !== undefined) {\n        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        optionalString(simulation.mockSignature, `${field}.simulation.mockSignature`);\n        if (simulation.mockSignaturesByChain !== undefined) {\n            const byChain = simulation.mockSignaturesByChain;\n            if (!isObject(byChain)) {\n                unsupported(`${field}.simulation.mockSignaturesByChain`);\n            }\n            for (const [key, signature] of Object.entries(byChain)) {\n                const at = `${field}.simulation.mockSignaturesByChain.${key}`;\n                chainId(key, at);\n                string(signature, at);\n            }\n        }\n    }\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 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    optionalString(entry.swigAccount, `${field}.swigAccount`);\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        optionalString(init.id, `${field}.initData.id`);\n    }\n}\nfunction swigAuthorityChange(value, field) {\n    if (!isObject(value))\n        unsupported(field);\n    const change = value.action === 'add'\n        ? object(value, field, ['action', 'key', 'permission'])\n        : value.action === 'remove'\n            ? object(value, field, ['action', 'key'])\n            : unsupported(`${field}.action`);\n    const key = object(change.key, `${field}.key`, ['kind', 'publicKey']);\n    if (key.kind !== 'secp256r1' && key.kind !== 'secp256k1') {\n        unsupported(`${field}.key.kind`);\n    }\n    string(key.publicKey, `${field}.key.publicKey`);\n    if (change.action === 'add' &&\n        change.permission !== 'all' &&\n        change.permission !== 'allButManageAuthority' &&\n        change.permission !== 'manageAuthority') {\n        unsupported(`${field}.permission`);\n    }\n}\nfunction solanaInstructions(value, field) {\n    for (const [index, item] of array(value, field).entries()) {\n        const at = `${field}.${index}`;\n        const instruction = object(item, at, ['programId', 'accounts', 'data']);\n        string(instruction.programId, `${at}.programId`);\n        string(instruction.data, `${at}.data`);\n        for (const [position, meta] of array(instruction.accounts, `${at}.accounts`).entries()) {\n            const where = `${at}.accounts.${position}`;\n            const entry = object(meta, where, ['pubkey', 'isSigner', 'isWritable']);\n            string(entry.pubkey, `${where}.pubkey`);\n            if (typeof entry.isSigner !== 'boolean')\n                unsupported(`${where}.isSigner`);\n            if (typeof entry.isWritable !== 'boolean') {\n                unsupported(`${where}.isWritable`);\n            }\n        }\n    }\n}\nfunction bareRecipient(value, field) {\n    string(object(value, field, ['address']).address, `${field}.address`);\n}\nconst DESTINATION_VMS = ['evm', 'svm', 'tvm', 'stellar', 'hypercore'];\nfunction destination(value) {\n    if (!isObject(value))\n        unsupported('destination');\n    const vm = value.vm;\n    if (typeof vm !== 'string' || !DESTINATION_VMS.includes(vm)) {\n        unsupported('destination.vm');\n    }\n    const executes = vm === 'evm' || vm === 'svm' || vm === 'hypercore';\n    const entry = object(value, 'destination', [\n        'vm',\n        'chainId',\n        'token',\n        'amount',\n        'recipient',\n        ...(executes ? ['execution'] : []),\n    ]);\n    chainId(entry.chainId, 'destination.chainId');\n    optionalString(entry.token, 'destination.token');\n    optionalString(entry.amount, 'destination.amount');\n    if (entry.amount !== undefined && entry.token === undefined) {\n        unsupported('destination.amount');\n    }\n    if (vm === 'evm' || vm === 'hypercore') {\n        if (entry.recipient !== undefined) {\n            evmAccount(entry.recipient, 'destination.recipient', {\n                signatureMode: false,\n            });\n        }\n    }\n    else if (vm === 'svm') {\n        if (entry.recipient !== undefined) {\n            bareRecipient(entry.recipient, 'destination.recipient');\n        }\n    }\n    else {\n        // tvm/stellar require a recipient.\n        bareRecipient(entry.recipient, 'destination.recipient');\n    }\n    if (entry.execution === undefined)\n        return;\n    if (vm === 'evm') {\n        evmExecution(entry.execution, 'destination.execution');\n    }\n    else if (vm === 'svm') {\n        if (isObject(entry.execution) && 'authority' in entry.execution) {\n            const execution = object(entry.execution, 'destination.execution', [\n                'authority',\n            ]);\n            swigAuthorityChange(execution.authority, 'destination.execution.authority');\n        }\n        else {\n            const execution = object(entry.execution, 'destination.execution', [\n                'instructions',\n                'addressLookupTables',\n            ]);\n            solanaInstructions(execution.instructions, 'destination.execution.instructions');\n            if (execution.addressLookupTables !== undefined) {\n                for (const [index, table] of array(execution.addressLookupTables, 'destination.execution.addressLookupTables').entries()) {\n                    string(table, `destination.execution.addressLookupTables.${index}`);\n                }\n            }\n        }\n    }\n    else {\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            if (actions.length !== 1 || !isObject(actions[0])) {\n                unsupported('destination.execution.actions');\n            }\n        }\n        if (execution.settlement !== undefined) {\n            evmExecution(execution.settlement, 'destination.execution.settlement');\n        }\n    }\n}\nfunction source(value) {\n    const entry = object(value, 'source', [\n        'vm',\n        'chainId',\n        'token',\n        'maxAmount',\n        'auxiliaryFunds',\n        'execution',\n    ]);\n    if (entry.vm !== 'evm' && entry.vm !== 'svm')\n        unsupported('source.vm');\n    chainId(entry.chainId, 'source.chainId');\n    string(entry.token, 'source.token');\n    optionalString(entry.maxAmount, 'source.maxAmount');\n    optionalString(entry.auxiliaryFunds, 'source.auxiliaryFunds');\n    if (entry.execution !== undefined) {\n        if (entry.vm !== 'evm')\n            unsupported('source.execution');\n        calls(object(entry.execution, 'source.execution', ['calls']).calls, 'source.execution.calls');\n    }\n}\nfunction venueFilter(value, field) {\n    const filter = object(value, field, ['include', 'exclude']);\n    const keys = Object.keys(filter);\n    if (keys.length !== 1)\n        unsupported(field);\n    for (const [index, venue] of array(filter[keys[0]], `${field}.${keys[0]}`).entries()) {\n        string(venue, `${field}.${keys[0]}.${index}`);\n    }\n}\nfunction options(value) {\n    const entry = object(value, 'options', [\n        'appFees',\n        'protocolFees',\n        'customDeadline',\n        'settlementLayers',\n        'quoters',\n        'sponsorship',\n    ]);\n    for (const key of ['appFees', 'protocolFees']) {\n        if (entry[key] === undefined)\n            continue;\n        const fee = object(entry[key], `options.${key}`, ['feeBps']);\n        if (typeof fee.feeBps !== 'number')\n            unsupported(`options.${key}.feeBps`);\n    }\n    if (entry.customDeadline !== undefined &&\n        typeof entry.customDeadline !== 'number') {\n        unsupported('options.customDeadline');\n    }\n    for (const key of ['settlementLayers', 'quoters']) {\n        if (entry[key] !== undefined)\n            venueFilter(entry[key], `options.${key}`);\n    }\n    if (entry.sponsorship !== undefined) {\n        const sponsorship = object(entry.sponsorship, 'options.sponsorship', [\n            'gas',\n            'bridgeFees',\n            'swapFees',\n            'protocolFees',\n        ]);\n        for (const [key, category] of Object.entries(sponsorship)) {\n            if (typeof category !== 'boolean') {\n                unsupported(`options.sponsorship.${key}`);\n            }\n        }\n    }\n}\nfunction account(value) {\n    const entry = object(value, 'account', ['evm', 'svm']);\n    if (entry.evm === undefined && entry.svm === undefined)\n        unsupported('account');\n    if (entry.evm !== undefined) {\n        evmAccount(entry.evm, 'account.evm', { signatureMode: true });\n    }\n    if (entry.svm !== undefined)\n        swigAccount(entry.svm, 'account.svm');\n}\n/**\n * The approval input of a singular Caucasus request, unvalidated: the body\n * verbatim, versioned, with `source` omitted when absent and `options`\n * defaulted to `{}`. {@link assertSponsorshipApproval} validates it against the\n * contract before any grant is requested.\n */\nexport function toSponsorshipApprovalInput(body) {\n    const root = toJson(body);\n    return {\n        contractVersion: SPONSORSHIP_APPROVAL_CONTRACT,\n        account: root.account,\n        ...(root.source === undefined ? {} : { source: root.source }),\n        destination: root.destination,\n        options: root.options ?? {},\n    };\n}\n/**\n * Derives the sponsorship approval input from a singular Caucasus\n * `POST /quotes` body, validating every field against the contract.\n *\n * Throws {@link UnsupportedSponsorshipApprovalError} on any field outside the\n * contract's allowlist, including a legacy-shaped body.\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', 'source', 'destination', 'options']);\n    account(root.account);\n    if (root.source !== undefined)\n        source(root.source);\n    destination(root.destination);\n    if (root.options !== undefined)\n        options(root.options);\n    return toSponsorshipApprovalInput(root);\n}\n/** Whether a sponsorship approval input asks for any sponsorship. */\nexport function isSponsoredIntentInput(input) {\n    return input.options.sponsorship !== undefined;\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(serializeBigInts(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","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 { chainIdFromReference, chainVm, formatCaip2 } from '../../chains/caip2.js';\nimport { normalizeTokenAddress } from '../../chains/tokens.js';\nimport { toSponsorshipApprovalInput } from '../../clients/orchestrator/sponsorship-approval.js';\nimport { toWireEvmAccount, toWireRecipient, } from './account.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 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    const source = buildSource(transaction, input.sourceCalls.map(toExecution), input.providedFunds);\n    const request = {\n        account: {\n            evm: toWireEvmAccount(input.account, {\n                signatureMode,\n                ...(input.mockSignatures\n                    ? {\n                        mockSignaturesByChain: mapMockSignatures(input.mockSignatures),\n                    }\n                    : {}),\n            }),\n        },\n        ...(source ? { source } : {}),\n        destination: buildDestination({\n            vm,\n            chainId: formatCaip2(destinationChainId),\n            transaction,\n            ...(transaction.token === undefined\n                ? {}\n                : {\n                    token: normalizeTokenAddress(transaction.token, destinationChainId, nonEvm),\n                }),\n            executions,\n        }),\n        ...(Object.keys(options).length > 0 ? { options } : {}),\n    };\n    return { request, intentInput: toSponsorshipApprovalInput(request) };\n}\nfunction buildSource(transaction, calls, providedFunds) {\n    const source = transaction.source;\n    if (!source) {\n        // Checked by the facade already; a request that loses its source calls here\n        // would quote an execution the caller did not ask for.\n        if (calls.length > 0) {\n            throw new Error('Source calls need a source chain to run on');\n        }\n        return undefined;\n    }\n    const auxiliaryFunds = (source.auxiliaryFunds ?? 0n) + providedFunds;\n    return {\n        vm: 'evm',\n        chainId: formatCaip2(source.chain.id),\n        token: normalizeTokenAddress(source.token, source.chain.id, false),\n        ...(source.maxAmount === undefined ? {} : { maxAmount: source.maxAmount }),\n        ...(auxiliaryFunds > 0n ? { auxiliaryFunds } : {}),\n        ...(calls.length > 0 ? { execution: { calls } } : {}),\n    };\n}\nfunction buildDestination(input) {\n    const { transaction, chainId } = input;\n    const delivery = {\n        ...(input.token === undefined ? {} : { token: input.token }),\n        ...(transaction.amount === undefined ? {} : { amount: transaction.amount }),\n    };\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                ...delivery,\n                ...(recipient ? { recipient } : {}),\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                ...delivery,\n                ...(recipient ? { recipient: { address: recipient.address } } : {}),\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                ...delivery,\n                recipient: { address: recipient.address },\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                ...delivery,\n                ...(recipient ? { recipient } : {}),\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    // Copied category by category, keeping an explicit `false` distinct from an\n    // 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}\n","/** Narrows the explicit source and global route filters before the quote is bound. */\nexport function constrainSessionIntent(intent, account) {\n    if (intent.signers?.kind !== 'smart-session')\n        return intent;\n    const chainIds = new Set();\n    if (intent.source)\n        chainIds.add(intent.source.chain.id);\n    if (intent.destination.kind === 'evm' &&\n        (!intent.recipient ||\n            intent.recipient.address.toLowerCase() === account.toLowerCase()))\n        chainIds.add(intent.destination.id);\n    const sessions = Object.entries(intent.signers.byChain)\n        .filter(([id]) => chainIds.has(Number(id)))\n        .map(([, selected]) => selected.session);\n    let source = intent.source;\n    if (source) {\n        const origin = intent.signers.byChain[source.chain.id]?.session;\n        if (origin?.permit2Sources?.length) {\n            const sameChain = intent.destination.kind === 'evm' &&\n                intent.destination.id === source.chain.id;\n            if (sameChain && !origin.swap)\n                throw new Error('A scoped Permit2 session without a swap scope settles cross-chain intents only');\n            const legs = sameChain && origin.swap\n                ? (origin.swap.sell.tokens ??\n                    (origin.swap.sell.token ? [origin.swap.sell.token] : [])).map((token) => ({\n                    chain: origin.chain,\n                    token,\n                    maxAmount: origin.swap.sell.maxTotal,\n                }))\n                : origin.permit2Sources;\n            const leg = legs.find((leg) => leg.chain.id === source.chain.id &&\n                leg.token.toLowerCase() === source.token.toLowerCase());\n            if (!leg)\n                throw new Error('The explicit source token is outside the session funding scope');\n            if (leg.maxAmount !== undefined)\n                source = {\n                    ...source,\n                    maxAmount: source.maxAmount === undefined || source.maxAmount > leg.maxAmount\n                        ? leg.maxAmount\n                        : source.maxAmount,\n                };\n        }\n    }\n    const settlementLayers = settlementPin(sessions, intent.options?.settlementLayers);\n    const quoters = quoterPin(sessions, intent.options?.quoters);\n    return {\n        ...intent,\n        ...(source ? { source } : {}),\n        options: {\n            ...intent.options,\n            ...(settlementLayers ? { settlementLayers } : {}),\n            ...(quoters ? { quoters } : {}),\n        },\n    };\n}\nfunction settlementPin(sessions, explicit) {\n    const includes = [];\n    const excluded = new Set();\n    for (const session of sessions) {\n        const named = session.settlementLayers ?? [];\n        if (named.some((layer) => ['SAME_CHAIN', 'ECO', 'ACROSS'].includes(layer)) &&\n            session.access?.kind !== 'scoped') {\n            if (!named.includes('ACROSS'))\n                excluded.add('ACROSS');\n            continue;\n        }\n        const layers = named.flatMap((layer) => layer === 'SAME_CHAIN_IE' || layer === 'SAME_CHAIN'\n            ? []\n            : [layer === 'ECO_IE' ? 'ECO' : layer]);\n        if (layers.length)\n            includes.push(new Set(layers));\n    }\n    if (!includes.length) {\n        if (!excluded.size)\n            return explicit;\n        if (!explicit || 'exclude' in explicit)\n            return {\n                exclude: [...new Set([...(explicit?.exclude ?? []), ...excluded])],\n            };\n        const include = explicit.include.filter((layer) => !excluded.has(layer));\n        if (!include.length)\n            throw new Error('settlementLayers: no settlement layer is left to settle the intent');\n        return { include };\n    }\n    const derived = [...includes[0]].filter((layer) => !excluded.has(layer) && includes.every((layers) => layers.has(layer)));\n    const include = !explicit\n        ? derived\n        : 'include' in explicit\n            ? derived.filter((layer) => explicit.include.includes(layer))\n            : derived.filter((layer) => !explicit.exclude.includes(layer));\n    if (!include.length)\n        throw new Error('settlementLayers: no settlement layer is left to settle the intent');\n    return { include };\n}\nfunction quoterPin(sessions, explicit) {\n    let pinned;\n    for (const session of sessions) {\n        const via = session.swap?.via;\n        if (!via?.length)\n            continue;\n        const venues = new Set();\n        let unconstrained = false;\n        for (const venue of via) {\n            if (venue.id === '0x')\n                venues.add('0x');\n            else if (venue.id === 'fynd')\n                venues.add('fynd');\n            else if (venue.id === 'rhinestone' &&\n                'route' in venue &&\n                venue.route === 'zeroEx')\n                venues.add('0x');\n            else if (venue.id === 'rhinestone' &&\n                'route' in venue &&\n                venue.route === 'fynd')\n                venues.add('fynd');\n            else\n                unconstrained = true;\n        }\n        if (unconstrained)\n            continue;\n        pinned = pinned\n            ? new Set([...pinned].filter((quoter) => venues.has(quoter)))\n            : venues;\n    }\n    if (!pinned)\n        return explicit;\n    const include = !explicit\n        ? [...pinned]\n        : 'include' in explicit\n            ? explicit.include.filter((quoter) => pinned.has(quoter))\n            : [...pinned].filter((quoter) => !explicit.exclude.includes(quoter));\n    return { include };\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';\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        // Claim policies are enforced from the erc1271 list, already in\n        // `erc7739Policies`; the manager skips this lockTag surface under a zero lock tag.\n        claimPolicies: [],\n    };\n}\nexport function getPermissionId(session) {\n    return session.permissionId;\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, encodeFunctionData, toFunctionSelector, } from 'viem';\n// OneTimeUseIdPolicy: a session pins an id it invents and each settlement burns\n// it through a pre-claim execution, so a session settles at most once per chain.\nexport const oneTimeUseIdPolicyAbi = [\n    {\n        type: 'function',\n        name: 'consume',\n        stateMutability: 'nonpayable',\n        inputs: [{ name: 'id', type: 'uint256' }],\n        outputs: [],\n    },\n    {\n        type: 'function',\n        name: 'consumeFor',\n        stateMutability: 'nonpayable',\n        inputs: [\n            { name: 'id', type: 'uint256' },\n            { name: 'witness', type: 'uint256' },\n        ],\n        outputs: [],\n    },\n];\n// source: smart-sessions-v2 src/policies/onetime/interfaces/IOneTimeUseIdPolicy.sol\nexport const CONSUME_SELECTOR = toFunctionSelector('function consume(uint256)');\nexport const CONSUME_FOR_SELECTOR = toFunctionSelector('function consumeFor(uint256,uint256)');\n// The id must be a non-zero uint256 — the policy rejects zero (\"not configured\").\nfunction assertValidOneTimeUseId(id) {\n    if (id <= 0n || id > (1n << 256n) - 1n) {\n        throw new Error('oneTimeUse.id must be a non-zero uint256');\n    }\n}\n// The policy's initData: abi.encode(id, deadline). The deadline is in unix\n// SECONDS; zero means never expires. Any other layout reverts at session enable.\nexport function encodeOneTimeUseIdInitData(id, deadline = 0n) {\n    assertValidOneTimeUseId(id);\n    return encodeAbiParameters([{ type: 'uint256' }, { type: 'uint256' }], [id, deadline]);\n}\n// The erc1271 policy entry to add to a session's erc7739Policies.erc1271Policies.\nexport function oneTimeUseIdErc1271Policy(params) {\n    return {\n        policy: params.policy,\n        initData: encodeOneTimeUseIdInitData(params.id, params.deadline),\n    };\n}\n// The burn op for the intent's `preClaimExecutions`: `consume(id)` on the executor\n// route, or `consumeFor(id, 0)` on Permit2, whose placeholder witness the\n// orchestrator replaces with the order nonce before the mandate is signed.\nexport function buildOneTimeUseBurnOp(params) {\n    const { policy, id, route } = params;\n    // Reject id=0 here too (not just at initData encoding) so a caller can't emit a\n    // burn op whose id doesn't match a validly-pinned session.\n    assertValidOneTimeUseId(id);\n    const data = route === 'permit2'\n        ? encodeFunctionData({\n            abi: oneTimeUseIdPolicyAbi,\n            functionName: 'consumeFor',\n            args: [id, 0n],\n        })\n        : encodeFunctionData({\n            abi: oneTimeUseIdPolicyAbi,\n            functionName: 'consume',\n            args: [id],\n        });\n    return { to: policy, value: 0n, data };\n}\n","import { isAddressEqual } from 'viem';\nimport { PERMIT2_CLAIM_POLICY_ADDRESS } from '../../policies/claim/permit2.js';\nimport { refusal } from '../refusals.js';\nexport const SPENDING_LIMITS_POLICY_ADDRESS = '0x000000000033212E272655D8a22402Db819477A6';\n/**\n * The TimeFramePolicy every window installs by default: it holds its window on\n * actions and ERC-1271 checks. Same address on every chain.\n */\nexport const TIME_FRAME_POLICY_ADDRESS = '0xEAAb79CA50a37514E3Bd2538Aa80ee8cB0eCe9d3';\n/** The previous TimeFramePolicy, which holds its window on ERC-1271 checks only. */\nexport const PREVIOUS_TIME_FRAME_POLICY_ADDRESS = '0x0000000000D30f611fA3bf652ac6879428586930';\nconst TIME_FRAME_POLICY_CHAINS = [\n    1, 10, 56, 100, 130, 137, 143, 146, 196, 480, 999, 1868, 2020, 4663, 5042,\n    8453, 9745, 9746, 42161, 57073, 84532, 421614, 747474, 11155420,\n];\n/** Whether TIME_FRAME_POLICY_ADDRESS is deployed on a chain. */\nexport function timeFramePolicyDeployed(chainId) {\n    return TIME_FRAME_POLICY_CHAINS.includes(chainId);\n}\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';\n// The constructor takes the IntentExecutor, so each environment has its own.\nexport const ONE_TIME_USE_ID_POLICY_ADDRESS = '0x630CEbCf54C7471154CF659088CC4197872Cf5FD';\nexport const ONE_TIME_USE_ID_POLICY_ADDRESS_DEV = '0x86F7cB4E25626d6a07cfED305c38816F30d07224';\n// A chain absent here gets no default, so a session never points at an empty\n// address.\nconst ONE_TIME_USE_ID_POLICY_CHAINS_DEV = [\n    1, 10, 56, 100, 130, 137, 143, 146, 196, 480, 999, 1868, 2020, 4663, 5042,\n    8453, 9745, 42161, 43114, 57073, 84532, 421614, 747474,\n];\nconst ONE_TIME_USE_ID_POLICY_CHAINS = [\n    ...ONE_TIME_USE_ID_POLICY_CHAINS_DEV,\n    9746,\n    11155111,\n    11155420,\n];\n// Accepts a claim signature only when Permit2 presents it. The constructor\n// takes only Permit2, so both environments share one address.\nexport const PERMIT2_SENDER_POLICY_ADDRESS = '0xb590a7409de9e9f2A42B56CB62C1f7bA5ea0f959';\nconst PERMIT2_SENDER_POLICY_CHAINS = [\n    1, 10, 56, 100, 130, 137, 143, 146, 196, 480, 999, 1868, 2020, 4663, 5042,\n    8453, 9745, 9746, 42161, 57073, 84532, 421614, 747474, 11155111, 11155420,\n];\n/** The deployed Permit2SenderPolicy on a chain, or undefined where there is none. */\nexport function defaultPermit2SenderPolicy(chainId) {\n    return PERMIT2_SENDER_POLICY_CHAINS.includes(chainId)\n        ? PERMIT2_SENDER_POLICY_ADDRESS\n        : undefined;\n}\n/** The deployed OneTimeUseIdPolicy on a chain, or undefined where there is none. */\nexport function defaultOneTimeUseIdPolicy(chainId, environment) {\n    if (environment === 'development') {\n        return ONE_TIME_USE_ID_POLICY_CHAINS_DEV.includes(chainId)\n            ? ONE_TIME_USE_ID_POLICY_ADDRESS_DEV\n            : undefined;\n    }\n    return ONE_TIME_USE_ID_POLICY_CHAINS.includes(chainId)\n        ? ONE_TIME_USE_ID_POLICY_ADDRESS\n        : undefined;\n}\n/** The refusal for a chain with no OneTimeUseIdPolicy to default to. */\nexport function oneTimeUseIdPolicyMissing(chainId, environment) {\n    return (`oneTimeUse: no OneTimeUseIdPolicy is deployed on chain ${chainId}` +\n        (environment === 'development' ? ' (development contracts)' : '') +\n        '; pass its address as policyAddresses.oneTimeUseId');\n}\n/**\n * Throws when `policy` is a default deployment with no code on `chainId`. A\n * session resolves its default on its own chain, but an intent can use it on\n * others. Any other address is the caller's to vouch for.\n */\nexport function assertOneTimeUseIdPolicyDeployed(policy, chainId) {\n    const environment = isAddressEqual(policy, ONE_TIME_USE_ID_POLICY_ADDRESS)\n        ? 'production'\n        : isAddressEqual(policy, ONE_TIME_USE_ID_POLICY_ADDRESS_DEV)\n            ? 'development'\n            : undefined;\n    if (environment && !defaultOneTimeUseIdPolicy(chainId, environment)) {\n        throw new Error(oneTimeUseIdPolicyMissing(chainId, environment));\n    }\n}\n// CREATE2 deployments of the canonical UniversalActionPolicy bytecode, at the\n// same addresses on every chain in UNIVERSAL_ACTION_POLICY_COPY_CHAINS.\nexport const UNIVERSAL_ACTION_POLICY_COPIES = Object.freeze([\n    '0x68744D25604872d2F81FAa864963353F3ee9b4d2',\n    '0x8a026acb4DF6EFbc9BD4664D1E8750D470E7dD9F',\n    '0x6EB915A22F2015A776eec56F11EF96cda1EDCC54',\n]);\n// Static so the encoding never depends on an RPC read.\nexport const UNIVERSAL_ACTION_POLICY_COPY_CHAINS = new Set([\n    1, 10, 56, 100, 130, 137, 143, 146, 196, 480, 999, 1868, 2020, 4663, 5042,\n    8453, 9745, 9746, 42161, 57073, 84532, 421614, 747474, 11155111, 11155420,\n]);\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, deployment) {\n    const oneTimeUseId = overrides?.oneTimeUseId ??\n        (deployment &&\n            defaultOneTimeUseIdPolicy(deployment.chainId, deployment.environment));\n    const resolved = {\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        ...(oneTimeUseId ? { oneTimeUseId } : {}),\n    };\n    const copies = overrides?.universalActionCopies ?? [];\n    if (!copies.length)\n        return resolved;\n    // A copy receives UniversalActionPolicy initData, so any other policy there\n    // would install the rules as something else.\n    const others = new Map();\n    for (const [name, address] of [\n        ...Object.entries(DEFAULT_POLICY_ADDRESSES),\n        ...Object.entries(resolved),\n        ['intent-execution', INTENT_EXECUTION_POLICY_ADDRESS],\n        ['intent-execution (dev)', INTENT_EXECUTION_POLICY_ADDRESS_DEV],\n        ['Permit2 claim', PERMIT2_CLAIM_POLICY_ADDRESS],\n    ]) {\n        if (name !== 'universalAction')\n            others.set(address.toLowerCase(), name);\n    }\n    const seen = new Set([resolved.universalAction.toLowerCase()]);\n    for (const copy of copies) {\n        const other = others.get(copy.toLowerCase());\n        if (other) {\n            throw refusal('UNIVERSAL_ACTION_COPY_INVALID', `universalActionCopies: ${copy} is the ${other} policy, not a UniversalActionPolicy deployment`);\n        }\n        if (seen.has(copy.toLowerCase())) {\n            throw refusal('UNIVERSAL_ACTION_COPY_INVALID', `universalActionCopies must be distinct from universalAction and from each other; ${copy} repeats`);\n        }\n        seen.add(copy.toLowerCase());\n    }\n    return { ...resolved, universalActionCopies: copies };\n}\n","import { concat, encodeAbiParameters, encodePacked, hashStruct, keccak256, maxUint256, toHex, } from 'viem';\nimport { ANY_ADDRESS, FIELD_ARBITER, FIELD_EXPIRY, FIELD_FILL_EXPIRY, FIELD_ORIGIN_OPS, 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}\n/** The hash of an empty `Op`: a claim that carries no pre-claim call. */\nexport const NO_OPS = '0x0c7bea50822ae8a3846eccbda4961a80e1e08aa92f2bf046be0011514ad2ddf1';\nexport function 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    const originOpsEnabled = !!policy.originOps?.length;\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    const target = message.mandate.target;\n    // Mandate section\n    if (!hasAnyTargetCheck && !originOpsEnabled) {\n        // No mandate-level checks enabled — provide pre-computed mandateHash\n        parts.push(hashMandateStruct(message.mandate));\n    }\n    else if (!hasAnyTargetCheck) {\n        // Mandate checks without target checks: [targetHash:32][targetChain:32]\n        parts.push(hashStruct({\n            primaryType: 'Target',\n            types: PERMIT2_TYPES,\n            data: { ...target, tokenOut: Array.from(target.tokenOut) },\n        }), toHex(target.targetChain, { size: 32 }));\n    }\n    else {\n        // Expanded mandate: target fields + minGas + ops hashes + q\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    }\n    if (hasAnyTargetCheck || originOpsEnabled) {\n        // minGas: uint128 = 16 bytes\n        parts.push(toHex(message.mandate.minGas, { size: 16 }));\n        // originOpsHash and destOpsHash: 32-byte hashes, read in place by the 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 = '0x4F9FAbC867E196Ebb27E7D7FaeD8AF41B2021B0e';\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    if (policy.originOps?.length)\n        setMode(FIELD_ORIGIN_OPS);\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    // OriginOps: [count: 1][chainId: 32][required: 1] each\n    if (policy.originOps?.length) {\n        parts.push(toHex(policy.originOps.length, { size: 1 }));\n        for (const { chainId, required } of policy.originOps) {\n            parts.push(encodePacked(['uint256', 'bool'], [BigInt(chainId), required]));\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","/**\n * Every stable code a `crossChainPermits` refusal carries, with what it means.\n * Codes never change once published; the messages beside them may.\n */\nexport const SESSION_REFUSAL_CODES = {\n    REMOVED_CLAIM_POLICIES_INPUT: 'claimPolicies on a new session definition; use crossChainPermits',\n    VALID_AFTER_EXCEEDS_VALID_UNTIL: 'a validAfter not earlier than validUntil',\n    VALID_AFTER_INVALID: 'a validAfter that is not a Date within uint48 seconds',\n    VALID_UNTIL_NOT_IN_FUTURE: 'a validUntil that is not a future Date',\n    TIME_FRAME_POLICY_UNAVAILABLE: 'an action window on a chain without the TimeFramePolicy',\n    PERMIT2_MAX_AMOUNT_REQUIRES_ONE_TIME_USE: 'maxAmount on a Permit2-layer permit with `fallback` and without oneTimeUse',\n    SETTLEMENT_SCOPED_SALT_V1: \"an IntentExecutor-layer permit with saltMode 'v1'\",\n    MIXED_PERMIT_KINDS: 'IntentExecutor-layer and Permit2-layer permits in one session',\n    MULTIPLE_INTENT_EXECUTOR_PERMITS: 'more than one IntentExecutor-layer permit in one session',\n    PERMIT2_LAYER_WITH_INTENT_EXECUTOR_LAYER: 'a Permit2 layer other than ACROSS, or ACROSS with `fallback`, named beside IntentExecutor layers in one permit',\n    SAME_CHAIN_IE_WITH_OTHER_LAYERS: 'SAME_CHAIN_IE named beside another layer',\n    NO_FROM_ON_CHAIN: \"no `from` leg on the session's chain\",\n    MULTIPLE_MAX_AMOUNTS: 'maxAmount on more than one `from` token per chain',\n    RECIPIENT_ANY_NOT_ALLOWED: \"recipient 'any' without allowRecipientNotAccount\",\n    RECIPIENT_NEEDS_ACCOUNT: 'the recipient defaults to the account, but the definition has no `account`',\n    RECIPIENT_NOT_ACCOUNT: 'a recipient other than the account without allowRecipientNotAccount',\n    MISSING_TO: 'an IntentExecutor-layer permit names no `to` chains',\n    FILL_DEADLINE_ONLY_PERMIT2: \"fillDeadline on a permit naming IntentExecutor layers, or under 'all' where ACROSS cannot settle\",\n    MAX_FEE_BPS_ONLY_ECO_IE: 'maxFeeBps without ECO_IE, or beside ACROSS',\n    MIN_AMOUNT_ON_PERMIT2_LAYER: '`to.minAmount` on a Permit2-layer permit',\n    SAME_CHAIN_IE_TRANSFER_MIN_AMOUNT: '`to.minAmount` on a SAME_CHAIN_IE transfer',\n    MIN_AMOUNT_OUTSIDE_CAP: '`to.minAmount` outside [maxAmount / 2, maxAmount] of a capped `from` leg',\n    MIN_AMOUNT_NOT_ENFORCEABLE: '`to.minAmount` on a layer that cannot enforce it (CCTP)',\n    MIN_AMOUNT_NOT_POSITIVE: 'a `to.minAmount` of zero or less',\n    MIN_AMOUNT_ABOVE_UINT64: 'an OFT or LZ `to.minAmount` above uint64',\n    FLOOR_DECIMALS_MISMATCH: 'an OFT or LZ floor whose `from` and `to` tokens lack served, equal decimals',\n    CONFLICTING_LEG_FLOORS: 'two `to` legs the layer cannot tell apart with different `to.minAmount`',\n    LZ_FLOORED_LEG_NOT_ALONE: 'a floored LZ leg beside another `to` leg on its chain',\n    LZ_FLOOR_ON_CCTP_ROUTE: 'a floored LZ leg on a chain LZ reaches over CCTP',\n    SETTLEMENT_CATALOG_MISSING: \"IntentExecutor layers without the orchestrator's settlement addresses\",\n    LAYER_REQUIRES_ONE_TIME_USE: 'a layer that pays a native fee (OFT, LZ) without oneTimeUse',\n    LAYER_NOT_SERVED: 'the layer does not route on a named chain',\n    MAX_FEE_BPS_ECO_IE_UNAVAILABLE: \"maxFeeBps with settlementLayers 'all' where ECO_IE cannot settle\",\n    NO_LAYER_CAN_SETTLE: \"settlementLayers 'all' where no layer can settle\",\n    MULTIPLE_FEE_PAYING_LAYERS: 'both OFT and LZ, which each pay a native fee',\n    ONE_SOURCE_TOKEN: 'the layer takes exactly one `from` token per chain',\n    TOKEN_NOT_ROUTED: 'a `from` or `to` token the layer does not move',\n    ECO_IE_STABLECOIN_DECIMALS: 'an ECO_IE token priced by maxFeeBps that is not one served USD stablecoin of 6 or 18 decimals',\n    ACCOUNT_REQUIRED: 'the layer needs `account` on the definition',\n    ECO_IE_NEEDS_MAX_AMOUNT_AND_FEE: 'ECO_IE without maxAmount, or without maxFeeBps where a `to` leg has no `to.minAmount`',\n    MAX_FEE_BPS_OUT_OF_RANGE: 'maxFeeBps outside the integers in [0, 10000)',\n    ECO_IE_VALIDITY_TOO_SHORT: 'ECO_IE validUntil under 7 days from now',\n    ECO_IE_FLOOR_NEEDS_EQUAL_CAPS: 'an ECO_IE `to.minAmount` without maxFeeBps across `from` legs with different maxAmount',\n    RECIPIENT_ANY_UNPINNABLE: \"recipient 'any' where the layer must pin a concrete recipient\",\n    ECO_IE_NO_SHARED_PROVER: 'no Eco prover deployed on both chains of a leg',\n    LZ_NO_ROUTE: 'no LZ route from the chain to any `to` chain',\n    NATIVE_SOURCE_UNSUPPORTED: 'a native `from` on SAME_CHAIN_IE or Permit2',\n    SAME_CHAIN_IE_OTHER_CHAIN_LEG: 'a SAME_CHAIN_IE `to` leg on another chain',\n    SAME_CHAIN_IE_TRANSFER_TO_SELF: 'a SAME_CHAIN_IE transfer to the account itself',\n    SAME_CHAIN_IE_ANY_RECIPIENT_NEEDS_MAX_AMOUNT: \"a SAME_CHAIN_IE transfer to 'any' without maxAmount\",\n    SAME_CHAIN_IE_TRANSFER_OR_SINGLE_SWAP: 'SAME_CHAIN_IE `to` legs that are neither a transfer nor one swap',\n    SAME_CHAIN_IE_SWAP_NEEDS_MIN_AMOUNT: 'a SAME_CHAIN_IE swap without a positive `to.minAmount`',\n    SAME_CHAIN_IE_SWAP_NEEDS_MAX_AMOUNT: 'a SAME_CHAIN_IE swap without maxAmount',\n    ALLOW_FEES_CATALOG_MISSING: \"allowFees without the orchestrator's settlement addresses\",\n    FEES_NOT_SERVED: 'allowFees on a chain with no served fee addresses',\n    ALLOW_FEES_NON_STABLECOIN: 'allowFees with a `from` token that is not a served USD stablecoin with known decimals',\n    ALLOW_FEES_MIXED_DECIMALS: 'allowFees with `from` tokens of different decimals on one chain',\n    ALLOW_FEES_ONLY_INTENT_EXECUTOR: 'retired: allowFees applies to Permit2 too',\n    SIGNING_WITH_INTENT_EXECUTOR_PERMIT: 'an IntentExecutor-layer permit with `signing` enabled',\n    RESTRICTED_WITH_PERMIT2_GRANTS: 'a restricted session holding claimPolicies',\n    PERMIT2_ROUTE_NEEDS_FROM: \"a Permit2-layer permit with no `from` on the session's chain, without `fallback` or with allowFees\",\n    RETIRED_PERMIT2_LAYER: 'a permit naming the Permit2 ECO arbiter',\n    PERMIT2_APPROVE_CONFLICT: 'a declared approve on a Permit2 `from` token',\n    FALLBACK_NOT_APPLICABLE: '`fallback` without a Permit2-layer permit, or with restrictToActions or swap',\n    PERMIT2_ROUTE_NEEDS_BOUND: \"a Permit2-layer permit without oneTimeUse, preClaimOps: 'none' or `fallback`, on a chain without Permit2SenderPolicy\",\n    PERMIT2_ROUTE_ACROSS_ONLY: 'a Permit2-layer permit naming a layer other than ACROSS, without `fallback`',\n    PRE_CLAIM_OPS_NOT_APPLICABLE: \"preClaimOps: 'none' with oneTimeUse, allowFees or a maxAmount on the session's chain, or on a permit that does not settle through ACROSS\",\n    NATIVE_DESTINATION_UNSUPPORTED: 'a native `to` token on a Permit2-layer permit, without `fallback`',\n    WRAPPED_NATIVE_ZERO_CAP: 'a wrapped native `from` leg with maxAmount 0',\n    WRAPPED_NATIVE_TOKEN_UNSERVED: \"the orchestrator's /chains serves no wrapped-native token for the chain\",\n    CLAIM_POLICIES_SIGNING_MODE: \"a scoped or disabled `signing` mode beside claim policies, including a Permit2-layer permit's\",\n    CLAIM_POLICIES_SIGNING_WINDOW_CLOSED: 'a `signing.validUntil` that is not in the future beside claim policies',\n    DUPLICATE_ERC1271_POLICY: 'one ERC-1271 policy installed twice, e.g. by two Permit2-layer permits',\n    UNIVERSAL_ACTION_COPY_INVALID: 'a universalActionCopies entry that is another policy or repeats',\n    UNIVERSAL_ACTION_POLICY_NO_CODE: 'universalAction has no code on the chain, so its copies cannot be checked',\n    UNIVERSAL_ACTION_COPY_CODE_MISMATCH: 'a universalActionCopies entry without the code of universalAction',\n    SESSION_REFUSED: 'the session is refused for a reason with no code of its own; see message',\n};\n/** Every stable code a session warning carries, with what it means. */\nexport const SESSION_WARNING_CODES = {\n    FALLBACK_RECIPIENT_PIN_ACROSS_ONLY: 'a recipient pin on a `fallback` session, which holds only for intents settled by ACROSS',\n    UNCAPPED_ACROSS_ROUTE: \"ACROSS beside IntentExecutor layers, or kept by `all`, with a `from` leg on the chain that has no maxAmount, or a permit naming only ACROSS with such a leg beside a capped one: nothing, or only the chain's maxAmount read in that token's raw units, caps what that route moves for it\",\n    ACTION_WINDOW_SHARED_PERMISSION_ID: 'an action window on a session whose permissionId any other zero-salt session of the same owners shares',\n};\n/** A plain `Error` carrying a refusal code; the class stays `Error`. */\nexport function refusal(code, message, details = {}) {\n    return Object.assign(new Error(message), { code, ...details });\n}\n/** A refuser that throws, or that records into `collect` with `context` added. */\nexport function refuser(collect, context = {}) {\n    return (error, extra) => {\n        if (collect === undefined)\n            throw error;\n        collect(error, { ...context, ...extra });\n    };\n}\n/** `run`'s result, or `undefined` once a dry run has recorded its refusal. */\nexport function recover(refuse, run) {\n    try {\n        return run();\n    }\n    catch (error) {\n        if (error instanceof RefusalCollectionHalted)\n            throw error;\n        refuse(error);\n        return undefined;\n    }\n}\n/** Ends a dry run whose next stage would read data a refusal removed. */\nexport class RefusalCollectionHalted extends Error {\n}\n/** Whether `error` carries one of the published refusal codes. */\nexport function isCodedRefusal(error) {\n    const code = error?.code;\n    return typeof code === 'string' && Object.hasOwn(SESSION_REFUSAL_CODES, code);\n}\n/** A dry run's record: each refusal once, in the order they are met. */\nexport function refusalLog() {\n    const refusals = [];\n    const seen = new Set();\n    // The v1 salt resolves the definition a second time and meets the same refusals.\n    const collect = (error, context = {}) => {\n        const entry = toRefusal(error, context);\n        const key = JSON.stringify(entry);\n        if (seen.has(key))\n            return;\n        seen.add(key);\n        refusals.push(entry);\n    };\n    return { refusals, collect };\n}\n/** `run`'s result and every refusal it meets; no result once one is met. */\nexport function collectRefusals(run, log = refusalLog()) {\n    try {\n        const result = run(log.collect);\n        return log.refusals.length\n            ? { refusals: log.refusals }\n            : { refusals: log.refusals, result };\n    }\n    catch (error) {\n        if (!(error instanceof RefusalCollectionHalted))\n            log.collect(error);\n        return { refusals: log.refusals };\n    }\n}\nfunction toRefusal(error, context) {\n    const fields = (typeof error === 'object' && error !== null ? error : {});\n    // What the error was raised with wins over where it was caught.\n    const pick = (key) => {\n        const value = fields[key] ?? context[key];\n        return value === undefined ? {} : { [key]: value };\n    };\n    return {\n        code: isCodedRefusal(error) && fields.code !== undefined\n            ? fields.code\n            : 'SESSION_REFUSED',\n        message: error instanceof Error ? error.message : String(error),\n        ...pick('permitIndex'),\n        ...pick('layer'),\n        ...pick('chainId'),\n        ...pick('leg'),\n    };\n}\n","import { encodeAbiParameters, isAddressEqual, keccak256, 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 { CONSUME_FOR_SELECTOR, CONSUME_SELECTOR, oneTimeUseIdErc1271Policy, } from './one-time-use.js';\nimport { DEFAULT_POLICY_ADDRESSES, defaultPermit2SenderPolicy, oneTimeUseIdPolicyMissing, PREVIOUS_TIME_FRAME_POLICY_ADDRESS, resolvePolicyAddresses, timeFramePolicyDeployed, UNIVERSAL_ACTION_POLICY_ADDRESS, UNIVERSAL_ACTION_POLICY_COPIES, UNIVERSAL_ACTION_POLICY_COPY_CHAINS, } from './policies/addresses.js';\nimport { expandCrossChainPermit, livePermit2Layers, resolvePermit2ClaimPolicy, } from './policies/claim.js';\nimport { encodeActionPolicies, encodeSessionPolicy } from './policies/encode.js';\nimport { DEPOSIT_SELECTOR, isNativeToken, permit2FallbackScope, permit2RouteScope, permit2SourceTokens, } from './policies/permit2-approval.js';\nimport { intersectTimeFrames, isEmptyTimeFrame, isWindowTime, permissionWithTimeFrame, permitTimeFrame, timeFrame, unionTimeFrames, withTimeFrame, } from './policies/time-frame.js';\nimport { collectRefusals, RefusalCollectionHalted, recover, refusal, refuser, SESSION_REFUSAL_CODES, } from './refusals.js';\nimport { servedFees } from './settlement/fees.js';\nimport { isSettlementScopedPermit, resolveSettlementScope, } from './settlement/scope.js';\nimport { resolveSessionSigning } from './signing.js';\nimport { swapperAddresses } from './swap/rhinestone.js';\nimport { resolveSwapScope } from './swap/scope.js';\nimport { assertStableFloorIsolated } from './swap/stable-floor.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';\nconst seconds = (date) => BigInt(Math.floor(date.getTime() / 1000));\nfunction isFutureDate(value) {\n    return (value instanceof Date &&\n        isWindowTime(value.getTime()) &&\n        value.getTime() > Date.now());\n}\n/**\n * The permissions and raw actions with each window checked, the swap scope's\n * window, and the windows that hold. A dry run records a refused window and\n * drops it, so it is reported once and the run goes on.\n */\nfunction sessionWindows(definition, refuse) {\n    const windows = [];\n    /** The window, once checked and recorded; undefined when refused. */\n    const holds = (field, validUntil, after) => {\n        const validAfter = after instanceof Date ? after.getTime() : after;\n        const window = timeFrame(validAfter, validUntil?.getTime?.());\n        const code = validAfter !== undefined && !isWindowTime(validAfter)\n            ? 'VALID_AFTER_INVALID'\n            : // 0 or less would read as \"never expires\".\n                validUntil !== undefined && !isFutureDate(validUntil)\n                    ? 'VALID_UNTIL_NOT_IN_FUTURE'\n                    : isEmptyTimeFrame(window)\n                        ? 'VALID_AFTER_EXCEEDS_VALID_UNTIL'\n                        : undefined;\n        if (code) {\n            refuse(refusal(code, `${field}: ${SESSION_REFUSAL_CODES[code]}`));\n            return undefined;\n        }\n        windows.push(window);\n        return window;\n    };\n    const permissions = (definition.permissions ?? []).map((permission) => ({\n        ...permission,\n        functions: Object.fromEntries(Object.entries(permission.functions).map(([name, config]) => {\n            if (!config ||\n                (config.validUntil === undefined && config.validAfter === undefined)) {\n                return [name, config];\n            }\n            const { validUntil, validAfter, ...rest } = config;\n            return [\n                name,\n                holds(`permissions[${permission.address}].${name}`, validUntil, validAfter) === undefined\n                    ? rest\n                    : config,\n            ];\n        })),\n    }));\n    const actions = (definition.actions ?? []).map((action) => action.policies?.some((policy) => policy.type === 'time-frame')\n        ? {\n            ...action,\n            policies: action.policies.filter((policy) => policy.type !== 'time-frame' ||\n                holds(`actions[${action.target}:${action.selector}]`, typeof policy.validUntil === 'number'\n                    ? new Date(policy.validUntil)\n                    : policy.validUntil, policy.validAfter) !== undefined),\n        }\n        : action);\n    const swap = definition.swap;\n    const swapWindow = swap && (swap.validUntil !== undefined || swap.validAfter !== undefined)\n        ? holds('swap', swap.validUntil, swap.validAfter)\n        : undefined;\n    return { permissions, actions, swapWindow, windows };\n}\nfunction usesEns(definition) {\n    return (definition.type === 'ens' ||\n        (definition.type === 'multi-factor' &&\n            definition.validators.some((validator) => validator.type === 'ens')));\n}\nexport function assertSessionDefinitionInput(definition) {\n    if ('claimPolicies' in definition) {\n        throw refusal('REMOVED_CLAIM_POLICIES_INPUT', '`SessionDefinition.claimPolicies` was removed; use `crossChainPermits`. Keep compiled `Session.claimPolicies` when restoring an authorized session, and pass that Session directly to enable/sign methods, not definition resolution.');\n    }\n}\nexport function resolveSessionData(definition, options = {}) {\n    return resolveSession(definition, options).data;\n}\n/**\n * The dry run of `toSession`: every refusal it meets and, when there is none,\n * the `access` and `settlementCoverage` the session gets. Never throws a refusal.\n */\nexport function validateSessionDefinition(definition, options = {}, log) {\n    const { refusals, result } = collectRefusals((collect) => resolveSession(definition, options, collect), log);\n    const warnings = [\n        ...sessionWarnings(definition),\n        ...(result\n            ? uncappedAcrossWarnings(definition, result.settlementLayers)\n            : []),\n        ...(result?.sharedActionWindow\n            ? [\n                {\n                    code: 'ACTION_WINDOW_SHARED_PERMISSION_ID',\n                    message: `an action window on a zeroHash-salted session: it shares its permissionId with any other zero-salt session of the same owners, so the window, like the session's other policies, may not be installed when an intent enables the session; use ${result.access.kind === 'scoped' ? \"saltMode 'strict' or \" : ''}a fresh session key`,\n                },\n            ]\n            : []),\n    ];\n    const warned = warnings.length ? { warnings } : {};\n    if (result === undefined)\n        return { refusals, ...warned };\n    const { access, settlementCoverage } = result;\n    return {\n        refusals,\n        access,\n        ...(settlementCoverage && { settlementCoverage }),\n        ...warned,\n    };\n}\n/**\n * Under `fallback`, the wildcard admits IntentExecutor-layer settlement\n * without reading its recipient, and the claim policy that pins it checks\n * only Permit2 (`ACROSS`) claims.\n */\nfunction sessionWarnings(definition) {\n    if (definition.fallback === undefined)\n        return [];\n    return (definition.crossChainPermits ?? []).flatMap((permit, permitIndex) => !isSettlementScopedPermit(permit) &&\n        (!permit.allowRecipientNotAccount ||\n            [permit.to ?? []]\n                .flat()\n                .some(({ recipient }) => recipient && recipient !== 'any'))\n        ? [\n            {\n                code: 'FALLBACK_RECIPIENT_PIN_ACROSS_ONLY',\n                message: 'crossChainPermits: with `fallback`, the recipient pin holds only for intents settled by ACROSS; use a settlement-scoped permit without `fallback` to pin it on IntentExecutor layers',\n                permitIndex,\n            },\n        ]\n        : []);\n}\n/**\n * The ACROSS claim checks no amount, so a `from` token without its own\n * `maxAmount` is bounded only by the approve cap: under a settlement-scoped\n * permit the chain's one cap, read in that token's raw units, and under a\n * permit naming only ACROSS nothing. That permit warns only beside a capped\n * leg, which suggests a bound it lacks.\n */\nfunction uncappedAcrossWarnings(definition, settlementLayers) {\n    return sessionPermits(definition).flatMap((permit, permitIndex) => {\n        const legs = [permit.from ?? []]\n            .flat()\n            .filter(({ chain }) => chain.id === definition.chain.id);\n        const uncapped = legs.some(({ maxAmount }) => maxAmount === undefined);\n        const capped = legs.some(({ maxAmount }) => maxAmount !== undefined);\n        const scoped = isSettlementScopedPermit(permit);\n        const warns = scoped\n            ? settlementLayers.includes('ACROSS') && uncapped\n            : uncapped &&\n                capped &&\n                (!permit.settlementLayers?.length ||\n                    permit.settlementLayers.includes('ACROSS'));\n        return warns\n            ? [\n                {\n                    code: 'UNCAPPED_ACROSS_ROUTE',\n                    message: `crossChainPermits: the session settles through ACROSS, whose route ${scoped && capped\n                        ? \"bounds a `from` token without its own maxAmount only by the chain's maxAmount, read in that token's raw units\"\n                        : `has no amount cap for a \\`from\\` token without its own maxAmount${capped ? \" (another leg's cap does not bound it)\" : ''}`}; set maxAmount on each \\`from\\` leg to bound it, or leave ACROSS out by naming the other layers`,\n                    permitIndex,\n                },\n            ]\n            : [];\n    });\n}\n/**\n * The session data and the IntentExecutor layers its actions were scoped to.\n * With `collect`, a dry run: independent refusals are recorded, not thrown.\n */\nfunction resolveSession(definition, options, collect) {\n    assertSessionDefinitionInput(definition);\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(sessionPolicyAddresses(definition), {\n        chainId: definition.chain.id,\n        environment,\n    });\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, options.settlement?.[definition.chain.id]?.usdStablecoins)\n        : undefined;\n    const refuse = refuser(collect);\n    const windowed = sessionWindows(definition, refuse);\n    const stableFloor = definition.swap?.stableFloor !== undefined;\n    if (stableFloor && definition.swap) {\n        assertStableFloorIsolated({\n            sellToken: (definition.swap.sell.token ??\n                definition.swap.sell.tokens?.[0]),\n            swapper: swapperAddresses(environment).swapper,\n            userTargets: [\n                ...(definition.permissions ?? []).map((p) => p.address),\n                ...(definition.actions ?? []).map((a) => a.target),\n            ],\n            signingMode: definition.signing?.mode,\n            hasCrossChainGrants: Boolean(definition.crossChainPermits?.length),\n        });\n        if (definition.saltMode === 'v1') {\n            throw new Error(\"swap.stableFloor cannot use saltMode 'v1': it must not share a permissionId with an unfloored session\");\n        }\n    }\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 resolvedPermits = sessionPermits(definition).map((input, permitIndex) => {\n        // As for oneTimeUse.validUntil: 0 or less would read as \"never expires\",\n        // and a past deadline only fails at enable, as an opaque signature error.\n        if (input.validUntil !== undefined && !isFutureDate(input.validUntil)) {\n            refuse(refusal('VALID_UNTIL_NOT_IN_FUTURE', `crossChainPermits[${permitIndex}]: ${SESSION_REFUSAL_CODES.VALID_UNTIL_NOT_IN_FUTURE}`, { permitIndex }));\n        }\n        return resolveCrossChainPermission(input, (error) => refuse(error, { permitIndex }));\n    });\n    // An invalid oneTimeUse.validUntil is left out here and refused below.\n    const otuUntil = definition.oneTimeUse?.validUntil;\n    const onceDeadline = isFutureDate(otuUntil) ? seconds(otuUntil) : undefined;\n    const chainId = definition.chain.id;\n    const permit2Sender = defaultPermit2SenderPolicy(chainId);\n    const fallback = definition.fallback;\n    const scopedPermit = resolvedPermits.find(isSettlementScopedPermit);\n    const scopedLayers = scopedPermit?.settlementLayers;\n    // With `fallback`, a permit naming ACROSS beside IntentExecutor layers stays refused.\n    const across = fallback !== undefined || scopedPermit === undefined\n        ? undefined\n        : scopedLayers === 'all'\n            ? {\n                dropped: acrossDropReason(definition, scopedPermit, permit2Sender, options.wrappedNativeToken),\n            }\n            : scopedLayers?.includes('ACROSS')\n                ? {}\n                : undefined;\n    // A permit naming an IntentExecutor layer compiles to argument-pinned scoped\n    // actions, which only bind with the fallback gone — so it restricts too.\n    const settlementScope = resolveSettlementScope(resolvedPermits, {\n        chainId: definition.chain.id,\n        environment,\n        account: definition.account,\n        oneTimeUse: Boolean(definition.oneTimeUse),\n        ...(options.settlement ? { settlement: options.settlement } : {}),\n        ...(collect ? { collect } : {}),\n        ...(onceDeadline === undefined ? {} : { sessionDeadline: onceDeadline }),\n        ...(across ? { across } : {}),\n    });\n    // ACROSS kept beside IntentExecutor layers settles through this Permit2-layer\n    // part of the same permit; the settlement scope already granted its approve.\n    const acrossPermit = scopedPermit && settlementScope?.settlementLayers.includes('ACROSS')\n        ? acrossPart(scopedPermit, definition.account, chainId)\n        : undefined;\n    const permitIndexOf = (permit) => resolvedPermits.indexOf(permit === acrossPermit && scopedPermit ? scopedPermit : permit);\n    // An ERC-1271 signing surface would let the key sign a Permit2 transfer that\n    // none of the calldata pins ever see.\n    if (settlementScope !== undefined &&\n        definition.signing !== undefined &&\n        definition.signing.mode !== 'disabled') {\n        refuse(refusal('SIGNING_WITH_INTENT_EXECUTOR_PERMIT', 'crossChainPermits: an IntentExecutor-layer permit cannot enable `signing`'));\n    }\n    if (settlementScope !== undefined && definition.saltMode === 'v1') {\n        refuse(refusal('SETTLEMENT_SCOPED_SALT_V1', \"crossChainPermits: a settlement-scoped session cannot use saltMode 'v1': it must not share a permissionId with an unscoped session\"));\n    }\n    const namedPermit2Permits = resolvedPermits.filter((permit) => !isSettlementScopedPermit(permit));\n    const permit2Permits = [\n        ...namedPermit2Permits,\n        ...(acrossPermit ? [acrossPermit] : []),\n    ];\n    // A permit's window goes on every action it adds. A session holds one\n    // Permit2-route permit: a second claim policy is refused below.\n    const permit2Window = permitTimeFrame(permit2Permits[0] ?? {});\n    const settlementWindow = permitTimeFrame(scopedPermit ?? {});\n    if (fallback !== undefined &&\n        (namedPermit2Permits.length === 0 ||\n            swapScope !== undefined ||\n            definition.restrictToActions === true)) {\n        refuse(refusal('FALLBACK_NOT_APPLICABLE', 'fallback needs a Permit2-layer permit, without restrictToActions or swap'));\n    }\n    const access = sessionAccess(definition, resolvedPermits, swapScope !== undefined, settlementScope?.settlementLayers);\n    const restricted = access.kind === 'scoped';\n    for (const [permitIndex, permit] of resolvedPermits.entries()) {\n        const at = { permitIndex, chainId };\n        // The burn and a fee carve are pre-claim calls, and an IntentExecutor\n        // layer has no claim: beside ACROSS, the option bounds the ACROSS claim.\n        // Its claims spend an allowance the account already holds, which\n        // maxAmount does not count.\n        if (permit.preClaimOps &&\n            (definition.oneTimeUse ||\n                permit.allowFees ||\n                permit.from?.some((leg) => leg.chain.id === chainId && leg.maxAmount !== undefined) ||\n                (isSettlementScopedPermit(permit) && acrossPermit === undefined))) {\n            refuse(refusal('PRE_CLAIM_OPS_NOT_APPLICABLE', 'crossChainPermits: preClaimOps needs a Permit2-layer permit without oneTimeUse, allowFees or maxAmount', at));\n        }\n        const permit2Permit = permit === scopedPermit ? acrossPermit : permit;\n        if (!permit2Permit || isSettlementScopedPermit(permit2Permit))\n            continue;\n        // Permit2 moves the wrapped token, so a native leg never matches the claim.\n        if (permit2Permit.from?.some(({ token }) => isNativeToken(token))) {\n            refuse(refusal('NATIVE_SOURCE_UNSUPPORTED', 'crossChainPermits: a Permit2-layer `from` must be an ERC-20, e.g. the wrapped native token', at));\n        }\n    }\n    const permit2Tokens = permit2SourceTokens(permit2Permits, chainId);\n    // A sudo wildcard already admits every fee call, so allowFees adds nothing.\n    const feesIndex = fallback === 'sudo'\n        ? -1\n        : resolvedPermits.findIndex((permit) => !isSettlementScopedPermit(permit) && permit.allowFees);\n    const permit2Fees = permit2Tokens.size && feesIndex !== -1\n        ? recover((error) => refuse(error, { permitIndex: feesIndex }), () => servedFees(options.settlement, chainId, [...permit2Tokens.keys()]))\n        : undefined;\n    // The orchestrator wraps native funding of a wrapped native `from` leg. The\n    // address comes from `/chains`, so the wrap is granted only within that\n    // leg's cap.\n    const wrapped = options.wrappedNativeToken;\n    const wrapCap = restricted && wrapped\n        ? [...permit2Tokens].find(([token]) => isAddressEqual(token, wrapped))?.[1]\n        : undefined;\n    // ValueLimitPolicy refuses a zero limit when the session is enabled.\n    if (wrapCap === 0n) {\n        refuse(refusal('WRAPPED_NATIVE_ZERO_CAP', 'crossChainPermits: a wrapped native `from` leg needs a maxAmount above 0', { chainId }));\n    }\n    const permissions = [\n        ...windowed.permissions,\n        ...(swapScope?.permissions ?? []).map((permission) => permissionWithTimeFrame(permission, windowed.swapWindow)),\n        ...(settlementScope?.permissions ?? []).map((permission) => permissionWithTimeFrame(permission, settlementWindow)),\n    ];\n    // The wildcard admits a fallback session's approves; an exact approve action\n    // would take precedence over it and refuse every other spender.\n    const permit2Actions = recover(refuse, () => fallback === undefined\n        ? permit2RouteScope(permit2Tokens, permissions, windowed.actions, permit2Fees, wrapped && wrapCap ? { token: wrapped, cap: wrapCap } : undefined, acrossPermit === undefined)\n        : permit2FallbackScope(permit2Tokens, permissions, windowed.actions, permit2Fees))?.map((action) => withTimeFrame(action, permit2Window)) ?? [];\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        ...windowed.actions,\n        ...(swapScope?.actions ?? []).map((action) => withTimeFrame(action, windowed.swapWindow)),\n        ...(settlementScope?.actions ?? []).map((action) => withTimeFrame(action, settlementWindow)),\n        ...permit2Actions,\n    ];\n    if (definition.oneTimeUse) {\n        if (definition.saltMode === 'v1') {\n            throw new Error(\"oneTimeUse cannot use saltMode 'v1': a 1.x session has no once-policy to reproduce\");\n        }\n    }\n    if (definition.saltMode === 'v1' &&\n        definition.policyAddresses?.universalActionCopies?.length) {\n        throw new Error(\"universalActionCopies cannot use saltMode 'v1': a 1.x session has no split policies to reproduce\");\n    }\n    const validUntil = definition.oneTimeUse?.validUntil;\n    // A deadline that rounds to 0 would read as \"never expires\"; a past one only\n    // fails at enable, as an opaque signature error.\n    if (validUntil !== undefined && !isFutureDate(validUntil)) {\n        throw new Error('oneTimeUse.validUntil must be a valid Date in the future');\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    // A reusable session's maxAmount is a lifetime total only while every claim's\n    // pre-claim calls are checked against its counter, which `fallback` leaves\n    // to no ERC-1271 bound (and `'sudo'` installs no limit at all).\n    const uncappedIndex = definition.oneTimeUse || fallback === undefined\n        ? -1\n        : resolvedPermits.findIndex((permit) => !isSettlementScopedPermit(permit) &&\n            permit.from?.some(({ maxAmount }) => maxAmount !== undefined));\n    if (uncappedIndex !== -1) {\n        refuse(refusal('PERMIT2_MAX_AMOUNT_REQUIRES_ONE_TIME_USE', \"crossChainPermits: with `fallback`, a Permit2-route permit's maxAmount is enforced only with oneTimeUse; set oneTimeUse, drop maxAmount, or drop `fallback`\", { permitIndex: uncappedIndex }));\n    }\n    let expansionRefused = false;\n    const expandedPermits = permit2Permits.flatMap((permit) => {\n        const permitIndex = permitIndexOf(permit);\n        const expanded = recover((error) => {\n            expansionRefused = true;\n            refuse(error, { permitIndex });\n        }, () => expandCrossChainPermit(permit, environment, onceDeadline, definition.account, definition.chain));\n        return expanded === undefined ? [] : [expanded];\n    });\n    // The claims a dry run dropped feed the checks below, so it stops here.\n    if (expansionRefused)\n        throw new RefusalCollectionHalted();\n    // After the claim checks, so a refused claim reports its own reason first.\n    for (const permit of permit2Permits) {\n        const at = { permitIndex: permitIndexOf(permit), chainId };\n        const fromHere = permit.from?.some((leg) => leg.chain.id === chainId);\n        if (!fromHere &&\n            (fallback === undefined || (permit.allowFees && fallback !== 'sudo'))) {\n            refuse(refusal('PERMIT2_ROUTE_NEEDS_FROM', `crossChainPermits: a Permit2-layer permit needs a \\`from\\` token on chain ${chainId}`, at));\n        }\n        if (fallback !== undefined)\n            continue;\n        if (!boundsPreClaimCalls(definition, permit, permit2Sender)) {\n            refuse(refusal('PERMIT2_ROUTE_NEEDS_BOUND', `crossChainPermits: a Permit2-layer permit needs one of ${[...PRE_CLAIM_BOUNDS, 'fallback'].join(', ')}; chain ${chainId} has no Permit2SenderPolicy`, at));\n        }\n        // Smart accounts settle same-chain intents through the IntentExecutor, so\n        // ACROSS is the one Permit2 layer a scoped session needs.\n        if (livePermit2Layers(permit).some((layer) => layer !== 'ACROSS')) {\n            refuse(refusal('PERMIT2_ROUTE_ACROSS_ONLY', 'crossChainPermits: a scoped Permit2-layer permit settles through ACROSS only', at));\n        }\n        // The claim pins the native token, which an ACROSS fill never delivers.\n        if (permit.to?.some(({ token }) => isNativeToken(token))) {\n            refuse(refusal('NATIVE_DESTINATION_UNSUPPORTED', 'crossChainPermits: a scoped Permit2-layer `to` must be an ERC-20, e.g. the wrapped native token', at));\n        }\n    }\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 = withTimeFrame({\n        policies: fallback === 'sudo'\n            ? [{ type: 'sudo' }]\n            : [{ type: 'intent-execution' }, ...permitFallbackPolicies],\n    }, permit2Window);\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                withTimeFrame({\n                    target: options.wrappedNativeToken,\n                    selector: DEPOSIT_SELECTOR,\n                }, permit2Window),\n            ]\n            : []),\n        ...(restricted ? [] : [fallbackAction]),\n        // A one-time-use session enables with its burn, which replaces the dummy op.\n        ...(definition.oneTimeUse\n            ? []\n            : [\n                {\n                    target: DUMMY_PRECLAIMOP_TARGET,\n                    selector: DUMMY_PRECLAIMOP_SELECTOR,\n                    // 1 wei rather than sudo, which would let this injected action send\n                    // native value; not 0, which ValueLimitPolicy refuses at install.\n                    policies: restricted\n                        ? [{ type: 'value-limit', limit: 1n }]\n                        : [{ type: 'sudo' }],\n                },\n            ].map((action) => withTimeFrame(action, permit2Window ?? settlementWindow))),\n    ];\n    // A Permit2-route session without `from` has already been refused.\n    if (restricted &&\n        !userActions.length &&\n        !rawActions.length &&\n        !permit2Permits.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        // The session's own burn actions are added below; a user action on the policy\n        // would share their action id.\n        if (definition.oneTimeUse &&\n            addresses.oneTimeUseId &&\n            a.target.toLowerCase() === addresses.oneTimeUseId.toLowerCase()) {\n            throw new Error('oneTimeUse sessions authorise their own burn; do not add an action on the policy');\n        }\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    // With nothing to scope, the wildcard fallback carries sudo, not intent-execution.\n    const sudoFallback = !(userActions.length ||\n        rawActions.length ||\n        expandedPermits.length);\n    let actions = !sudoFallback\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\n                ? encodeActionPolicies(action.policies, environment, addresses)\n                : [{ 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        ? resolveSession(definition, { ...options, environment: 'production' }, collect).data.actions\n        : undefined;\n    const rawClaimPolicies = expandedPermits.map(({ claim }) => claim);\n    // The pre-claim entrypoint is permissionless and names its caller as the\n    // arbiter, so an unpinned arbiter lets the session key settle without burning.\n    if (definition.oneTimeUse &&\n        rawClaimPolicies.some((claim) => !claim.spenders?.length)) {\n        throw new Error('oneTimeUse claim policies must pin their spenders (the Permit2 arbiter)');\n    }\n    let claimPolicies = rawClaimPolicies.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, unless it holds claim policies, which then\n    // become its whole 1271 list (see boundsPreClaimCalls). Without them, a 1271\n    // surface would let a one-time-use key settle through Permit2 unbounded by the id.\n    const executorOnlyOneTimeUse = Boolean(definition.oneTimeUse) && claimPolicies.length === 0;\n    if (executorOnlyOneTimeUse &&\n        definition.signing &&\n        definition.signing.mode !== 'disabled') {\n        throw new Error('oneTimeUse without claim policies cannot sign; leave `signing` unset');\n    }\n    let signing = definition.signing ??\n        ((restricted && rawClaimPolicies.length === 0) || executorOnlyOneTimeUse\n            ? { mode: 'disabled' }\n            : undefined);\n    // A signing surface would outlive the action windows, so it is bounded by the\n    // time any of them allows. Claim policies replace it, keeping only `signing`.\n    const actionWindow = windowed.windows.reduce((a, b) => (a ? unionTimeFrames(a, b) : b), undefined);\n    if (actionWindow && signing?.mode !== 'disabled') {\n        const window = intersectTimeFrames(actionWindow, timeFrame(signing?.validAfter?.getTime(), signing?.validUntil?.getTime()));\n        if (isEmptyTimeFrame(window)) {\n            throw refusal('VALID_AFTER_EXCEEDS_VALID_UNTIL', 'signing: its window does not overlap the action or permit windows');\n        }\n        signing = {\n            ...(signing ?? { mode: 'unrestricted' }),\n            validAfter: new Date(window.validAfter),\n            validUntil: new Date(window.validUntil),\n        };\n    }\n    // The previous TimeFramePolicy holds a window on ERC-1271 checks, so signing\n    // keeps it where the current one is not deployed.\n    const timeFrameMissing = definition.policyAddresses?.timeFrame === undefined &&\n        !timeFramePolicyDeployed(chainId);\n    const signingAddresses = timeFrameMissing\n        ? { ...addresses, timeFrame: PREVIOUS_TIME_FRAME_POLICY_ADDRESS }\n        : addresses;\n    if (timeFrameMissing &&\n        actions.some(({ actionPolicies }) => actionPolicies.some(({ policy }) => policy === addresses.timeFrame))) {\n        refuse(refusal('TIME_FRAME_POLICY_UNAVAILABLE', `chain ${chainId}: ${SESSION_REFUSAL_CODES.TIME_FRAME_POLICY_UNAVAILABLE}; set policyAddresses.timeFrame`));\n    }\n    const erc7739Policies = resolveSessionSigning({\n        signing,\n        environment,\n        addresses: signingAddresses,\n    });\n    let erc1271Policies = erc7739Policies.erc1271Policies;\n    let onceErc1271Policy;\n    if (definition.oneTimeUse) {\n        if (!addresses.oneTimeUseId) {\n            throw new Error(oneTimeUseIdPolicyMissing(definition.chain.id, environment));\n        }\n        const once = oneTimeUseIdErc1271Policy({\n            policy: addresses.oneTimeUseId,\n            id: definition.oneTimeUse.id,\n            deadline: onceDeadline,\n        });\n        // The once-policy goes on EVERY action: checkAction runs its guard once per\n        // execution, so no other permitted action can carry the batch.\n        actions = [\n            ...actions.map((action) => ({\n                ...action,\n                actionPolicies: [...action.actionPolicies, once],\n            })),\n            // The burn itself, so every session shape can settle: checkAction pins it to\n            // this session's own id and requires it before any other execution.\n            ...[CONSUME_SELECTOR, CONSUME_FOR_SELECTOR].map((actionTargetSelector) => ({\n                actionTarget: addresses.oneTimeUseId,\n                actionTargetSelector,\n                actionPolicies: [once],\n            })),\n        ];\n        onceErc1271Policy = once;\n    }\n    // Permit2 checks a contract owner via `isValidSignature`, so claim policies\n    // bind only from the 1271 list, where they AND with the once-policy. A session\n    // declaring none keeps its own signing list: a lone once-policy there would\n    // approve a Permit2 transfer with no claim policy bounding the spender.\n    const claimPoliciesMoved = claimPolicies.length > 0;\n    if (claimPoliciesMoved) {\n        const signing = definition.signing;\n        // A window lowers to a TimeFramePolicy that ANDs with the claim policies, so\n        // it is carried; a windowless signing policy is sudo and is dropped.\n        if (signing !== undefined && signing.mode !== 'unrestricted') {\n            throw refusal('CLAIM_POLICIES_SIGNING_MODE', `Claim policies take over the session's ERC-1271 list, so \\`signing.mode: '${signing.mode}'\\` cannot also be configured — it rewrites the ERC-7739 content gate the claim policy is reached through, leaving the policy unreachable. Omit \\`signing\\` to keep only the claim policies, or use \\`{ mode: 'unrestricted', validAfter, validUntil }\\` to bound them with a window.`);\n        }\n        const hasWindow = signing?.validAfter !== undefined || signing?.validUntil !== undefined;\n        if (signing?.validUntil !== undefined &&\n            !(Number.isFinite(signing.validUntil.getTime()) &&\n                signing.validUntil.getTime() > Date.now())) {\n            throw refusal('CLAIM_POLICIES_SIGNING_WINDOW_CLOSED', 'signing.validUntil must be a valid Date in the future when the session carries claim policies — an expired window leaves no surface that can authorize a claim');\n        }\n        // Permit2 refuses an expired permit and the claim caps its deadline, but a\n        // permit signed before the window opens is stopped only here.\n        const claimWindow = permit2Permits.some((permit) => permit.validAfter !== undefined)\n            ? permit2Window\n            : undefined;\n        let windowPolicies = hasWindow ? erc1271Policies : [];\n        if (claimWindow) {\n            let window = claimWindow;\n            if (hasWindow) {\n                window = intersectTimeFrames(window, timeFrame(signing?.validAfter?.getTime(), signing?.validUntil?.getTime()));\n                // Each was checked alone; one entry per policy holds both.\n                if (isEmptyTimeFrame(window)) {\n                    throw refusal('VALID_AFTER_EXCEEDS_VALID_UNTIL', 'signing: its window does not overlap the action or permit windows');\n                }\n            }\n            windowPolicies = [\n                encodeSessionPolicy(window, environment, signingAddresses),\n            ];\n        }\n        erc1271Policies = [\n            ...claimPolicies,\n            // Only where no other bound holds, so those sessions keep their ids.\n            ...(fallback === undefined &&\n                permit2Sender &&\n                permit2Permits.some((permit) => !boundsPreClaimCalls(definition, permit))\n                ? [{ policy: permit2Sender, initData: '0x' }]\n                : []),\n            ...windowPolicies,\n            ...(onceErc1271Policy ? [onceErc1271Policy] : []),\n        ];\n        claimPolicies = [];\n    }\n    // The ERC-1271 list is an AddressSet keyed by policy, so a repeated address keeps\n    // only its last config, and every Permit2 claim policy is one contract.\n    {\n        const seen = new Set();\n        for (const { policy } of erc1271Policies) {\n            const key = policy.toLowerCase();\n            if (seen.has(key)) {\n                throw refusal('DUPLICATE_ERC1271_POLICY', `Session carries ERC-1271 policy ${policy} twice; the second config would overwrite the first on-chain, so only one of the declared restrictions would be enforced. Split them across sessions.`);\n            }\n            seen.add(key);\n        }\n    }\n    // Enabling keeps one config per policy contract and action, so a second\n    // entry for the same policy would overwrite the first instead of ANDing.\n    for (const action of actions) {\n        const seen = new Set();\n        for (const { policy } of action.actionPolicies) {\n            const key = policy.toLowerCase();\n            if (seen.has(key)) {\n                throw new Error(`Action (${action.actionTarget}, ${action.actionTargetSelector}) carries policy ${policy} twice; the second config would overwrite the first on-chain`);\n            }\n            seen.add(key);\n        }\n    }\n    const enabledErc7739Policies = { ...erc7739Policies, erc1271Policies };\n    const data = {\n        sessionValidator: validator.address,\n        sessionValidatorInitData: validator.initData,\n        // These sessions must never share a permissionId: an enable would union with\n        // the other session's policies. A claim-policy session is never `restricted`,\n        // and an enable that finds a swap window's id taken would never install it.\n        salt: sessionSalt(definition.oneTimeUse ||\n            stableFloor ||\n            claimPoliciesMoved ||\n            settlementScope !== undefined ||\n            (windowed.swapWindow !== undefined && definition.saltMode !== 'v1')\n            ? 'strict'\n            : definition.saltMode, restricted || Boolean(definition.oneTimeUse) || claimPoliciesMoved, {\n            actions: v1SaltActions ?? actions,\n            erc7739Policies: enabledErc7739Policies,\n            claimPolicies,\n        }),\n        erc7739Policies: enabledErc7739Policies,\n        actions,\n        claimPolicies,\n    };\n    return {\n        data,\n        // An intent sends no enable data for a permissionId already enabled, so\n        // the window may not be installed.\n        sharedActionWindow: windowed.windows.length > 0 && data.salt === zeroHash,\n        settlementLayers: settlementScope?.settlementLayers ?? [],\n        permit2Permits,\n        settlementCoverage: settlementScope && {\n            dropped: settlementScope.dropped,\n        },\n        access: sudoFallback\n            ? {\n                kind: 'open',\n                reason: 'no restriction set; the wildcard fallback is sudo',\n            }\n            : access,\n    };\n}\n/** Whether the session drops the intent-execution fallback, and what decided it. */\nfunction sessionAccess(definition, permits, swapScoped, settlementLayers) {\n    if (definition.fallback !== undefined) {\n        return { kind: 'open', reason: `fallback: ${definition.fallback}` };\n    }\n    const permit2 = permits.filter((permit) => !isSettlementScopedPermit(permit));\n    const scopedBy = [\n        ...(definition.restrictToActions === true ? ['restrictToActions'] : []),\n        ...(swapScoped ? ['swap scope'] : []),\n        ...(settlementLayers\n            ? [`settlement-scoped permit (${settlementLayers.join(', ')})`]\n            : []),\n        ...(permit2.length\n            ? [`Permit2-route permit (${permit2LayerSet(permit2).join(', ')})`]\n            : []),\n    ];\n    if (scopedBy.length)\n        return { kind: 'scoped', reason: scopedBy.join('; ') };\n    return { kind: 'open', reason: 'no restriction set' };\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`, so two for the same signer share\n * a permissionId even when their permissions differ. Restricted and one-time-use\n * ones can take a salt that tells them apart.\n */\nfunction sessionSalt(mode, salted, session) {\n    if (!salted || 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 other than one-time-use ones keep `zeroHash`, which is\n * what their stored signatures 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}\n/**\n * The Permit2 layers the session's permit names. Empty when it names none,\n * which admits every Permit2 arbiter. A session carries at most one Permit2\n * permit (a second claim policy is refused when the session resolves).\n */\nfunction namedPermit2Layers(permits) {\n    return [\n        ...new Set(permits.flatMap(({ settlementLayers }) => Array.isArray(settlementLayers) ? settlementLayers : [])),\n    ];\n}\n/** The ways a Permit2-route session's ERC-1271 list bounds the calls a claim carries. */\nconst PRE_CLAIM_BOUNDS = [\n    'oneTimeUse',\n    \"preClaimOps: 'none'\",\n    'Permit2SenderPolicy',\n];\n/**\n * Whether the session's ERC-1271 list bounds the pre-claim calls a claim\n * through this permit may carry, which a scoped session needs: the once-policy\n * and Permit2SenderPolicy admit only Permit2 as the requester, so pre-claim\n * calls are checked as executions, and `preClaimOps: 'none'` admits none.\n */\nfunction boundsPreClaimCalls(definition, permit, permit2Sender) {\n    return (Boolean(definition.oneTimeUse) ||\n        permit.preClaimOps === 'none' ||\n        permit2Sender !== undefined);\n}\n/** Every Permit2 layer the permits settle through, once each. */\nfunction permit2LayerSet(permits) {\n    return [...new Set(permits.flatMap(livePermit2Layers))];\n}\n/**\n * The definition's permits, a permit naming no layer read as `'all'`. With\n * `fallback` it keeps `ACROSS`: `'all'` is settlement-scoped, and `fallback`\n * needs a Permit2-layer permit.\n */\nfunction sessionPermits(definition) {\n    const permits = definition.crossChainPermits ?? [];\n    if (definition.fallback !== undefined)\n        return permits;\n    return permits.map((permit) => permit.settlementLayers?.length\n        ? permit\n        : { ...permit, settlementLayers: 'all' });\n}\n/**\n * Why `'all'` leaves ACROSS out: the refusal a permit naming it would meet,\n * without its `crossChainPermits: ` prefix.\n */\nfunction acrossDropReason(definition, permit, permit2Sender, wrappedNativeToken) {\n    const chainId = definition.chain.id;\n    if (permit.to?.some((leg) => leg.minAmount !== undefined)) {\n        return '`to.minAmount` does not apply to Permit2 layers';\n    }\n    // ACROSS output is what the claim signs, so no floor binds it.\n    if (permit.maxFeeBps !== undefined) {\n        return 'maxFeeBps applies only to ECO_IE';\n    }\n    if (permit.from?.some(({ token }) => isNativeToken(token))) {\n        return 'a Permit2-layer `from` must be an ERC-20, e.g. the wrapped native token';\n    }\n    if (permit.to?.some(({ token }) => isNativeToken(token))) {\n        return 'a scoped Permit2-layer `to` must be an ERC-20, e.g. the wrapped native token';\n    }\n    if (!boundsPreClaimCalls(definition, permit, permit2Sender)) {\n        return `a Permit2-layer permit needs one of ${[...PRE_CLAIM_BOUNDS, 'fallback'].join(', ')}; chain ${chainId} has no Permit2SenderPolicy`;\n    }\n    const wrapped = wrappedNativeToken;\n    if (wrapped &&\n        [...permit2SourceTokens([permit], chainId)].some(([token, cap]) => isAddressEqual(token, wrapped) && cap === 0n)) {\n        return 'a wrapped native `from` leg needs a maxAmount above 0';\n    }\n    return undefined;\n}\n/**\n * The ACROSS route of a permit naming IntentExecutor layers too, pinned as the\n * layers pin it: a leg without a recipient delivers to the account, and the\n * chain's one cap bounds each of its `from` tokens, as the shared approve does.\n */\nfunction acrossPart(permit, account, chainId) {\n    const cap = permit.from?.find((leg) => leg.chain.id === chainId && leg.maxAmount !== undefined)?.maxAmount;\n    return {\n        ...permit,\n        settlementLayers: ['ACROSS'],\n        ...(permit.from &&\n            cap !== undefined && {\n            from: permit.from.map((leg) => leg.chain.id === chainId && leg.maxAmount === undefined\n                ? { ...leg, maxAmount: cap }\n                : leg),\n        }),\n        ...(permit.to &&\n            account &&\n            permit.recipientIsAccount === false && {\n            to: permit.to.map((leg) => leg.recipient === undefined ? { ...leg, recipient: account } : leg),\n        }),\n    };\n}\n/**\n * The definition's policy addresses, with the deployed UniversalActionPolicy\n * copies defaulted in for a settlement-scoped session on a chain that has them.\n */\nexport function sessionPolicyAddresses(definition) {\n    const overrides = definition.policyAddresses;\n    const universalAction = overrides?.universalAction;\n    if (overrides?.universalActionCopies !== undefined ||\n        // A pinned ArgPolicy asks for the ArgPolicy encoding; splitting would move it.\n        overrides?.argPolicy !== undefined ||\n        // The copies hold the canonical code, so they cannot stand in for another.\n        (universalAction !== undefined &&\n            universalAction.toLowerCase() !==\n                UNIVERSAL_ACTION_POLICY_ADDRESS.toLowerCase()) ||\n        // resolve refuses it; this only spares createSession a code check first.\n        definition.saltMode === 'v1' ||\n        !UNIVERSAL_ACTION_POLICY_COPY_CHAINS.has(definition.chain.id) ||\n        !sessionPermits(definition).some(isSettlementScopedPermit)) {\n        return overrides;\n    }\n    return { ...overrides, universalActionCopies: UNIVERSAL_ACTION_POLICY_COPIES };\n}\nexport function toSession(definition, options = {}) {\n    const environment = options.environment ?? 'production';\n    // One resolution: 'all' depends on the clock and the catalog, so a second\n    // could keep a different set of layers than the session's actions.\n    const { data, settlementLayers, settlementCoverage, access, permit2Permits } = resolveSession(definition, {\n        environment,\n        ...(options.wrappedNativeToken\n            ? { wrappedNativeToken: options.wrappedNativeToken }\n            : {}),\n        ...(options.settlement ? { settlement: options.settlement } : {}),\n    });\n    const resolvedPermits = sessionPermits(definition).map((permit) => resolveCrossChainPermission(permit));\n    const scopedPermits = resolvedPermits.filter(isSettlementScopedPermit);\n    const permit2Scoped = access.kind === 'scoped' && permit2Permits.length > 0;\n    // A scoped Permit2-route session settles only through the live arbiters.\n    const intentLayers = settlementLayers.length\n        ? settlementLayers\n        : permit2Scoped\n            ? permit2LayerSet(permit2Permits)\n            : namedPermit2Layers(resolvedPermits);\n    // The same deadline as the installed claim, which signing re-encodes from here.\n    const otuUntil = definition.oneTimeUse?.validUntil;\n    const expandedClaims = permit2Permits.map((permit) => expandCrossChainPermit(permit, environment, otuUntil && seconds(otuUntil), undefined, definition.chain).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            scopedPermits.length ||\n            permit2Scoped ||\n            // The fallback action admits the IntentExecutor layers' calls; its\n            // ERC-1271 list holds only the claim policy, which refuses them.\n            definition.fallback),\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        // Kept for both routes: the Permit2 settlement signature builds their calldata\n        // from here (see claimPolicyData); they are enforced from the 1271 list.\n        claimPolicies: expandedClaims,\n        ...(definition.swap ? { swap: definition.swap } : {}),\n        ...(intentLayers.length ? { settlementLayers: intentLayers } : {}),\n        ...(settlementCoverage ? { settlementCoverage } : {}),\n        ...(permit2Scoped && {\n            permit2Sources: [\n                ...new Map(permit2Permits.flatMap(({ from = [] }) => from.map(({ chain }) => [chain.id, chain]))).values(),\n            ].flatMap((chain) => [...permit2SourceTokens(permit2Permits, chain.id)].map(([token, maxAmount]) => ({\n                chain,\n                token,\n                ...(maxAmount === undefined ? {} : { maxAmount }),\n            }))),\n        }),\n        access,\n        ...(!definition.oneTimeUse &&\n            resolvedPermits.some(({ from }) => from?.some(({ chain, maxAmount }) => chain.id === definition.chain.id && maxAmount !== undefined)) && { lifetimeBudget: true }),\n        ...(definition.oneTimeUse && {\n            oneTimeUse: {\n                id: definition.oneTimeUse.id,\n                policy: resolvePolicyAddresses(definition.policyAddresses, {\n                    chainId: definition.chain.id,\n                    environment,\n                }).oneTimeUseId,\n                ...(definition.policyAddresses?.oneTimeUseId === undefined\n                    ? { defaultPolicy: true }\n                    : {}),\n            },\n        }),\n    };\n}\nexport { DEFAULT_POLICY_ADDRESSES };\n","import { isAddress, isHex, padHex, size, toFunctionSelector, } from 'viem';\nimport { isEmptyTimeFrame, timeFrame, } from './smart-sessions/policies/time-frame.js';\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]);\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 window = timeFrame(config.validAfter?.getTime(), config.validUntil?.getTime());\n            if (isEmptyTimeFrame(window)) {\n                throw new Error(`Function \"${fnName}\": validAfter must be earlier than validUntil`);\n            }\n            policies.push(window);\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","/** Year 2100 in ms: the always-passing validUntil of a one-sided window. */\nexport const FAR_FUTURE_MS = 4_102_444_800_000;\n/** Whether `ms` is a time TimeFramePolicy can hold: whole seconds in uint48. */\nexport function isWindowTime(ms) {\n    return typeof ms === 'number' && ms >= 0 && ms < 2 ** 48 * 1000;\n}\n/** A window (unix ms) as a time-frame policy; an open end always passes. */\nexport function timeFrame(validAfter, validUntil) {\n    return {\n        type: 'time-frame',\n        validUntil: validUntil ?? FAR_FUTURE_MS,\n        validAfter: validAfter ?? 0,\n    };\n}\n/** A permit's window (unix seconds) as a time-frame policy, if it sets one. */\nexport function permitTimeFrame(permit) {\n    const ms = (s) => (s === undefined ? s : Number(s * 1000n));\n    return permit.validAfter === undefined && permit.validUntil === undefined\n        ? undefined\n        : timeFrame(ms(permit.validAfter), ms(permit.validUntil));\n}\n/** The time both windows allow: the later start and the earlier end. */\nexport function intersectTimeFrames(a, b) {\n    return timeFrame(Math.max(a.validAfter, b.validAfter), Math.min(a.validUntil, b.validUntil));\n}\n/** The time either window allows, and any gap between them. */\nexport function unionTimeFrames(a, b) {\n    return timeFrame(Math.min(a.validAfter, b.validAfter), Math.max(a.validUntil, b.validUntil));\n}\n/** Whether no second passes the policy's `validAfter <= t < validUntil`. */\nexport function isEmptyTimeFrame({ validAfter, validUntil, }) {\n    return Math.ceil(validAfter / 1000) >= Math.floor(validUntil / 1000);\n}\n/** The action with `window` added to its policies. */\nexport function withTimeFrame(action, window) {\n    return window\n        ? { ...action, policies: [...(action.policies ?? []), window] }\n        : action;\n}\n/** The permission with `window` on every function, as `validAfter`/`validUntil`. */\nexport function permissionWithTimeFrame(permission, window) {\n    if (window === undefined)\n        return permission;\n    return {\n        ...permission,\n        functions: Object.fromEntries(Object.entries(permission.functions).map(([name, config]) => [\n            name,\n            config && {\n                ...config,\n                validAfter: new Date(window.validAfter),\n                validUntil: new Date(window.validUntil),\n            },\n        ])),\n    };\n}\n","import { FAR_FUTURE_MS, isWindowTime } from './policies/time-frame.js';\nimport { refusal, refuser, SESSION_REFUSAL_CODES, } from './refusals.js';\n/** The refusal for a recipient `allowRecipientNotAccount` has not opened, on either route. */\nexport function recipientNotAllowed(recipient) {\n    return recipient === 'any'\n        ? refusal('RECIPIENT_ANY_NOT_ALLOWED', \"crossChainPermits: recipient 'any' requires allowRecipientNotAccount\")\n        : refusal('RECIPIENT_NOT_ACCOUNT', 'crossChainPermits: a recipient other than the account requires allowRecipientNotAccount');\n}\nfunction 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, refuse = refuser()) {\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        ...(leg.minAmount === undefined ? {} : { minAmount: leg.minAmount }),\n    }));\n    const until = input.validUntil;\n    // resolve refuses a validUntil that is not a future Date.\n    const validUntil = until instanceof Date && isWindowTime(until.getTime())\n        ? seconds(until)\n        : undefined;\n    const after = input.validAfter;\n    let validAfter;\n    if (after instanceof Date && isWindowTime(after.getTime())) {\n        // Rounded up, so the window never opens early.\n        validAfter = BigInt(Math.ceil(after.getTime() / 1000));\n    }\n    else if (after !== undefined) {\n        refuse(refusal('VALID_AFTER_INVALID', `crossChainPermits: ${SESSION_REFUSAL_CODES.VALID_AFTER_INVALID}`));\n    }\n    if (validAfter !== undefined &&\n        validAfter >= (validUntil ?? BigInt(FAR_FUTURE_MS / 1000))) {\n        refuse(refusal('VALID_AFTER_EXCEEDS_VALID_UNTIL', `crossChainPermits: ${SESSION_REFUSAL_CODES.VALID_AFTER_EXCEEDS_VALID_UNTIL}`));\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        ...(input.maxFeeBps === undefined ? {} : { maxFeeBps: input.maxFeeBps }),\n        ...(input.allowFees === undefined ? {} : { allowFees: input.allowFees }),\n        ...(input.preClaimOps && { preClaimOps: input.preClaimOps }),\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        ...(permit.maxFeeBps === undefined ? {} : { maxFeeBps: permit.maxFeeBps }),\n        ...(permit.allowFees === undefined ? {} : { allowFees: permit.allowFees }),\n        ...(permit.preClaimOps && { preClaimOps: permit.preClaimOps }),\n    };\n}\n","import { isAddressEqual } from 'viem';\nimport { getArbitersForSettlementLayers } from '../../policies/claim/arbiters.js';\nimport { recipientNotAllowed } from '../cross-chain-permits.js';\nimport { refusal } from '../refusals.js';\nexport function expandCrossChainPermit(permit, environment, onceDeadline, account, chain) {\n    // Unreachable ('all' is settlement-scoped); narrows the type for the arbiters.\n    if (permit.settlementLayers === 'all') {\n        throw new Error(\"crossChainPermits (internal): settlementLayers 'all' names IntentExecutor layers, which have no Permit2 claim\");\n    }\n    // The orchestrator does not route a smart account through the Permit2 ECO\n    // arbiter, so the claim never admits it.\n    if (permit.settlementLayers?.includes('ECO')) {\n        throw refusal('RETIRED_PERMIT2_LAYER', 'crossChainPermits: the Permit2 ECO arbiter is retired; use ECO_IE');\n    }\n    if (permit.maxFeeBps !== undefined) {\n        throw refusal('MAX_FEE_BPS_ONLY_ECO_IE', 'crossChainPermits: maxFeeBps applies only to ECO_IE');\n    }\n    if (permit.to?.some((leg) => leg.minAmount !== undefined)) {\n        throw refusal('MIN_AMOUNT_ON_PERMIT2_LAYER', 'crossChainPermits: `to.minAmount` does not apply to Permit2 layers');\n    }\n    // recipientIsSponsor pins every recipient to the account, so a leg pinned\n    // anywhere else could never settle.\n    if (permit.recipientIsAccount ?? true) {\n        const leg = permit.to?.find(({ recipient }) => recipient === 'any' ||\n            (recipient !== undefined &&\n                account !== undefined &&\n                !isAddressEqual(recipient, account)));\n        if (leg?.recipient !== undefined)\n            throw recipientNotAllowed(leg.recipient);\n    }\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    // The once-policy refuses a settlement past its deadline, so the claim does too.\n    // Permit2 accepts a deadline it has reached, and the window has closed then.\n    const until = permit.validUntil === undefined ? undefined : permit.validUntil - 1n;\n    const maxDeadline = onceDeadline !== undefined && (until === undefined || onceDeadline < until)\n        ? onceDeadline\n        : until;\n    const permitDeadline = permit.validAfter !== undefined || maxDeadline !== undefined\n        ? { min: permit.validAfter, max: maxDeadline }\n        : undefined;\n    const claim = {\n        type: 'permit2',\n        spenders: getArbitersForSettlementLayers(livePermit2Layers(permit), environment === 'development'),\n        sourceTokens,\n        destinationTokens,\n        recipients: recipientsList.length ? recipientsList : undefined,\n        recipientIsAccount: permit.recipientIsAccount,\n        permitDeadline,\n        fillDeadline: permit.fillDeadline,\n        ...(chain &&\n            permit.preClaimOps && { originOps: [{ chain, required: false }] }),\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    return { claim, fallbackPolicies };\n}\n/** The Permit2 layers a permit settles through: those it names, else ACROSS. */\nexport function livePermit2Layers(permit) {\n    const named = Array.isArray(permit.settlementLayers)\n        ? permit.settlementLayers\n        : [];\n    return named.length ? named : ['ACROSS'];\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        originOps: policy.originOps?.map(({ chain, required }) => ({\n            chainId: chain.id,\n            required,\n        })),\n    };\n}\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` stays mapped to the legacy Standard ECO arbiters: the claim policy\n * inspects only the origin mandate, so allowing the generic\n * `intentExecutorAdapter` would admit every IntentExecutor-backed route without\n * its Eco destination, token, recipient or deadline checked.\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    // Fail closed: an empty result would leave the claim policy with no spender\n    // pin, which admits any arbiter. IntentExecutor layers never reach here.\n    for (const layer of layers ?? []) {\n        if (!(layer in SETTLEMENT_LAYER_CONTRACT_KEYS)) {\n            throw new Error(`Settlement layer ${layer} has no Permit2 arbiter`);\n        }\n    }\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","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.ceil(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/** The rules of an expression that only ANDs rules, in evaluation order. */\nfunction andedRules(expression) {\n    if (expression.type === 'rule')\n        return [expression.rule];\n    if (expression.type !== 'and')\n        return undefined;\n    const left = andedRules(expression.left);\n    const right = andedRules(expression.right);\n    return left && right ? [...left, ...right] : undefined;\n}\n/**\n * Encodes an action's policies. With `universalActionCopies` configured, an\n * ArgPolicy that only ANDs rules becomes UniversalActionPolicy configs of up to\n * 16 rules, in evaluation order, one per deployment not already on the action.\n * Every config carries the ArgPolicy's `valueLimitPerUse`. It stays an\n * ArgPolicy when there are fewer free deployments than configs.\n */\nexport function encodeActionPolicies(policies, environment, addresses) {\n    const encoded = policies.map((policy) => encodeSessionPolicy(policy, environment, addresses));\n    const copies = addresses.universalActionCopies;\n    const index = policies.findIndex((policy) => policy.type === 'arg-policy');\n    const policy = policies[index];\n    if (!copies?.length || policy?.type !== 'arg-policy')\n        return encoded;\n    const rules = andedRules(policy.expression);\n    if (!rules)\n        return encoded;\n    const taken = new Set(encoded.flatMap((p, i) => (i === index ? [] : [p.policy.toLowerCase()])));\n    const free = [addresses.universalAction, ...copies].filter((address) => !taken.has(address.toLowerCase()));\n    const chunks = Math.ceil(rules.length / 16);\n    if (chunks > free.length)\n        return encoded;\n    const split = free.slice(0, chunks).map((address, i) => ({\n        ...encodeSessionPolicy({\n            type: 'universal-action',\n            valueLimitPerUse: policy.valueLimitPerUse,\n            rules: rules.slice(16 * i, 16 * (i + 1)),\n        }, environment, addresses),\n        policy: address,\n    }));\n    return [...encoded.slice(0, index), ...split, ...encoded.slice(index + 1)];\n}\n","import { isAddressEqual, zeroAddress } from 'viem';\nimport { refusal } from '../refusals.js';\nimport { APPROVE_SELECTOR, withFeeActions, } from '../settlement/fees.js';\nimport { NATIVE_SENTINEL } from '../settlement/same-chain.js';\nimport { cumulativeCap, pin, swapAction } from '../swap/rules.js';\nimport { PERMIT2 } from '../swap/stable-floor.js';\n/** `deposit()` on the wrapped native token. */\nexport const DEPOSIT_SELECTOR = '0xd0e30db0';\nexport const isNativeToken = (token) => isAddressEqual(token, zeroAddress) || isAddressEqual(token, NATIVE_SENTINEL);\n/** The `from` tokens on `chainId`, each with the largest `maxAmount` of its legs, or none if one leg has none. */\nexport function permit2SourceTokens(permits, chainId) {\n    const caps = new Map();\n    for (const { chain, token, maxAmount } of permits.flatMap(({ from }) => from ?? [])) {\n        if (chain.id !== chainId)\n            continue;\n        const seen = caps.get(token.toLowerCase());\n        // One settlement draws on one permit, so the largest cap covers it; a sum\n        // would let one approval exceed every leg's cap.\n        caps.set(token.toLowerCase(), [\n            seen?.[0] ?? token,\n            !seen\n                ? maxAmount\n                : seen[1] === undefined || maxAmount === undefined\n                    ? undefined\n                    : seen[1] > maxAmount\n                        ? seen[1]\n                        : maxAmount,\n        ]);\n    }\n    return new Map(caps.values());\n}\n/**\n * The scoped actions a Permit2-route permit settles through: per `from` token,\n * `approve(Permit2, amount)` capped cumulatively at its largest `maxAmount`;\n * the wrapped-native `deposit()`, its value capped, when `wrap` is given;\n * and the fee calls when `fees` is. A declared approve on a `from` token is\n * refused: the permit adds its own, or with `approve` false the settlement\n * scope it shares a permit with does.\n */\nexport function permit2RouteScope(sourceTokens, permissions, declaredActions, fees, wrap, approve = true) {\n    refuseDeclaredApproves(sourceTokens.keys(), permissions, declaredActions, 'the permit adds its own');\n    const actions = [];\n    for (const [token, cap] of approve ? sourceTokens : []) {\n        actions.push(swapAction(token, APPROVE_SELECTOR, [\n            pin(0n, PERMIT2),\n            ...(cap === undefined ? [] : [cumulativeCap(32n, cap)]),\n        ]));\n    }\n    if (wrap) {\n        actions.push({\n            target: wrap.token,\n            selector: DEPOSIT_SELECTOR,\n            policies: [{ type: 'value-limit', limit: wrap.cap }],\n        });\n    }\n    return fees === undefined\n        ? actions\n        : withFeeActions(actions, [...sourceTokens.keys()], fees);\n}\n/**\n * The fee calls of a `fallback` session's Permit2-route permit: the capped\n * transfer to the fee collector and the paymaster callback. An exact\n * (token, approve) action would replace the wildcard for every approve of that\n * token, so approves, the paymaster's included, are left to the wildcard. The\n * transfer takes nothing from it: the intent-execution policy admits a token's\n * `transfer` only when the token is itself a whitelisted target (an OFT that is\n * its own adapter).\n */\nexport function permit2FallbackScope(sourceTokens, permissions, declaredActions, fees) {\n    refuseDeclaredApproves(sourceTokens.keys(), permissions, declaredActions, 'the fallback admits its approves');\n    return fees === undefined\n        ? []\n        : withFeeActions([], [...sourceTokens.keys()], fees, false);\n}\nfunction refuseDeclaredApproves(tokens, permissions, declaredActions, why) {\n    for (const token of tokens) {\n        if (permissions.some(({ address, functions }) => isAddressEqual(address, token) && functions.approve) ||\n            declaredActions.some(({ target, selector }) => isAddressEqual(target, token) && selector === APPROVE_SELECTOR)) {\n            throw refusal('PERMIT2_APPROVE_CONFLICT', `crossChainPermits: drop the declared approve on ${token}; ${why}`);\n        }\n    }\n}\n","import { isAddressEqual, toFunctionSelector, } from 'viem';\nimport { resolvePermissions } from '../../permissions.js';\nimport { refusal } from '../refusals.js';\nimport { allOf, anyOf, cumulativeCap, cumulativeOnly, pin, swapAction, } from '../swap/rules.js';\nimport { STABLE_DECIMALS } from '../swap/stable-floor.js';\nimport { withRule } from './same-chain.js';\n/**\n * `allowFees`: the app-fee transfer and the unsponsored-gas paymaster\n * calls the orchestrator adds before the layer calls. Each call has its own\n * USD cap ({@link settlementFeeCap}): per `from` token for the transfer and\n * approve, one shared across tokens for the callback.\n */\n/** The per-call cap in whole USD where a chain has no entry below. */\nconst DEFAULT_SETTLEMENT_FEE_USD = 5n;\n/** Chains whose per-call cap differs from the default, in whole USD. */\nconst SETTLEMENT_FEE_USD_BY_CHAIN = {\n    // Ethereum mainnet: a session enable needs a gas refund above 5 USD.\n    1: 30n,\n};\n/**\n * The per-call fee cap on `chainId` in raw units of a stablecoin with\n * `decimals`. Cumulative: the burning transaction admits every later op.\n */\nexport function settlementFeeCap(chainId, decimals) {\n    const usd = SETTLEMENT_FEE_USD_BY_CHAIN[chainId] ?? DEFAULT_SETTLEMENT_FEE_USD;\n    return usd * 10n ** BigInt(decimals);\n}\nconst TRANSFER_SELECTOR = toFunctionSelector('transfer(address,uint256)');\nexport const APPROVE_SELECTOR = toFunctionSelector('approve(address,uint256)');\nexport const CALLBACK_ALLOW_MAX_AMOUNT_SELECTOR = toFunctionSelector('callbackAllowMaxAmount(address,uint256)');\nconst isParamsPolicy = (policy) => policy.type === 'universal-action' || policy.type === 'arg-policy';\n/** The chain's fee addresses and cap, once every `from` token is one the layers serve with known decimals. */\nexport function servedFees(settlement, chainId, sourceTokens) {\n    if (settlement === undefined) {\n        throw refusal('ALLOW_FEES_CATALOG_MISSING', \"crossChainPermits: allowFees needs the orchestrator's settlement addresses; create the session with sdk.createSession\");\n    }\n    const chain = settlement[chainId];\n    if (chain?.fees === undefined) {\n        throw refusal('FEES_NOT_SERVED', `crossChainPermits: the orchestrator serves no fee addresses on chain ${chainId}, so allowFees cannot be scoped there`, { chainId });\n    }\n    // The cap is a USD amount, so it only bounds the stablecoins the layers serve\n    // (all 6-decimal today); any other token would make it meaningless.\n    const stables = [\n        chain.cctp?.usdc,\n        chain.oft?.token,\n        ...(chain.eco?.stablecoins ?? []),\n        chain.lz?.stargateUsdc?.token,\n        chain.lz?.cctp?.token,\n    ].filter((token) => token !== undefined);\n    for (const token of sourceTokens) {\n        if (!stables.some((stable) => isAddressEqual(stable, token))) {\n            throw refusal('ALLOW_FEES_NON_STABLECOIN', `crossChainPermits: allowFees caps fees in USD, so every \\`from\\` token must be a served USD stablecoin; ${token} on chain ${chainId} is not`, { chainId });\n        }\n    }\n    // The cap scales by the token's served decimals; a wrong scale moves it by\n    // orders of magnitude, so unknown decimals fail closed.\n    const decimals = sourceTokens.map((token) => {\n        const listed = (chain.usdStablecoins ?? []).filter((t) => isAddressEqual(t.address, token));\n        const why = listed.length === 0\n            ? 'is not listed in usdStablecoins'\n            : listed.length > 1\n                ? `appears ${listed.length} times in usdStablecoins`\n                : !STABLE_DECIMALS.has(listed[0].decimals)\n                    ? `is served with ${listed[0].decimals} decimals; expected 6 or 18`\n                    : undefined;\n        if (why !== undefined) {\n            throw refusal('ALLOW_FEES_NON_STABLECOIN', `crossChainPermits: allowFees caps fees in USD, so every \\`from\\` token must be a served USD stablecoin with known decimals; ${token} on chain ${chainId} ${why}`, { chainId });\n        }\n        return listed[0].decimals;\n    });\n    // The callback's one cap is shared across tokens, so it needs one scale.\n    if (new Set(decimals).size > 1) {\n        throw refusal('ALLOW_FEES_MIXED_DECIMALS', `crossChainPermits: allowFees shares one callback cap across \\`from\\` tokens, so they must have the same decimals; on chain ${chainId} they have ${[...new Set(decimals)].join(' and ')}`, { chainId });\n    }\n    // No `from` token leaves only the callback, at the 6-decimal scale.\n    return { ...chain.fees, cap: settlementFeeCap(chainId, decimals[0] ?? 6) };\n}\n/**\n * Turn the swap scope's approve permissions into raw actions, so the paymaster\n * approve can join them. The spending limit becomes a cumulative cap on the\n * swap's params policy: a shared limit would count the fee approves against it.\n */\nexport function swapApprovesAsActions(permissions, cap) {\n    if (permissions.length === 0)\n        return [];\n    // scopeSameChain refuses an uncapped swap first; this keeps the cap from being dropped.\n    if (cap === undefined) {\n        throw refusal('SAME_CHAIN_IE_SWAP_NEEDS_MAX_AMOUNT', 'crossChainPermits: a SAME_CHAIN_IE swap with allowFees needs maxAmount');\n    }\n    return resolvePermissions([...permissions]).map((action) => {\n        if (!('target' in action) || action.selector !== APPROVE_SELECTOR) {\n            throw new Error('crossChainPermits (internal): allowFees expected only approve permissions from the swap scope');\n        }\n        const policies = action.policies ?? [];\n        // Dropping the spending limit is only safe with a params policy to carry the cap.\n        if (!policies.some(isParamsPolicy)) {\n            throw new Error('crossChainPermits (internal): a swap approve has no params policy to carry its cap');\n        }\n        return {\n            ...action,\n            policies: policies\n                .filter((policy) => policy.type !== 'spending-limits')\n                .map((policy) => isParamsPolicy(policy)\n                ? withRule(policy, cumulativeCap(32n, cap))\n                : policy),\n        };\n    });\n}\n/**\n * Allow `branch` as a shape of the (target, selector) call: a new action when the\n * layer makes no such call, else ORed into the layer's one params policy, since\n * the chain keeps a single config per policy and action.\n */\nfunction addFeeBranch(actions, target, selector, branch) {\n    const index = actions.findIndex((a) => isAddressEqual(a.target, target) && a.selector === selector);\n    if (index === -1) {\n        // A rule list goes on UniversalActionPolicy, whose enable writes fewer slots.\n        const policies = Array.isArray(branch)\n            ? (swapAction(target, selector, branch).policies ?? [])\n            : [{ type: 'arg-policy', valueLimitPerUse: 0n, expression: branch }];\n        actions.push({ target, selector, policies });\n        return;\n    }\n    const expression = Array.isArray(branch) ? allOf(branch) : branch;\n    const existing = actions[index];\n    const policies = existing.policies ?? [];\n    const layer = policies.find(isParamsPolicy);\n    if (layer === undefined) {\n        throw new Error(`crossChainPermits (internal): the (${target}, ${selector}) action has no params policy for allowFees to join`);\n    }\n    const layerExpression = layer.type === 'universal-action' ? allOf(layer.rules) : layer.expression;\n    // The fee branch first: its pin fails fast for the layer's own call, and a\n    // fee call it admits never reaches (or counts against) the layer's cap.\n    actions[index] = {\n        ...existing,\n        policies: policies.map((p) => p === layer\n            ? {\n                type: 'arg-policy',\n                valueLimitPerUse: layer.valueLimitPerUse ?? 0n,\n                expression: anyOf([expression, layerExpression]),\n            }\n            : p),\n    };\n}\n/** Add the fee calls to a scoped session; without `approve`, all but the paymaster approve. */\nexport function withFeeActions(actions, sourceTokens, fees, approve = true) {\n    const out = [...actions];\n    // Usage-limited rules go last: a passing limited rule counts even if its\n    // branch then fails.\n    const cap = () => cumulativeOnly(32n, fees.cap);\n    for (const token of sourceTokens) {\n        addFeeBranch(out, token, TRANSFER_SELECTOR, [\n            pin(0n, fees.appFeeCollector),\n            cap(),\n        ]);\n        // approve(paymaster, 0) passes too: tokens like USDT need the reset.\n        if (approve) {\n            addFeeBranch(out, token, APPROVE_SELECTOR, [\n                pin(0n, fees.paymaster),\n                cap(),\n            ]);\n        }\n    }\n    // One cap rule after the OR, so every token draws on the same budget.\n    addFeeBranch(out, fees.paymaster, CALLBACK_ALLOW_MAX_AMOUNT_SELECTOR, sourceTokens.length === 1\n        ? [pin(0n, sourceTokens[0]), cap()]\n        : {\n            type: 'and',\n            left: anyOf(sourceTokens.map((token) => allOf([pin(0n, token)]))),\n            right: allOf([cap()]),\n        });\n    return out;\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/** Require a calldata word to be at least `floor`, per call. */\nexport function atLeast(calldataOffset, floor) {\n    return {\n        condition: 'greaterThanOrEqual',\n        calldataOffset,\n        referenceValue: floor,\n    };\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 * `cumulativeCap` with only the usage limit, which stores one slot fewer.\n *\n * It still bounds each call because the policies count a limited rule under\n * any condition with checked math: `used + value > limit` is refused, and a\n * sum past 2^256 reverts, so both fail closed.\n */\nexport function cumulativeOnly(calldataOffset, cap) {\n    return {\n        condition: 'greaterThanOrEqual',\n        calldataOffset,\n        referenceValue: 0n,\n        usageLimit: cap,\n    };\n}\n/**\n * The least `to`-token amount worth `cap` `from` tokens at `numerator /\n * denominator`, for two 1:1 assets, rescaled between their decimals. Rounded up,\n * so the floor never admits a rate below the one asked for.\n */\nexport function floorFor(cap, numerator, denominator, fromDecimals, toDecimals) {\n    const scaled = cap * numerator * 10n ** BigInt(toDecimals);\n    const unit = denominator * 10n ** BigInt(fromDecimals);\n    return (scaled + unit - 1n) / unit;\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. */\nexport function allOf(rules) {\n    return rules\n        .map((rule) => ({ type: 'rule', rule }))\n        .reduceRight((right, left) => ({ type: 'and', left, right }));\n}\n/** At least one branch must hold. */\nexport function anyOf(branches) {\n    return branches.reduce((left, right) => ({ type: 'or', 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 */\nexport const 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/**\n * Native value each call may carry. Zero for every swap; a bridge that pays\n * its messaging fee in `msg.value` (OFT) raises it.\n */\nvalueLimitPerUse = 0n) {\n    const usable = alternatives.filter((set) => set.length > 0);\n    const policy = usable.length > 0\n        ? {\n            type: 'arg-policy',\n            valueLimitPerUse,\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,\n                rules: rules,\n            }\n            : { type: 'arg-policy', valueLimitPerUse, 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 { floorFor } from './rules.js';\n/**\n * Opt-in stable-swap floor.\n *\n * The Swapper takes its output bound from the caller and its `calls[]` route\n * may call anything, so a capped input alone lets a session key set the bound\n * to zero and route the input away. Pinning the output bound to a\n * floor derived from the cap bounds the rate: worst case floor/cap.\n */\nconst DEFAULT_MAX_SLIPPAGE_BPS = 100;\nconst BPS = 10000n;\n/** The decimals a served USD stablecoin may have; any other is a bad entry. */\nexport const STABLE_DECIMALS = new Set([6, 18]);\n/** Validate a `stableFloor` scope; undefined when the scope does not opt in. */\nexport function resolveStableFloor(scope, sellTokens, stablecoins) {\n    const option = scope.stableFloor;\n    if (option === undefined)\n        return undefined;\n    const maxSlippageBps = option === true ? DEFAULT_MAX_SLIPPAGE_BPS : option.maxSlippageBps;\n    if (!Number.isInteger(maxSlippageBps) ||\n        maxSlippageBps < 0 ||\n        maxSlippageBps >= 10_000) {\n        throw new Error(`swap.stableFloor.maxSlippageBps must be an integer in [0, 10000), got ${maxSlippageBps}`);\n    }\n    if (sellTokens.length !== 1) {\n        throw new Error('swap.stableFloor needs exactly one sell token — the floor is derived ' +\n            \"from one token's cap and decimals\");\n    }\n    if (scope.sell.maxTotal === undefined) {\n        throw new Error('swap.stableFloor needs swap.sell.maxTotal — the floor is a fraction of it');\n    }\n    const nonSwapper = (scope.via ?? []).find((venue) => venue.id !== 'rhinestone');\n    if (nonSwapper) {\n        throw new Error(`swap.stableFloor allows only the Rhinestone Swapper venue, not ${nonSwapper.id}: ` +\n            'a direct aggregator call has no output bound for the floor to pin');\n    }\n    if (stablecoins === undefined) {\n        throw new Error(\"swap.stableFloor needs the orchestrator's stablecoins for this chain to \" +\n            'confirm both tokens are USD stablecoins — create the session with ' +\n            'sdk.createSession on a chain that serves them');\n    }\n    const stable = (token, side) => {\n        const matches = stablecoins.filter((t) => t.address.toLowerCase() === token.toLowerCase());\n        if (matches.length === 0) {\n            throw new Error(`swap.stableFloor: ${side} token ${token} is not a USD stablecoin the orchestrator serves for this chain`);\n        }\n        // Two entries could disagree on decimals, and the floor would silently\n        // take whichever came first.\n        if (matches.length > 1) {\n            throw new Error(`swap.stableFloor: ${side} token ${token} appears ${matches.length} times in the served stablecoins`);\n        }\n        const info = matches[0];\n        // Every served USD stable is 6 or 18; anything else is a bad entry, and a\n        // wrong scale moves the floor by orders of magnitude.\n        if (!STABLE_DECIMALS.has(info.decimals)) {\n            throw new Error(`swap.stableFloor: ${side} token ${token} (${info.symbol}) has ${info.decimals} decimals; expected 6 or 18`);\n        }\n        return info;\n    };\n    return {\n        maxSlippageBps,\n        sellDecimals: stable(sellTokens[0], 'sell').decimals,\n        buyDecimals: stable(scope.buy.token, 'buy').decimals,\n    };\n}\n/**\n * The minimum buy-token output for a swap of up to `cap` sell tokens, rounded\n * up so the floor never admits a rate below the tolerance. Exact-in bounds the\n * output (`out >= in × (1 − bps)`), exact-out the input (`in <= out × (1 + bps)`,\n * so `out >= in ÷ (1 + bps)`): at 100 bps the two floors differ by 1 bp of the\n * cap, and far more at higher tolerances.\n */\nexport function stableFloorAmount(cap, params, direction) {\n    const bps = BigInt(params.maxSlippageBps);\n    const [rateNumerator, rateDenominator] = direction === 'exactIn' ? [BPS - bps, BPS] : [BPS, BPS + bps];\n    return floorFor(cap, rateNumerator, rateDenominator, params.sellDecimals, params.buyDecimals);\n}\nexport const PERMIT2 = '0x000000000022D473030F116dDEE9F6B43aC78BA3';\n/**\n * Refuse a stableFloor session that grants a way to move the sell token around\n * the floor: a user action on the sell token, Permit2 or the Swapper, or an\n * ERC-1271 signing surface (the key could sign a Permit2 transfer no calldata\n * pin ever sees).\n */\nexport function assertStableFloorIsolated(input) {\n    // A permit compiles to its own actions (a SAME_CHAIN_IE permit\n    // is a `transfer` on the source token), which the target check below never sees.\n    if (input.hasCrossChainGrants) {\n        throw new Error('swap.stableFloor cannot be combined with `crossChainPermits`: ' +\n            'their actions could move the sell token without ' +\n            'meeting the floor');\n    }\n    if (input.signingMode !== undefined && input.signingMode !== 'disabled') {\n        throw new Error('swap.stableFloor cannot enable `signing`: an ERC-1271 signature could ' +\n            'move the sell token without meeting the floor');\n    }\n    const guarded = [input.sellToken, PERMIT2, input.swapper].map((a) => a.toLowerCase());\n    const sideDoor = input.userTargets.find((t) => guarded.includes(t.toLowerCase()));\n    if (sideDoor) {\n        throw new Error(`swap.stableFloor: the session also grants an action on ${sideDoor}, ` +\n            'which could move the sell token without meeting the floor');\n    }\n}\n","import { isAddressEqual, toFunctionSelector, zeroAddress, } from 'viem';\nimport { namedParamOffsets } from '../../permissions.js';\nimport { refusal } from '../refusals.js';\nimport { swapperAbi } from '../swap/rhinestone.js';\nimport { cumulativeCap, pin, swapAction, UNIVERSAL_ACTION_MAX_RULES, } from '../swap/rules.js';\nimport { resolveSwapScope } from '../swap/scope.js';\n/**\n * SAME_CHAIN_IE — a smart account settling on its own chain through the\n * IntentExecutor: a plain `transfer` when the token does not change, or a\n * Rhinestone Swapper swap (the existing `swap` scope) with a pinned output\n * floor when it does.\n */\nconst TRANSFER_SELECTOR = toFunctionSelector('transfer(address,uint256)');\nexport const NATIVE_SENTINEL = '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE';\n/**\n * The Swapper's output bound, at the same head word in both entrypoints:\n * `minAmountOut` for `swapExactIn`, `amountOut` for `swapExactOut`.\n */\nexport const SWAPPER_OUTPUT_BOUND_OFFSET = namedParamOffsets(swapperAbi, 'swapExactIn').minAmountOut;\n/**\n * Add a rule to an action's params policy. It must join the existing policy:\n * the chain keeps one config per policy contract and action, so a second\n * policy of the same kind would overwrite the first rather than AND with it.\n */\nexport function withRule(policy, rule) {\n    if (policy.type === 'arg-policy') {\n        return {\n            ...policy,\n            expression: {\n                type: 'and',\n                left: policy.expression,\n                right: { type: 'rule', rule },\n            },\n        };\n    }\n    if (policy.type !== 'universal-action')\n        return policy;\n    if (policy.rules.length < UNIVERSAL_ACTION_MAX_RULES) {\n        return { ...policy, rules: [...policy.rules, rule] };\n    }\n    return {\n        type: 'arg-policy',\n        ...(policy.valueLimitPerUse === undefined\n            ? {}\n            : { valueLimitPerUse: policy.valueLimitPerUse }),\n        expression: [...policy.rules, rule]\n            .map((r) => ({ type: 'rule', rule: r }))\n            .reduceRight((right, left) => ({ type: 'and', left, right })),\n    };\n}\n/** A transfer pinned only to one of several recipients. */\nfunction recipientsOnly(token, recipients) {\n    // swapAction needs shared rules to AND the alternatives onto, so a bare OR\n    // is built here.\n    const expression = recipients\n        .map((recipient) => ({\n        type: 'rule',\n        rule: pin(0n, recipient),\n    }))\n        .reduce((left, right) => ({ type: 'or', left, right }));\n    return {\n        target: token,\n        selector: TRANSFER_SELECTOR,\n        policies: [{ type: 'arg-policy', valueLimitPerUse: 0n, expression }],\n    };\n}\nexport function scopeSameChain(ctx) {\n    if (ctx.sourceTokens.length !== 1) {\n        throw refusal('ONE_SOURCE_TOKEN', 'crossChainPermits: SAME_CHAIN_IE spends one token; give exactly one `from` token on this chain');\n    }\n    const [token] = ctx.sourceTokens;\n    // The orchestrator moves native value as a plain value call or a payable\n    // swap, neither of which these ERC-20 scopes admit.\n    if (isAddressEqual(token, zeroAddress) ||\n        isAddressEqual(token, NATIVE_SENTINEL)) {\n        throw refusal('NATIVE_SOURCE_UNSUPPORTED', 'crossChainPermits: SAME_CHAIN_IE spends an ERC-20; a native `from` token is not supported');\n    }\n    const elsewhere = ctx.destinations.find((leg) => leg.chainId !== ctx.chainId);\n    if (elsewhere) {\n        throw refusal('SAME_CHAIN_IE_OTHER_CHAIN_LEG', `crossChainPermits: SAME_CHAIN_IE settles on chain ${ctx.chainId}; a \\`to\\` leg names chain ${elsewhere.chainId}`, { chainId: elsewhere.chainId, leg: 'to' });\n    }\n    const sameToken = ctx.destinations.map((leg) => isAddressEqual(leg.token, token));\n    if (sameToken.every(Boolean)) {\n        if (ctx.destinations.some((leg) => leg.minAmount !== undefined)) {\n            throw refusal('SAME_CHAIN_IE_TRANSFER_MIN_AMOUNT', 'crossChainPermits: a SAME_CHAIN_IE transfer cannot enforce `to.minAmount`; it applies to a swap');\n        }\n        const rules = ctx.cap === undefined ? [] : [cumulativeCap(32n, ctx.cap)];\n        const recipients = ctx.destinations.map((leg) => leg.recipient);\n        const account = ctx.account;\n        // The orchestrator never transfers a token to the account that holds it.\n        if (account &&\n            recipients.every((r) => r !== undefined && isAddressEqual(r, account))) {\n            throw refusal('SAME_CHAIN_IE_TRANSFER_TO_SELF', 'crossChainPermits: a SAME_CHAIN_IE transfer to the account itself never settles; name another recipient');\n        }\n        // An open leg ('any', opted into with allowRecipientNotAccount) lifts the\n        // recipient pin for the whole transfer.\n        const pinned = recipients.every((r) => r !== undefined)\n            ? recipients\n            : [];\n        if (pinned.length === 0 && rules.length === 0) {\n            throw refusal('SAME_CHAIN_IE_ANY_RECIPIENT_NEEDS_MAX_AMOUNT', \"crossChainPermits: a SAME_CHAIN_IE transfer to 'any' recipient needs maxAmount; otherwise it authorises every transfer of the token\");\n        }\n        const action = pinned.length <= 1\n            ? swapAction(token, TRANSFER_SELECTOR, [\n                ...rules,\n                ...pinned.map((recipient) => pin(0n, recipient)),\n            ])\n            : rules.length > 0\n                ? swapAction(token, TRANSFER_SELECTOR, rules, pinned.map((recipient) => [pin(0n, recipient)]))\n                : recipientsOnly(token, pinned);\n        return { actions: [action], permissions: [] };\n    }\n    if (sameToken.some(Boolean) || ctx.destinations.length !== 1) {\n        throw refusal('SAME_CHAIN_IE_TRANSFER_OR_SINGLE_SWAP', 'crossChainPermits: SAME_CHAIN_IE either transfers the `from` token or swaps it into exactly one `to` token');\n    }\n    const [leg] = ctx.destinations;\n    if (leg.recipient === undefined) {\n        throw refusal('RECIPIENT_ANY_UNPINNABLE', \"crossChainPermits: a SAME_CHAIN_IE swap needs a concrete recipient; 'any' cannot pin the swap output\");\n    }\n    // The key passes the Swapper's output bound and its route, so without a\n    // floor it could route the pulled input anywhere and accept nothing back.\n    if (leg.minAmount === undefined || leg.minAmount <= 0n) {\n        throw refusal('SAME_CHAIN_IE_SWAP_NEEDS_MIN_AMOUNT', 'crossChainPermits: a SAME_CHAIN_IE swap needs a positive `to.minAmount` to bound what the swap must deliver');\n    }\n    // The floor is a fixed amount, not a price: only against a capped input does\n    // maxAmount : minAmount bound the rate, over one swap or a lifetime of them.\n    if (ctx.cap === undefined) {\n        throw refusal('SAME_CHAIN_IE_SWAP_NEEDS_MAX_AMOUNT', 'crossChainPermits: a SAME_CHAIN_IE swap needs maxAmount; the floor bounds the rate only against a capped input');\n    }\n    const swap = resolveSwapScope({\n        sell: {\n            token,\n            ...(ctx.cap === undefined ? {} : { maxTotal: ctx.cap }),\n        },\n        buy: { token: leg.token },\n        to: leg.recipient,\n    }, ctx.chainId, ctx.environment);\n    const floor = {\n        condition: 'greaterThanOrEqual',\n        calldataOffset: SWAPPER_OUTPUT_BOUND_OFFSET,\n        referenceValue: leg.minAmount,\n    };\n    return {\n        // The bare venue emits only Swapper entrypoints; the floor goes on every\n        // action so none can run without it.\n        actions: swap.actions.map((action) => {\n            const policies = action.policies ?? [];\n            // The floor rides on the params policy; an action without one would run\n            // unfloored.\n            if (!policies.some((p) => p.type === 'universal-action' || p.type === 'arg-policy')) {\n                throw new Error('crossChainPermits (internal): a SAME_CHAIN_IE swap action has no params policy to carry its floor');\n            }\n            return {\n                ...action,\n                policies: policies.map((policy) => withRule(policy, floor)),\n            };\n        }),\n        permissions: swap.permissions,\n    };\n}\n","import { toFunctionSelector } from 'viem';\nimport { namedParamOffsets } from '../../permissions.js';\nimport { FYND_CHAIN_IDS, FYND_ROUTERS } from './fynd.js';\nimport { atLeast, 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 `offsets.test.ts`:\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: `singleSwap(amountIn, tokenIn, tokenOut,\n * expectedAmountOut, minAmountOut, receiver, ...)`, its head starting at 708.\n * The receiver is the Swapper itself, which collects the output and forwards\n * it to the scope's recipient, so that is what gets pinned rather than the end\n * recipient.\n */\nconst NESTED_FYND_TOKEN_IN_OFFSET = 740n;\nconst NESTED_FYND_TOKEN_OUT_OFFSET = 772n;\nconst NESTED_FYND_RECEIVER_OFFSET = 868n;\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, outputParam, direction) => {\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        // Before the cap: usage-limited rules go last so the order stays safe if\n        // these rules ever land in an ArgPolicy AND branch.\n        if (ctx.minOut !== undefined) {\n            rules.push(atLeast(offsets[outputParam], ctx.minOut[direction]));\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', 'minAmountOut', 'exactIn'), assertSellTokenPinned(alternativesFor(EXACT_IN))),\n            swapAction(swapper, SWAP_EXACT_OUT_SELECTOR, rulesFor(EXACT_OUT, 'amountInMax', 'amountOut', 'exactOut'), assertSellTokenPinned(alternativesFor(EXACT_OUT))),\n        ],\n    };\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 V3 per chain — the contract fynd's encoded fills target.\n *\n * Mirrors the first router of each chain's `fynd.routers` in yeet's\n * `config/quoters.jsonnet`. A chain is listed only when the router is\n * whitelisted in `IntentExecutionPolicy`, since a quoter enabled without a\n * whitelisted target produces quotes that revert.\n */\nexport const FYND_ROUTERS = {\n    1: '0x1644d2477f809cc2c71bccfd6dc9497e3f83210d',\n    56: '0x7f3d12bbafb8955e51b3ab9588b34c8ad95bda4e',\n    130: '0xcba5574597ad00ea250fd106dab4fc7461949635',\n    137: '0xbd4e6011f03355c2a377fd9af939322a7d0a1bc1',\n    8453: '0xaba5b53b03eafad1c5fc8bd5fc765fc85bb3de67',\n    9745: '0x0953c7e23b44259e5e5630e9b97c31d7278c4c85',\n    42161: '0x924f147c50ea59f5180a26031a8b65b2aa1e81cd',\n};\n/**\n * TychoRouterV3 `singleSwap`, the entrypoint fynd's encoded quotes call.\n *\n * Names are upstream's (`TychoRouterV3.sol` and its `ClientFeeParams` struct,\n * propeller-heads/tycho at tag 0.387.0); the types are pinned by\n * {@link FYND_SWAP_SELECTOR}'s assertion in the test suite. We never address\n * `clientFeeParams`: a tuple containing `bytes` is dynamic and sits behind a\n * 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: 'expectedAmountOut', type: 'uint256' },\n            { name: 'minAmountOut', type: 'uint256' },\n            { name: 'receiver', type: 'address' },\n            {\n                name: 'clientFeeParams',\n                type: 'tuple',\n                components: [\n                    { name: 'clientFeeBps', type: 'uint32' },\n                    { name: 'clientFeeReceiver', type: 'address' },\n                    { name: 'maxClientContribution', type: 'uint256' },\n                    { name: 'deadline', type: 'uint256' },\n                    { name: 'clientSignature', type: 'bytes' },\n                ],\n            },\n            { name: 'swapData', 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","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 { resolveStableFloor, stableFloorAmount } from './stable-floor.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', stablecoins) {\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 stableFloor = resolveStableFloor(scope, sellTokens, stablecoins);\n    const ctxFor = (venue) => {\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        const cap = venue.maxSpend ?? scope.sell.maxTotal;\n        return {\n            chainId,\n            environment,\n            sellTokens,\n            buyToken: scope.buy.token,\n            recipient: scope.to,\n            cap,\n            // Derived from the cap this action enforces, so floor/cap stays the\n            // worst rate even under a venue-level `maxSpend`.\n            ...(stableFloor && cap !== undefined\n                ? {\n                    minOut: {\n                        exactIn: stableFloorAmount(cap, stableFloor, 'exactIn'),\n                        exactOut: stableFloorAmount(cap, stableFloor, 'exactOut'),\n                    },\n                }\n                : {}),\n        };\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 { isAddressEqual } from 'viem';\nimport { recipientNotAllowed } from '../cross-chain-permits.js';\nimport { RefusalCollectionHalted, recover, refusal, refuser, } from '../refusals.js';\nimport { allOf, anyOf, cumulativeCap, pin, swapAction } from '../swap/rules.js';\nimport { PERMIT2 } from '../swap/stable-floor.js';\nimport { scopeCctp } from './cctp.js';\nimport { scopeEco } from './eco.js';\nimport { APPROVE_SELECTOR, servedFees, swapApprovesAsActions, withFeeActions, } from './fees.js';\nimport { requireFloorsWithinCaps } from './floor.js';\nimport { scopeLz } from './lz.js';\nimport { scopeOft } from './oft.js';\nimport { scopeSameChain } from './same-chain.js';\nimport { SettlementLayerRefusal, served } from './served.js';\n/**\n * Settlement-scoped cross-chain permits.\n *\n * A permit that names IntentExecutor layers compiles to scoped actions with\n * its recipient, destination chain, token and amount pinned in each layer's\n * calldata. Those pins only bind when nothing else can run, so such a session\n * is restricted: the wildcard fallback is dropped and only the layers'\n * settlement calls and their shared approve remain. `ACROSS` beside them adds\n * Permit2 as one more spender of that approve; its claim is bound from the\n * ERC-1271 list.\n */\n/** Each layer's settlement contract on a chain and the scoped call it makes. */\n// SAME_CHAIN_IE has no fixed target: it transfers the token itself or reuses the\n// swap scope, so it is resolved before this table.\nconst LAYERS = {\n    CCTP: {\n        target: (settlement, chainId) => served(settlement, chainId, 'cctp').tokenMessenger,\n        scope: scopeCctp,\n    },\n    OFT: {\n        target: (settlement, chainId) => served(settlement, chainId, 'oft').adapter,\n        scope: scopeOft,\n        requiresOneTimeUse: true,\n        floorsDelivery: true,\n    },\n    ECO_IE: {\n        target: (settlement, chainId) => served(settlement, chainId, 'eco').portal,\n        scope: scopeEco,\n        floorsDelivery: true,\n    },\n    LZ: {\n        target: (settlement, chainId) => served(settlement, chainId, 'lz').multiCall,\n        spender: (settlement, chainId) => served(settlement, chainId, 'lz').transferDelegate,\n        scope: scopeLz,\n        requiresOneTimeUse: true,\n        floorsDelivery: true,\n    },\n};\nexport const INTENT_EXECUTOR_SETTLEMENT_LAYERS = [\n    'CCTP',\n    'OFT',\n    'ECO_IE',\n    'SAME_CHAIN_IE',\n    'LZ',\n];\nexport function isIntentExecutorLayer(layer) {\n    return INTENT_EXECUTOR_SETTLEMENT_LAYERS.includes(layer);\n}\n/** The bridging layers, in the order a session compiles them; `'all'` names each. */\nconst CROSS_CHAIN_LAYERS = ['CCTP', 'OFT', 'ECO_IE', 'LZ'];\nexport function isSettlementScopedPermit(permit) {\n    return (permit.settlementLayers === 'all' ||\n        (permit.settlementLayers?.some(isIntentExecutorLayer) ?? false));\n}\nexport function resolveSettlementScope(permits, options) {\n    const scoped = permits.filter(isSettlementScopedPermit);\n    if (scoped.length === 0)\n        return undefined;\n    if (scoped.length !== permits.length) {\n        throw refusal('MIXED_PERMIT_KINDS', 'crossChainPermits: a session cannot mix IntentExecutor-layer permits with Permit2-layer permits', {\n            permitIndex: permits.findIndex((permit) => !isSettlementScopedPermit(permit)),\n        });\n    }\n    if (scoped.length > 1) {\n        throw refusal('MULTIPLE_INTENT_EXECUTOR_PERMITS', 'crossChainPermits: give at most one IntentExecutor-layer permit per session', { permitIndex: permits.indexOf(scoped[1]) });\n    }\n    const [permit] = scoped;\n    const permitIndex = permits.indexOf(permit);\n    const refuse = refuser(options.collect, { permitIndex });\n    // A refusal that leaves nothing valid to scope ends the dry run here.\n    const scope = recover(refuse, () => scopePermit(permit, options, refuse));\n    if (scope === undefined)\n        throw new RefusalCollectionHalted();\n    return scope;\n}\nfunction scopePermit(permit, options, refuse) {\n    const named = permit.settlementLayers;\n    const all = named === 'all';\n    const layers = all ? [...CROSS_CHAIN_LAYERS] : (named ?? []);\n    const across = options.across !== undefined && !options.across.dropped;\n    const permit2Layers = layers.filter((layer) => !isIntentExecutorLayer(layer) && !(across && layer === 'ACROSS'));\n    if (permit2Layers.length) {\n        throw refusal('PERMIT2_LAYER_WITH_INTENT_EXECUTOR_LAYER', `crossChainPermits: ${permit2Layers.join(', ')} cannot share a permit with IntentExecutor layers`);\n    }\n    const requested = [...new Set(layers.filter(isIntentExecutorLayer))];\n    // SAME_CHAIN_IE's transfer or swap shares no call shape with a bridge.\n    if ((requested.length > 1 || across) && requested.includes('SAME_CHAIN_IE')) {\n        throw refusal('SAME_CHAIN_IE_WITH_OTHER_LAYERS', `crossChainPermits: SAME_CHAIN_IE cannot share a permit with ${across ? 'ACROSS' : 'other IntentExecutor layers'}`);\n    }\n    const fromLegs = (permit.from ?? []).filter((leg) => leg.chain.id === options.chainId);\n    if (fromLegs.length === 0) {\n        throw refusal('NO_FROM_ON_CHAIN', `crossChainPermits: the permit names no \\`from\\` token on chain ${options.chainId}`, { chainId: options.chainId });\n    }\n    const caps = fromLegs.flatMap(({ maxAmount }) => maxAmount === undefined ? [] : [maxAmount]);\n    if (caps.length > 1) {\n        refuse(refusal('MULTIPLE_MAX_AMOUNTS', 'crossChainPermits: give maxAmount on at most one `from` token per chain', { chainId: options.chainId, leg: 'from' }));\n    }\n    const cap = caps[0];\n    const sourceTokens = fromLegs.map(({ token }) => token);\n    const recipientIsAccount = permit.recipientIsAccount ?? true;\n    const resolveRecipient = (recipient) => {\n        if (recipient === 'any') {\n            if (recipientIsAccount)\n                throw recipientNotAllowed(recipient);\n            return undefined;\n        }\n        if (recipient === undefined || recipientIsAccount) {\n            if (!options.account) {\n                throw refusal('RECIPIENT_NEEDS_ACCOUNT', 'crossChainPermits: pinning the recipient to the account needs `account` on the session definition');\n            }\n            if (recipient !== undefined &&\n                !isAddressEqual(recipient, options.account)) {\n                throw recipientNotAllowed(recipient);\n            }\n            return options.account;\n        }\n        return recipient;\n    };\n    // Without a destination pin the key picks the domain, and a burn to a domain\n    // where the recipient cannot mint (e.g. Solana, whose recipient is an ATA)\n    // is lost.\n    if (!permit.to?.length) {\n        throw refusal('MISSING_TO', 'crossChainPermits: an IntentExecutor-layer permit must name its `to` chains');\n    }\n    // fillDeadline bounds a Permit2 claim; no IntentExecutor layer carries one,\n    // so 'all' keeps ACROSS alone.\n    const fillDeadlineDrops = Boolean(permit.fillDeadline?.length && all && across);\n    if (permit.fillDeadline?.length && !fillDeadlineDrops) {\n        refuse(refusal('FILL_DEADLINE_ONLY_PERMIT2', 'crossChainPermits: fillDeadline applies only to Permit2 layers'));\n    }\n    const destinations = permit.to.map(({ chain, token, recipient, minAmount }) => ({\n        chainId: chain.id,\n        token,\n        recipient: resolveRecipient(recipient),\n        ...(minAmount === undefined ? {} : { minAmount }),\n    }));\n    const sameChainOnly = requested[0] === 'SAME_CHAIN_IE';\n    // Only ECO_IE prices its delivery against the reward; elsewhere the field would\n    // be silently ignored.\n    if (permit.maxFeeBps !== undefined && !requested.includes('ECO_IE')) {\n        refuse(refusal('MAX_FEE_BPS_ONLY_ECO_IE', 'crossChainPermits: maxFeeBps applies only to ECO_IE'));\n    }\n    // Every layer in the permit must enforce `to.minAmount`, or the key would\n    // settle around it: scopeLayer refuses one that cannot (CCTP never can).\n    const minAmount = permit.to.some((leg) => leg.minAmount !== undefined);\n    if (minAmount && !sameChainOnly && options.settlement) {\n        const settlement = options.settlement;\n        recover(refuse, () => requireFloorsWithinCaps(permit, settlement));\n    }\n    // A dry run that refuses the fee addresses goes on to check the layers.\n    const fees = permit.allowFees\n        ? recover(refuse, () => servedFees(options.settlement, options.chainId, sourceTokens))\n        : undefined;\n    if (sameChainOnly) {\n        const settlementLayers = requested;\n        const sameChain = scopeSameChain({\n            chainId: options.chainId,\n            environment: options.environment,\n            account: options.account,\n            sourceTokens,\n            destinations,\n            cap,\n        });\n        if (fees === undefined) {\n            return { ...sameChain, settlementLayers, dropped: [] };\n        }\n        // A swap's approve is a permission; as a raw action the paymaster approve can\n        // join it. Only the swap shape has permissions.\n        const actions = [\n            ...sameChain.actions,\n            ...swapApprovesAsActions(sameChain.permissions, cap),\n        ];\n        return {\n            actions: withFeeActions(actions, sourceTokens, fees),\n            permissions: [],\n            settlementLayers,\n            dropped: [],\n        };\n    }\n    // No bundled fallback: the orchestrator is the one source for these addresses.\n    // SAME_CHAIN_IE pins none of them, so only the layers below need it.\n    const settlement = options.settlement;\n    if (settlement === undefined) {\n        throw refusal('SETTLEMENT_CATALOG_MISSING', \"crossChainPermits: IntentExecutor layers and 'all' (the default) need options.settlement from GET /chains; pass it or name settlementLayers, e.g. ['ACROSS']\");\n    }\n    const fromCaps = (permit.from ?? []).map(({ maxAmount }) => maxAmount);\n    // ECO_IE pins Eco's deadlines under the earlier of the permit's validUntil and\n    // the one-time-use deadline.\n    const validUntil = permit.validUntil === undefined ||\n        (options.sessionDeadline !== undefined &&\n            options.sessionDeadline < permit.validUntil)\n        ? options.sessionDeadline\n        : permit.validUntil;\n    const scopeLayer = (layer) => {\n        if (fillDeadlineDrops) {\n            throw new SettlementLayerRefusal('crossChainPermits: fillDeadline applies only to Permit2 layers', { code: 'FILL_DEADLINE_ONLY_PERMIT2' });\n        }\n        if (LAYERS[layer].requiresOneTimeUse && !options.oneTimeUse) {\n            throw new SettlementLayerRefusal(`crossChainPermits: an ${layer} permit requires oneTimeUse`, { code: 'LAYER_REQUIRES_ONE_TIME_USE' });\n        }\n        if (minAmount && !LAYERS[layer].floorsDelivery) {\n            throw new SettlementLayerRefusal(`crossChainPermits: ${layer} cannot enforce \\`to.minAmount\\``, { code: 'MIN_AMOUNT_NOT_ENFORCEABLE' });\n        }\n        const target = LAYERS[layer].target(settlement, options.chainId);\n        const spender = LAYERS[layer].spender?.(settlement, options.chainId) ?? target;\n        const action = LAYERS[layer].scope({\n            chainId: options.chainId,\n            settlement,\n            target,\n            account: options.account,\n            sourceTokens,\n            destinations,\n            cap,\n            fromCaps,\n            ...(permit.maxFeeBps === undefined\n                ? {}\n                : { maxFeeBps: permit.maxFeeBps }),\n            ...(validUntil === undefined ? {} : { validUntil }),\n        });\n        return { layer, spender, action };\n    };\n    // An explicit list is strict: a layer that cannot scope throws. 'all' keeps\n    // only the layers that can; any other error still throws. A fixed order keeps\n    // the session the same however the layers were listed.\n    const skipped = new Map(options.across?.dropped ? [['ACROSS', options.across.dropped]] : []);\n    const scopedLayers = CROSS_CHAIN_LAYERS.filter((layer) => requested.includes(layer)).flatMap((layer) => {\n        if (!all) {\n            const scopedLayer = recover((error) => refuse(error, { layer }), () => scopeLayer(layer));\n            return scopedLayer === undefined ? [] : [scopedLayer];\n        }\n        try {\n            return [scopeLayer(layer)];\n        }\n        catch (error) {\n            if (!(error instanceof SettlementLayerRefusal))\n                throw error;\n            skipped.set(layer, error.message.replace(/^crossChainPermits: /, ''));\n            return [];\n        }\n    });\n    // Only a dry run gets here with no named layer scoped; it has recorded why.\n    if (!all && scopedLayers.length === 0)\n        throw new RefusalCollectionHalted();\n    const ecoSkipped = skipped.get('ECO_IE');\n    if (permit.maxFeeBps !== undefined && ecoSkipped !== undefined) {\n        refuse(refusal('MAX_FEE_BPS_ECO_IE_UNAVAILABLE', `crossChainPermits: maxFeeBps asks for ECO_IE, which cannot settle this permit: ${ecoSkipped}`, { layer: 'ECO_IE' }));\n    }\n    if (scopedLayers.length === 0 && !across) {\n        throw refusal('NO_LAYER_CAN_SETTLE', `crossChainPermits: no ${options.across ? '' : 'IntentExecutor '}layer can settle this permit on chain ${options.chainId} (${[\n            ...skipped,\n        ]\n            .map(([layer, reason]) => `${layer}: ${reason}`)\n            .join('; ')})`, { chainId: options.chainId });\n    }\n    // Each layer's call allows one send, but one burning transaction admits both,\n    // and each pays a native fee no pin bounds.\n    const feePaying = scopedLayers.filter(({ layer }) => LAYERS[layer].requiresOneTimeUse);\n    if (feePaying.length > 1) {\n        refuse(refusal('MULTIPLE_FEE_PAYING_LAYERS', `crossChainPermits: ${feePaying.map(({ layer }) => layer).join(' and ')} each pay a native LayerZero fee, so a permit may use only one of them; name the layers to keep`));\n    }\n    const settlementLayers = [\n        ...(across ? ['ACROSS'] : []),\n        ...scopedLayers.map(({ layer }) => layer),\n    ];\n    // Permit2 joins the one approve, so ACROSS draws on the same maxAmount.\n    const spenders = [\n        ...scopedLayers.map(({ spender }) => spender),\n        ...(across ? [PERMIT2] : []),\n    ].filter((spender, i, list) => list.findIndex((other) => isAddressEqual(other, spender)) === i);\n    // Without allowFees, only the layers' own approves: an unsponsored intent or\n    // one carrying an app fee adds calls this session does not authorise.\n    // Cumulative: the burning transaction admits every op after the burn, and a\n    // reusable session every later intent, so a per-call bound would let\n    // repeated approves grant the cap many times. Each layer call keeps its own\n    // counter; this one is what bounds them together, for the session's life.\n    const capRules = cap === undefined ? [] : [cumulativeCap(32n, cap)];\n    const spenderPins = anyOf(spenders.map((s) => allOf([pin(0n, s)])));\n    const approveActions = sourceTokens.map((token) => spenders.length === 1\n        ? swapAction(token, APPROVE_SELECTOR, [\n            pin(0n, spenders[0]),\n            ...capRules,\n        ])\n        : {\n            target: token,\n            selector: APPROVE_SELECTOR,\n            policies: [\n                {\n                    type: 'arg-policy',\n                    valueLimitPerUse: 0n,\n                    // One cap rule after the spender OR: the chain counts usage per\n                    // rule, so every layer draws on the same budget.\n                    expression: cap === undefined\n                        ? spenderPins\n                        : {\n                            type: 'and',\n                            left: spenderPins,\n                            right: allOf(capRules),\n                        },\n                },\n            ],\n        });\n    const actions = [\n        ...scopedLayers.map(({ action }) => action),\n        ...approveActions,\n    ];\n    return {\n        actions: fees === undefined\n            ? actions\n            : withFeeActions(actions, sourceTokens, fees),\n        permissions: [],\n        settlementLayers,\n        dropped: [...skipped].map(([layer, reason]) => ({ layer, reason })),\n    };\n}\n","import { isAddressEqual, pad, toFunctionSelector, } from 'viem';\nimport { namedParamOffsets } from '../../permissions.js';\nimport { cumulativeCap, pin, pinValue, pinWord, swapAction, } from '../swap/rules.js';\nimport { SettlementLayerRefusal, served } from './served.js';\n/**\n * CCTP V2 — `TokenMessengerV2.depositForBurnWithHook`, encoded by the\n * orchestrator against a fixed Circle deployment, so every field the session\n * pins is a static head word.\n */\nexport const tokenMessengerAbi = [\n    {\n        type: 'function',\n        name: 'depositForBurnWithHook',\n        stateMutability: 'nonpayable',\n        inputs: [\n            { name: 'amount', type: 'uint256' },\n            { name: 'destinationDomain', type: 'uint32' },\n            { name: 'mintRecipient', type: 'bytes32' },\n            { name: 'burnToken', type: 'address' },\n            { name: 'destinationCaller', type: 'bytes32' },\n            { name: 'maxFee', type: 'uint256' },\n            { name: 'minFinalityThreshold', type: 'uint32' },\n            { name: 'hookData', type: 'bytes' },\n        ],\n        outputs: [],\n    },\n];\nexport const DEPOSIT_FOR_BURN_WITH_HOOK_SELECTOR = toFunctionSelector(tokenMessengerAbi[0]);\nconst BURN = namedParamOffsets(tokenMessengerAbi, 'depositForBurnWithHook');\n/**\n * CCTP moves only native USDC, so any other token names a route it cannot take.\n * Solana (domain 5) is never served: its `mintRecipient` is the recipient's ATA.\n */\nfunction requireUsdc(settlement, chainId, token, leg) {\n    if (!isAddressEqual(token, served(settlement, chainId, 'cctp').usdc)) {\n        throw new SettlementLayerRefusal(`crossChainPermits: CCTP moves only USDC; the \\`${leg}\\` token on chain ${chainId} is ${token}`, { code: 'TOKEN_NOT_ROUTED', chainId, leg });\n    }\n}\n/** The burn call, pinned to the permit's token, destinations and cap. */\nexport function scopeCctp(ctx) {\n    if (ctx.sourceTokens.length !== 1) {\n        throw new SettlementLayerRefusal('crossChainPermits: CCTP burns one token (USDC) per chain; give exactly one `from` token on this chain', { code: 'ONE_SOURCE_TOKEN', chainId: ctx.chainId });\n    }\n    requireUsdc(ctx.settlement, ctx.chainId, ctx.sourceTokens[0], 'from');\n    const rules = [\n        pin(BURN.burnToken, ctx.sourceTokens[0]),\n        // A non-zero destinationCaller restricts who may mint; the orchestrator\n        // never sets one, so any other value is not a settlement it built.\n        pinValue(BURN.destinationCaller, 0n),\n    ];\n    if (ctx.cap !== undefined)\n        rules.push(cumulativeCap(BURN.amount, ctx.cap));\n    const legs = ctx.destinations.map((leg) => {\n        requireUsdc(ctx.settlement, leg.chainId, leg.token, 'to');\n        const legRules = [\n            pinValue(BURN.destinationDomain, BigInt(served(ctx.settlement, leg.chainId, 'cctp').domain)),\n        ];\n        if (leg.recipient !== undefined) {\n            legRules.push(pinWord(BURN.mintRecipient, pad(leg.recipient)));\n        }\n        return legRules;\n    });\n    // One destination keeps its pins in the shared AND; several become an OR of\n    // (domain, recipient) pairs so a recipient is only valid on its own chain.\n    return legs.length === 1\n        ? swapAction(ctx.target, DEPOSIT_FOR_BURN_WITH_HOOK_SELECTOR, [\n            ...rules,\n            ...legs[0],\n        ])\n        : swapAction(ctx.target, DEPOSIT_FOR_BURN_WITH_HOOK_SELECTOR, rules, legs);\n}\n","const REFUSAL = {\n    cctp: 'CCTP does not route to',\n    oft: 'OFT does not route to',\n    eco: 'ECO_IE does not route to',\n    lz: 'LZ does not route from',\n};\n/** A layer cannot settle the permit here; `settlementLayers: 'all'` drops it. */\nexport class SettlementLayerRefusal extends Error {\n    constructor(message, details) {\n        super(message);\n        Object.assign(this, details);\n    }\n}\n/** The chain's served block for a layer; a chain without one does not route it. */\nexport function served(settlement, chainId, layer) {\n    const block = settlement[chainId]?.[layer];\n    if (block === undefined) {\n        throw new SettlementLayerRefusal(`crossChainPermits: ${REFUSAL[layer]} chain ${chainId}`, { code: 'LAYER_NOT_SERVED', chainId });\n    }\n    return block;\n}\n","import { concat, isAddressEqual, pad, parseAbi, slice, toFunctionSelector, } from 'viem';\nimport { compareHexValues } from '../../ordering.js';\nimport { cumulativeCap, floorFor, pin, pinValue, pinWord } from '../swap/rules.js';\nimport { STABLE_DECIMALS } from '../swap/stable-floor.js';\nimport { SettlementLayerRefusal, served } from './served.js';\n/**\n * ECO — Eco Routes, `Portal.publishAndFund` with Eco's quoted route bytes\n * forwarded verbatim by the orchestrator.\n *\n * The session pins the one shape the orchestrator accepts: an ERC-20 reward and\n * a single `transfer` delivery, with every calldata pointer and count pinned so\n * no field can alias another. The route's own pointers and byte length are\n * not: the destination Portal fills only a route whose `abi.encode` hash\n * matches, so any other layout never fills and refunds to the pinned creator\n * after the reward deadline. This assumes EVM destinations. An unpinned route\n * token count or call value reverts at fill: the only other canonical count\n * names address 1, which has no code, and served stablecoins' `transfer` is\n * non-payable.\n *\n * `valueLimitPerUse: 0` holds `msg.value` at 0, so the account never pays more\n * than the capped reward. A key can fill its own intent and name itself\n * claimant, so the delivery floor (`maxFeeBps` or `to.minAmount`, the higher\n * when both) is the whole price bound.\n */\nexport const ecoPortalAbi = parseAbi([\n    'function publishAndFund(uint64 destination, bytes route, (uint64 deadline,address creator,address prover,uint256 nativeAmount,(address token,uint256 amount)[] tokens) reward, bool allowPartial) payable returns (bytes32 intentHash, address vault)',\n]);\nexport const PUBLISH_AND_FUND_SELECTOR = toFunctionSelector(ecoPortalAbi[0]);\nconst TRANSFER_SELECTOR = toFunctionSelector('transfer(address,uint256)');\n/**\n * Offsets from the start of `publishAndFund`'s args for the canonical encoding\n * of an ERC-20 reward and a route that delivers one token by one `transfer`.\n */\nexport const PUBLISH = {\n    destination: 0n,\n    routePointer: 32n,\n    rewardPointer: 64n,\n    allowPartial: 96n,\n    routeLength: 128n,\n    routeTuplePointer: 160n,\n    routeDeadline: 224n,\n    routePortal: 256n,\n    routeNativeAmount: 288n,\n    routeTokensPointer: 320n,\n    routeCallsPointer: 352n,\n    routeTokensLength: 384n,\n    routeToken: 416n,\n    routeTokenAmount: 448n,\n    callsLength: 480n,\n    callPointer: 512n,\n    callTarget: 544n,\n    callDataPointer: 576n,\n    callValue: 608n,\n    callDataLength: 640n,\n    /** The `transfer` selector and the first 28 bytes of its recipient word. */\n    callDataHead: 672n,\n    transferRecipient: 676n,\n    transferAmount: 708n,\n    rewardDeadline: 768n,\n    rewardCreator: 800n,\n    rewardProver: 832n,\n    rewardNativeAmount: 864n,\n    rewardTokensPointer: 896n,\n    rewardTokensLength: 928n,\n    rewardToken: 960n,\n    rewardAmount: 992n,\n};\nconst BPS = 10000n;\n/**\n * How far ahead a set `validUntil` must reach: the session pins Eco's reward\n * deadline under it, and the orchestrator publishes Eco's quoted deadline about\n * 7 days out.\n */\nexport const ECO_MIN_VALIDITY_SECONDS = 7n * 24n * 60n * 60n;\n/**\n * Eco's solvers deliver only the stablecoins it serves on a chain; any other\n * token never fills and locks the reward until its deadline.\n */\nfunction requireServed(settlement, chainId, token, leg) {\n    if (!served(settlement, chainId, 'eco').stablecoins.some((t) => isAddressEqual(t, token))) {\n        throw new SettlementLayerRefusal(`crossChainPermits: ECO_IE moves only USD stablecoins; the \\`${leg}\\` token on chain ${chainId} is ${token}`, { code: 'TOKEN_NOT_ROUTED', chainId, leg });\n    }\n}\n/**\n * The decimals of a served Eco stablecoin the `maxFeeBps` floor prices 1:1, as\n * the served `usdStablecoins` vouch for them. Eco's bare address list carries\n * none, and the permit's own word is not taken.\n */\nfunction stableDecimals(settlement, chainId, token, leg) {\n    const usd = (settlement[chainId]?.usdStablecoins ?? []).filter((t) => isAddressEqual(t.address, token));\n    const refuse = (why) => new SettlementLayerRefusal(`crossChainPermits: ECO_IE prices reward against delivery 1:1, so the \\`${leg}\\` token ${token} on chain ${chainId} must be a served USD stablecoin with known decimals; ${why}`, { code: 'ECO_IE_STABLECOIN_DECIMALS', chainId, leg });\n    if (usd.length === 0) {\n        throw refuse('the orchestrator serves no usdStablecoins entry for it');\n    }\n    // Two entries could disagree, and the floor would take whichever came first.\n    if (usd.length > 1) {\n        throw refuse(`it appears ${usd.length} times in usdStablecoins`);\n    }\n    // A wrong scale moves the floor by orders of magnitude.\n    if (!STABLE_DECIMALS.has(usd[0].decimals)) {\n        throw refuse(`it has ${usd[0].decimals} decimals; expected 6 or 18`);\n    }\n    return usd[0].decimals;\n}\n/** The token's served decimals when `stableDecimals` would accept them. */\nexport function knownDecimals(settlement, chainId, token) {\n    const usd = (settlement[chainId]?.usdStablecoins ?? []).filter((t) => isAddressEqual(t.address, token));\n    return usd.length === 1 && STABLE_DECIMALS.has(usd[0].decimals)\n        ? usd[0].decimals\n        : undefined;\n}\n/**\n * Provers served on both chains of a leg. An unlisted prover could attest a\n * fill that never happened; one with no code on the source chain makes\n * `refund` revert and locks the reward.\n */\nexport function proversBetween(settlement, source, destination) {\n    const there = served(settlement, destination, 'eco').provers;\n    // Sorted so the policy, and so the permissionId, ignores the served order.\n    return served(settlement, source, 'eco')\n        .provers.filter((prover) => there.some((p) => isAddressEqual(p, prover)))\n        .map((prover) => prover.toLowerCase())\n        .sort(compareHexValues);\n}\n/** The word holding `transfer`'s selector and the head of its recipient. */\nfunction transferHead(recipient) {\n    return concat([TRANSFER_SELECTOR, slice(pad(recipient), 0, 28)]);\n}\nconst allOf = (rules) => rules\n    .map((rule) => ({ type: 'rule', rule }))\n    .reduceRight((right, left) => ({ type: 'and', left, right }));\nconst anyOf = (branches) => branches.reduce((left, right) => ({ type: 'or', left, right }));\nconst allOfExpressions = (parts) => parts.reduceRight((right, left) => ({ type: 'and', left, right }));\n/**\n * The same check on the same word; a usage-limited rule is never the same, as\n * hoisted out of the leg OR it would count calls its branch never admits.\n */\nexport const sameRule = (a, b) => a.usageLimit === undefined &&\n    b.usageLimit === undefined &&\n    a.condition === b.condition &&\n    a.calldataOffset === b.calldataOffset &&\n    BigInt(a.referenceValue) === BigInt(b.referenceValue);\n/** The publish call, pinned to the permit's destinations, provers and prices. */\nexport function scopeEco(ctx) {\n    if (ctx.sourceTokens.length !== 1) {\n        throw new SettlementLayerRefusal('crossChainPermits: ECO_IE funds one reward token per chain; give exactly one `from` token on this chain', { code: 'ONE_SOURCE_TOKEN', chainId: ctx.chainId });\n    }\n    // `maxFeeBps` prices the reward 1:1 against delivery; without it every leg's\n    // owner-set `to.minAmount` is the floor, in that leg's own token.\n    requireServed(ctx.settlement, ctx.chainId, ctx.sourceTokens[0], 'from');\n    const fromDecimals = ctx.maxFeeBps === undefined\n        ? undefined\n        : stableDecimals(ctx.settlement, ctx.chainId, ctx.sourceTokens[0], 'from');\n    if (!ctx.account) {\n        throw new SettlementLayerRefusal('crossChainPermits: ECO_IE refunds an unfilled reward to the account, so the session definition needs `account`', { code: 'ACCOUNT_REQUIRED' });\n    }\n    // The key fills its own intent and names itself claimant, so a floor on\n    // delivery is all that stops a reward paying for next to nothing.\n    if (ctx.cap === undefined ||\n        (ctx.maxFeeBps === undefined &&\n            ctx.destinations.some((leg) => leg.minAmount === undefined))) {\n        throw new SettlementLayerRefusal('crossChainPermits: ECO_IE needs maxAmount and maxFeeBps to bound what a reward must deliver (or maxAmount and a `to.minAmount` on every leg)', { code: 'ECO_IE_NEEDS_MAX_AMOUNT_AND_FEE' });\n    }\n    if (ctx.destinations.some((leg) => leg.minAmount !== undefined && leg.minAmount <= 0n)) {\n        throw new SettlementLayerRefusal('crossChainPermits: ECO_IE needs a positive `to.minAmount`', { code: 'MIN_AMOUNT_NOT_POSITIVE', leg: 'to' });\n    }\n    if (ctx.maxFeeBps !== undefined &&\n        (!Number.isInteger(ctx.maxFeeBps) ||\n            ctx.maxFeeBps < 0 ||\n            ctx.maxFeeBps >= 10_000)) {\n        throw new SettlementLayerRefusal('crossChainPermits: maxFeeBps must be an integer in [0, 10000)', { code: 'MAX_FEE_BPS_OUT_OF_RANGE' });\n    }\n    // `validUntil` is the earlier of the permit's and oneTimeUse's. Both\n    // deadlines stay unpinned only when neither is set: an unfilled reward then\n    // has no refund deadline.\n    const validUntil = ctx.validUntil;\n    const now = BigInt(Math.floor(Date.now() / 1000));\n    if (validUntil !== undefined && validUntil < now + ECO_MIN_VALIDITY_SECONDS) {\n        throw new SettlementLayerRefusal(\"crossChainPermits: ECO_IE needs validUntil at least 7 days ahead: Eco's reward deadline is ~7 days out and the session pins it\", { code: 'ECO_IE_VALIDITY_TOO_SHORT' });\n    }\n    // Each source chain's session floors its own capped reward with the same\n    // absolute amount, so it bounds the rate only where every cap is the same.\n    if (ctx.maxFeeBps === undefined && new Set(ctx.fromCaps ?? []).size > 1) {\n        throw new SettlementLayerRefusal('crossChainPermits: an ECO_IE `to.minAmount` floors every source chain alike, so `from` legs with different maxAmount need maxFeeBps, which scales with each cap', { code: 'ECO_IE_FLOOR_NEEDS_EQUAL_CAPS' });\n    }\n    const cap = ctx.cap;\n    const maxFeeBps = ctx.maxFeeBps;\n    const rules = [\n        pinValue(PUBLISH.routePointer, 0x80n),\n        pinValue(PUBLISH.rewardPointer, 0x300n),\n        pinValue(PUBLISH.callsLength, 1n),\n        pinValue(PUBLISH.callDataLength, 0x44n),\n        pin(PUBLISH.rewardCreator, ctx.account),\n        pinValue(PUBLISH.rewardTokensPointer, 0xa0n),\n        pinValue(PUBLISH.rewardTokensLength, 1n),\n        pin(PUBLISH.rewardToken, ctx.sourceTokens[0]),\n        cumulativeCap(PUBLISH.rewardAmount, cap),\n        ...(validUntil === undefined\n            ? []\n            : [\n                {\n                    condition: 'lessThanOrEqual',\n                    calldataOffset: PUBLISH.rewardDeadline,\n                    referenceValue: validUntil,\n                },\n                // The route deadline bounds when a solver may still fill; the\n                // session's window bounds the whole settlement, not just its refund.\n                {\n                    condition: 'lessThanOrEqual',\n                    calldataOffset: PUBLISH.routeDeadline,\n                    referenceValue: validUntil,\n                },\n            ]),\n    ];\n    // Two legs that pin the same delivery become an OR, so the lower floor binds.\n    const twin = ctx.destinations.find((leg, i) => ctx.destinations.some((other, j) => j < i &&\n        other.chainId === leg.chainId &&\n        isAddressEqual(other.token, leg.token) &&\n        (other.recipient === undefined || leg.recipient === undefined\n            ? other.recipient === leg.recipient\n            : isAddressEqual(other.recipient, leg.recipient)) &&\n        other.minAmount !== leg.minAmount));\n    if (twin) {\n        throw new SettlementLayerRefusal(`crossChainPermits: ECO_IE names the \\`to\\` leg ${twin.token} on chain ${twin.chainId} twice with different \\`to.minAmount\\`; give it once`, { code: 'CONFLICTING_LEG_FLOORS', chainId: twin.chainId, leg: 'to' });\n    }\n    const legs = ctx.destinations.map((leg) => {\n        requireServed(ctx.settlement, leg.chainId, leg.token, 'to');\n        // The cap less what the solver may keep, rescaled from the reward's\n        // decimals to the delivery's; with `to.minAmount` too, the stricter wins.\n        const feeFloor = maxFeeBps === undefined || fromDecimals === undefined\n            ? 0n\n            : floorFor(cap, BPS - BigInt(maxFeeBps), BPS, fromDecimals, stableDecimals(ctx.settlement, leg.chainId, leg.token, 'to'));\n        const floor = leg.minAmount !== undefined && leg.minAmount > feeFloor\n            ? leg.minAmount\n            : feeFloor;\n        if (leg.recipient === undefined) {\n            throw new SettlementLayerRefusal(\"crossChainPermits: ECO_IE needs a concrete recipient; 'any' cannot pin the route's transfer\", { code: 'RECIPIENT_ANY_UNPINNABLE', chainId: leg.chainId, leg: 'to' });\n        }\n        const provers = proversBetween(ctx.settlement, ctx.chainId, leg.chainId);\n        if (provers.length === 0) {\n            throw new SettlementLayerRefusal(`crossChainPermits: no Eco prover is deployed on both chain ${ctx.chainId} and chain ${leg.chainId}`, { code: 'ECO_IE_NO_SHARED_PROVER', chainId: leg.chainId, leg: 'to' });\n        }\n        const legRules = [\n            pinValue(PUBLISH.destination, BigInt(leg.chainId)),\n            pin(PUBLISH.routePortal, served(ctx.settlement, leg.chainId, 'eco').portal),\n            pin(PUBLISH.routeToken, leg.token),\n            pin(PUBLISH.callTarget, leg.token),\n            pinWord(PUBLISH.callDataHead, transferHead(leg.recipient)),\n            pinWord(PUBLISH.transferRecipient, pad(leg.recipient)),\n            {\n                condition: 'greaterThanOrEqual',\n                calldataOffset: PUBLISH.routeTokenAmount,\n                referenceValue: floor,\n            },\n            {\n                condition: 'greaterThanOrEqual',\n                calldataOffset: PUBLISH.transferAmount,\n                referenceValue: floor,\n            },\n        ];\n        return { rules: legRules, provers };\n    });\n    // What every leg pins moves out of the OR, stored once instead of per leg:\n    // (A and X) or (A and Y) is A and (X or Y).\n    const shared = legs[0].rules.filter((rule) => legs.every((leg) => leg.rules.some((other) => sameRule(other, rule))));\n    const sharedProvers = legs.every((leg) => leg.provers.length === legs[0].provers.length &&\n        leg.provers.every((prover, i) => prover === legs[0].provers[i]));\n    // The prover OR nests inside its leg, so the rule count grows with legs\n    // plus provers rather than their product.\n    const proverOr = (provers) => anyOf(provers.map((prover) => allOf([pin(PUBLISH.rewardProver, prover)])));\n    const branches = legs.map((leg) => {\n        const own = leg.rules.filter((rule) => !shared.some((other) => sameRule(other, rule)));\n        return [\n            ...(own.length ? [allOf(own)] : []),\n            ...(sharedProvers ? [] : [proverOr(leg.provers)]),\n        ];\n    });\n    const expression = [\n        allOf([...rules, ...shared]),\n        ...(sharedProvers ? [proverOr(legs[0].provers)] : []),\n        // A leg left with nothing of its own admits everything the others do.\n        ...(branches.some((branch) => branch.length === 0)\n            ? []\n            : [anyOf(branches.map(allOfExpressions))]),\n    ];\n    return {\n        target: ctx.target,\n        selector: PUBLISH_AND_FUND_SELECTOR,\n        policies: [\n            {\n                type: 'arg-policy',\n                valueLimitPerUse: 0n,\n                expression: allOfExpressions(expression),\n            },\n        ],\n    };\n}\n","import { refusal } from '../refusals.js';\nimport { floorFor } from '../swap/rules.js';\nimport { knownDecimals } from './eco.js';\n/**\n * Every bridged token is a USD stablecoin, so a `to.minAmount` outside\n * [maxAmount / 2, maxAmount] of any capped `from` leg is a units mistake. It is\n * a hard error, never a dropped layer: 'all' must not keep a floor of dust.\n * Pairs whose decimals the orchestrator does not serve are not judged.\n */\nexport function requireFloorsWithinCaps(permit, settlement) {\n    for (const to of permit.to ?? []) {\n        const toDecimals = knownDecimals(settlement, to.chain.id, to.token);\n        for (const from of permit.from ?? []) {\n            const fromDecimals = knownDecimals(settlement, from.chain.id, from.token);\n            if (to.minAmount === undefined ||\n                from.maxAmount === undefined ||\n                toDecimals === undefined ||\n                fromDecimals === undefined) {\n                continue;\n            }\n            const cap = from.maxAmount;\n            const at = (num, den) => floorFor(cap, num, den, fromDecimals, toDecimals);\n            if (to.minAmount < at(1n, 2n) || to.minAmount > at(1n, 1n)) {\n                throw refusal('MIN_AMOUNT_OUTSIDE_CAP', `crossChainPermits: \\`to.minAmount\\` ${to.minAmount} on chain ${to.chain.id} must be between half of and all of the chain ${from.chain.id} maxAmount; give it in the \\`to\\` token's smallest units (${toDecimals} decimals)`, { chainId: to.chain.id, leg: 'to' });\n            }\n        }\n    }\n}\n","import { isAddressEqual, maxUint64, maxUint256, pad, toFunctionSelector, } from 'viem';\nimport { allOf, anyOf, atLeast, cumulativeCap, pin, pinValue, pinWord, } from '../swap/rules.js';\nimport { OFT_SEND_SELECTOR, SEND } from './oft.js';\nimport { SettlementLayerRefusal, served } from './served.js';\n/**\n * LZ — USDC over the LayerZero Value Transfer API: `approve(TransferDelegate)`\n * then `LZMultiCall.execute(calls, quoteId)`. LZMultiCall runs any call it is\n * handed, so every nested call's shape and redirectable argument is pinned,\n * except what LZMultiCall or the target already refuses (see `batch` and\n * `pull`). Two routes are accepted: CCTP, and Stargate TAXI only into a leg no\n * CCTP route reaches (CCTP is cheaper there); BUS is refused.\n *\n * A Stargate send's `minAmountLD` is pinned only against an owner-given\n * `to.minAmount`: the amount sent varies, and a rule compares with a constant.\n */\n/**\n * Circle's TokenMessengerV2, which the API's CCTP route approves and burns\n * through on every mainnet. `/chains` does not serve it inside `lz.cctp`, and\n * Plasma has no `cctp` block to borrow it from.\n */\nconst LZ_CCTP_TOKEN_MESSENGER = '0x28b5a0e9C621a5BadaA536219b3a228C8168cf5d';\n/**\n * The most relay fee the key may send LayerZero's receiver, in USDC units:\n * ~10x the live fee into Ethereum, the dearest destination.\n */\nexport const LZ_CCTP_MAX_RELAY_FEE = 1000000n;\nexport const LZ_EXECUTE_SELECTOR = toFunctionSelector('execute((address,uint256,bytes)[],bytes32)');\nconst DELEGATE_TRANSFER_FROM = toFunctionSelector('delegateTransferFrom(address,address,address,uint256)');\nconst APPROVE = toFunctionSelector('approve(address,uint256)');\nconst TRANSFER = toFunctionSelector('transfer(address,uint256)');\nconst DEPOSIT_FOR_BURN = toFunctionSelector('depositForBurn(uint256,uint32,bytes32,address,bytes32,uint256,uint32)');\nconst SWEEP = toFunctionSelector('sweep(address[],address)');\nconst ceil32 = (n) => BigInt(Math.ceil(n / 32) * 32);\nconst and = (terms) => terms.reduceRight((right, left) => ({ type: 'and', left, right }));\n/**\n * The same check on the same word. A usage-limited rule is never the same: one\n * hoisted out of an OR would count on every call, not only when its branch runs.\n */\nexport const sameRule = (a, b) => a.usageLimit === undefined &&\n    b.usageLimit === undefined &&\n    a.condition === b.condition &&\n    a.calldataOffset === b.calldataOffset &&\n    BigInt(a.referenceValue) === BigInt(b.referenceValue);\n/**\n * The pins of an `execute` batch under the canonical encoding, below the\n * `calls` pointer every route shares, and each call's argument accessor.\n */\nfunction batch(calls) {\n    const rules = [pinValue(0x40n, BigInt(calls.length))];\n    const args = [];\n    let relative = BigInt(calls.length) * 32n;\n    calls.forEach((call, i) => {\n        const start = 0x60n + relative;\n        const data = start + 128n;\n        const at = (offset) => data + 4n + offset;\n        // No call's value is pinned: the send's is the messaging fee, and every\n        // other target is non-payable, a revert LZMultiCall bubbles.\n        rules.push(pinValue(0x60n + BigInt(i) * 32n, relative), pin(start, call.target), pinValue(start + 64n, 0x60n), \n        // The word ending at the selector: the length's low 28 bytes, then the\n        // selector. A length above 2^224 fails to decode, so this pins both.\n        ...(call.shapeChecked\n            ? []\n            : [\n                pinValue(data - 28n, (BigInt(call.length) << 32n) | BigInt(call.selector)),\n            ]), ...call.args(at));\n        args.push(at);\n        relative += 128n + ceil32(call.length);\n    });\n    return { rules, args };\n}\n/** The execute call, pinned to the permit's destinations, recipients and cap. */\nexport function scopeLz(ctx) {\n    if (ctx.sourceTokens.length !== 1) {\n        throw new SettlementLayerRefusal('crossChainPermits: LZ moves one token (USDC) per chain; give exactly one `from` token on this chain', { code: 'ONE_SOURCE_TOKEN', chainId: ctx.chainId });\n    }\n    const account = ctx.account;\n    if (!account) {\n        throw new SettlementLayerRefusal('crossChainPermits: LZ sweeps what it does not bridge back to the account, so the session definition needs `account`', { code: 'ACCOUNT_REQUIRED' });\n    }\n    const [token] = ctx.sourceTokens;\n    const source = served(ctx.settlement, ctx.chainId, 'lz');\n    const { multiCall, transferDelegate } = source;\n    const servedLz = (leg) => ctx.settlement[leg.chainId]?.lz;\n    const cap = (offset) => ctx.cap === undefined ? [] : [cumulativeCap(offset, ctx.cap)];\n    const crossChain = (leg) => leg.chainId !== ctx.chainId;\n    const recipient = (offset, leg) => leg.recipient === undefined ? [] : [pinWord(offset, pad(leg.recipient))];\n    // LZMultiCall routes a call to its own TransferDelegate through\n    // `_handleTransfer`, which reverts unless the data is 132 bytes of\n    // `delegateTransferFrom` pulling from the caller, the account.\n    const pull = {\n        target: transferDelegate,\n        selector: DELEGATE_TRANSFER_FROM,\n        length: 132,\n        shapeChecked: true,\n        args: (at) => [pin(at(0n), token), pin(at(64n), multiCall)],\n    };\n    const sweep = {\n        target: multiCall,\n        selector: SWEEP,\n        length: 164,\n        args: (at) => [\n            pinValue(at(0n), 0x40n),\n            pin(at(32n), account),\n            pinValue(at(64n), 2n),\n            pin(at(96n), token),\n            pinValue(at(128n), 0n),\n        ],\n    };\n    const approve = (spender) => ({\n        target: token,\n        selector: APPROVE,\n        length: 68,\n        args: (at) => [pin(at(0n), spender)],\n    });\n    const routes = [];\n    const cctp = source.cctp;\n    const cctpFrom = cctp !== undefined && isAddressEqual(token, cctp.token);\n    // A route exists where both chains carry its block.\n    const cctpLinks = (leg) => cctpFrom && crossChain(leg) && servedLz(leg)?.cctp !== undefined;\n    // A leg whose token CCTP does not mint, such as a Stargate USDC, stays\n    // Stargate's.\n    const cctpReaches = (leg) => {\n        const dst = servedLz(leg)?.cctp;\n        return cctpLinks(leg) && !!dst && isAddressEqual(leg.token, dst.token);\n    };\n    const decimals = (chainId, address) => ctx.settlement[chainId]?.usdStablecoins?.find((t) => isAddressEqual(t.address, address))?.decimals;\n    // The floor is a constant in `minAmountLD`, so it must reach the pool as the\n    // owner meant it: on a Stargate send, in units both legs share.\n    const requireStargateFloor = (leg, minAmount, reached) => {\n        if (minAmount <= 0n) {\n            throw new SettlementLayerRefusal('crossChainPermits: an LZ `to.minAmount` must be positive', { code: 'MIN_AMOUNT_NOT_POSITIVE', chainId: leg.chainId, leg: 'to' });\n        }\n        // Stargate casts `minAmountLD` in shared decimals to uint64; a larger floor\n        // would revert every send.\n        if (minAmount > maxUint64) {\n            throw new SettlementLayerRefusal('crossChainPermits: an LZ `to.minAmount` above uint64 cannot be met by any Stargate send', { code: 'MIN_AMOUNT_ABOVE_UINT64', chainId: leg.chainId, leg: 'to' });\n        }\n        // Legs are ORed, so a second leg into the chain would admit the send\n        // without this floor.\n        if (reached.some((other) => other !== leg && other.chainId === leg.chainId)) {\n            throw new SettlementLayerRefusal(`crossChainPermits: a floored LZ leg must be the only \\`to\\` leg on chain ${leg.chainId}; give one \\`to\\` leg per chain`, { code: 'LZ_FLOORED_LEG_NOT_ALONE', chainId: leg.chainId, leg: 'to' });\n        }\n        // depositForBurn takes a maxFee, not a minimum out, so no word carries it.\n        if (cctpReaches(leg)) {\n            throw new SettlementLayerRefusal(`crossChainPermits: LZ pins \\`to.minAmount\\` only on a Stargate send, and chain ${leg.chainId} is reached over CCTP`, { code: 'LZ_FLOOR_ON_CCTP_ROUTE', chainId: leg.chainId, leg: 'to' });\n        }\n        // Stargate reads `minAmountLD` in source units and pays out in destination\n        // units; only equal decimals keep the floor in the `to` token's units.\n        const from = decimals(ctx.chainId, token);\n        const to = decimals(leg.chainId, leg.token);\n        if (from === undefined || to === undefined || from !== to) {\n            throw new SettlementLayerRefusal(`crossChainPermits: an LZ \\`to.minAmount\\` needs the \\`from\\` and \\`to\\` tokens served with equal decimals; chain ${ctx.chainId} serves ${from ?? 'none'}, chain ${leg.chainId} ${to ?? 'none'}`, { code: 'FLOOR_DECIMALS_MISMATCH', chainId: leg.chainId, leg: 'to' });\n        }\n    };\n    const stargate = source.stargateUsdc;\n    if (stargate !== undefined && isAddressEqual(token, stargate.token)) {\n        const send = {\n            target: stargate.pool,\n            selector: OFT_SEND_SELECTOR,\n            length: 484,\n            args: (at) => [\n                pinValue(at(SEND.sendParamPointer), 0x80n),\n                // The fee is native only; the refund returns to LZMultiCall, whose\n                // sweep forwards it to the account.\n                pinValue(at(SEND.lzTokenFee), 0n),\n                pin(at(SEND.refundAddress), multiCall),\n                // A zero-amount send still costs the account the LayerZero fee.\n                {\n                    condition: 'greaterThan',\n                    calldataOffset: at(SEND.amountLD),\n                    referenceValue: 0n,\n                },\n                pinValue(at(SEND.extraOptionsPointer), 0xe0n),\n            ],\n        };\n        const calls = [pull, approve(stargate.pool), send, sweep];\n        const { rules, args } = batch(calls);\n        const s = args[2];\n        // TAXI: extraOptions 0x0003, composeMsg and oftCmd empty. No native drop,\n        // no compose.\n        rules.push(pinValue(s(SEND.composeMsgPointer), 0x120n), pinValue(s(SEND.oftCmdPointer), 0x140n), pinValue(s(0x160n), 2n), pinValue(s(0x180n), 0x0003n << 240n), pinValue(s(0x1a0n), 0n), pinValue(s(0x1c0n), 0n));\n        const reaches = (leg) => crossChain(leg) &&\n            servedLz(leg)?.stargateUsdc !== undefined &&\n            !cctpReaches(leg);\n        routes.push({\n            rules,\n            calls: calls.length,\n            reaches,\n            leg: (leg) => {\n                const dst = servedLz(leg)?.stargateUsdc;\n                if (!reaches(leg) || !dst || !isAddressEqual(leg.token, dst.token))\n                    return undefined;\n                return [\n                    pinValue(s(SEND.dstEid), BigInt(dst.eid)),\n                    ...recipient(s(SEND.to), leg),\n                    ...(leg.minAmount === undefined\n                        ? []\n                        : [atLeast(s(SEND.minAmountLD), leg.minAmount)]),\n                ];\n            },\n            limits: cap(args[0](96n)),\n        });\n    }\n    if (cctpFrom) {\n        const burn = {\n            target: LZ_CCTP_TOKEN_MESSENGER,\n            selector: DEPOSIT_FOR_BURN,\n            length: 228,\n            // `burnToken` is not pinned: the pull and the sweep are pinned to this\n            // token and the account, so another burn token can only spend what a\n            // third party left in LZMultiCall, and the pull is swept back.\n            args: (at) => [\n                // A non-zero destinationCaller restricts who may mint; the API never\n                // sets one.\n                pinValue(at(128n), 0n),\n            ],\n        };\n        const fee = {\n            target: token,\n            selector: TRANSFER,\n            length: 68,\n            args: (at) => [pin(at(0n), cctp.feeReceiver)],\n        };\n        const maxFee = ctx.cap !== undefined && ctx.cap < LZ_CCTP_MAX_RELAY_FEE\n            ? ctx.cap\n            : LZ_CCTP_MAX_RELAY_FEE;\n        for (const feeless of [false, true]) {\n            const calls = feeless\n                ? [pull, approve(LZ_CCTP_TOKEN_MESSENGER), burn, sweep]\n                : [pull, fee, approve(LZ_CCTP_TOKEN_MESSENGER), burn, sweep];\n            const { rules, args } = batch(calls);\n            const b = args[calls.indexOf(burn)];\n            const reaches = (leg) => cctpLinks(leg) && (servedLz(leg)?.cctp?.feeless === true) === feeless;\n            routes.push({\n                rules,\n                calls: calls.length,\n                reaches,\n                leg: (leg) => {\n                    const dst = servedLz(leg)?.cctp;\n                    if (!reaches(leg) || !dst || !isAddressEqual(leg.token, dst.token))\n                        return undefined;\n                    return [\n                        pinValue(b(32n), BigInt(dst.domain)),\n                        ...recipient(b(64n), leg),\n                    ];\n                },\n                limits: [\n                    ...cap(args[0](96n)),\n                    // The fee goes to LayerZero's receiver, so the key cannot keep it;\n                    // the ceiling bounds how much of the pull it can waste there.\n                    ...(feeless ? [] : [cumulativeCap(args[1](32n), maxFee)]),\n                ],\n            });\n        }\n    }\n    if (routes.length === 0) {\n        throw new SettlementLayerRefusal(`crossChainPermits: LZ moves only USDC; the \\`from\\` token on chain ${ctx.chainId} is ${token}`, { code: 'TOKEN_NOT_ROUTED', chainId: ctx.chainId, leg: 'from' });\n    }\n    // A leg no route from this chain reaches is another chain's business in a\n    // multi-chain permit; one it reaches with a token no route delivers is an error.\n    const legs = ctx.destinations.filter((leg) => routes.some((route) => route.reaches(leg)));\n    for (const leg of legs) {\n        if (routes.every((route) => route.leg(leg) === undefined)) {\n            throw new SettlementLayerRefusal(`crossChainPermits: LZ delivers only USDC; the \\`to\\` token on chain ${leg.chainId} is ${leg.token}`, { code: 'TOKEN_NOT_ROUTED', chainId: leg.chainId, leg: 'to' });\n        }\n        if (leg.minAmount !== undefined)\n            requireStargateFloor(leg, leg.minAmount, legs);\n    }\n    const branches = routes.flatMap((route) => {\n        const pinned = legs.flatMap((leg) => {\n            const rules = route.leg(leg);\n            return rules ? [rules] : [];\n        });\n        if (pinned.length === 0)\n            return [];\n        return [\n            {\n                route,\n                rest: [\n                    anyOf(pinned.map(allOf)),\n                    ...(route.limits.length ? [allOf(route.limits)] : []),\n                ],\n            },\n        ];\n    });\n    if (branches.length === 0) {\n        throw new SettlementLayerRefusal(`crossChainPermits: LZ has no route from chain ${ctx.chainId} to any \\`to\\` chain`, { code: 'LZ_NO_ROUTE', chainId: ctx.chainId });\n    }\n    // A pure pin that every branch of a group carries (`group.every`) is checked\n    // once, ahead of their OR; that alone makes it sound. Grouping by call count\n    // only picks the batches likely to share pins.\n    const groups = [...new Set(branches.map(({ route }) => route.calls))].map((calls) => {\n        const group = branches.filter(({ route }) => route.calls === calls);\n        const shared = group[0].route.rules.filter((rule) => group.every(({ route }) => route.rules.some((r) => sameRule(r, rule))));\n        const own = group.map(({ route, rest }) => {\n            const left = route.rules.filter((r) => !shared.some((s) => sameRule(s, r)));\n            return and([...(left.length ? [allOf(left)] : []), ...rest]);\n        });\n        return and([...(shared.length ? [allOf(shared)] : []), anyOf(own)]);\n    });\n    return {\n        target: multiCall,\n        selector: LZ_EXECUTE_SELECTOR,\n        policies: [\n            {\n                type: 'arg-policy',\n                // `msg.value` carries the Stargate messaging fee; the sweep returns any\n                // overpayment to the account.\n                valueLimitPerUse: maxUint256,\n                expression: {\n                    type: 'and',\n                    // A usage limit on the shared calls pointer: one execute per session,\n                    // so a stale TransferDelegate allowance cannot fund a second route.\n                    left: allOf([{ ...pinValue(0n, 0x40n), usageLimit: 0x40n }]),\n                    right: anyOf(groups),\n                },\n            },\n        ],\n    };\n}\n","import { isAddressEqual, maxUint64, maxUint256, pad, toFunctionSelector, } from 'viem';\nimport { atLeast, cumulativeCap, pin, pinValue, pinWord, swapAction, } from '../swap/rules.js';\nimport { SettlementLayerRefusal, served } from './served.js';\n/**\n * OFT — USDT0 over LayerZero, `OFTAdapter.send` encoded by the orchestrator\n * with empty `extraOptions`, `composeMsg` and `oftCmd`.\n *\n * `send` takes a dynamic tuple, so its fields sit at fixed offsets only under\n * the canonical encoding. The head pointer, the three tail pointers and the\n * three tail lengths are pinned too: that fixes the layout, and the empty tails\n * rule out a LayerZero native drop (paid from the account's `msg.value`) or a\n * compose call on the destination.\n */\nexport const oftAbi = [\n    {\n        type: 'function',\n        name: 'send',\n        stateMutability: 'payable',\n        inputs: [\n            {\n                name: '_sendParam',\n                type: 'tuple',\n                components: [\n                    { name: 'dstEid', type: 'uint32' },\n                    { name: 'to', type: 'bytes32' },\n                    { name: 'amountLD', type: 'uint256' },\n                    { name: 'minAmountLD', type: 'uint256' },\n                    { name: 'extraOptions', type: 'bytes' },\n                    { name: 'composeMsg', type: 'bytes' },\n                    { name: 'oftCmd', type: 'bytes' },\n                ],\n            },\n            {\n                name: '_fee',\n                type: 'tuple',\n                components: [\n                    { name: 'nativeFee', type: 'uint256' },\n                    { name: 'lzTokenFee', type: 'uint256' },\n                ],\n            },\n            { name: '_refundAddress', type: 'address' },\n        ],\n        outputs: [],\n    },\n];\nexport const OFT_SEND_SELECTOR = toFunctionSelector(oftAbi[0]);\n/** Offsets from the start of `send`'s args under the canonical encoding. */\nexport const SEND = {\n    sendParamPointer: 0n,\n    lzTokenFee: 64n,\n    refundAddress: 96n,\n    dstEid: 128n,\n    to: 160n,\n    amountLD: 192n,\n    minAmountLD: 224n,\n    extraOptionsPointer: 256n,\n    composeMsgPointer: 288n,\n    oftCmdPointer: 320n,\n    extraOptionsLength: 352n,\n    composeMsgLength: 384n,\n    oftCmdLength: 416n,\n};\n/**\n * The mesh moves only USDT0, so any other token names a route it cannot take.\n * USDT0 takes no fee and removes no dust (6 local and 6 shared decimals), so\n * `send` delivers exactly `amountLD` and an unfloored `minAmountLD` costs\n * nothing. An OFT that takes a fee or removes dust delivers less, down to the\n * key's `minAmountLD`: serving one needs `to.minAmount` on every leg.\n */\nfunction requireUsdt0(settlement, chainId, token, leg) {\n    if (!isAddressEqual(token, served(settlement, chainId, 'oft').token)) {\n        throw new SettlementLayerRefusal(`crossChainPermits: OFT moves only USDT0; the \\`${leg}\\` token on chain ${chainId} is ${token}`, { code: 'TOKEN_NOT_ROUTED', chainId, leg });\n    }\n}\n/**\n * `send` reverts unless it delivers at least `minAmountLD`, so a floor on that\n * word floors the delivery. It is a fixed amount, since a rule compares with a\n * constant, not with `amountLD`. `minAmountLD` is in the source token's\n * decimals and `to.minAmount` in the destination's, so both must be served\n * and equal.\n */\nfunction floorMinAmount(ctx, leg, minAmount) {\n    const decimals = (chainId, token) => ctx.settlement[chainId]?.usdStablecoins?.find((t) => isAddressEqual(t.address, token))?.decimals;\n    const from = decimals(ctx.chainId, ctx.sourceTokens[0]);\n    const to = decimals(leg.chainId, leg.token);\n    if (from === undefined || from !== to) {\n        throw new SettlementLayerRefusal(`crossChainPermits: an OFT \\`to.minAmount\\` needs served, equal decimals for the \\`from\\` token on chain ${ctx.chainId} (${from ?? 'not served'}) and the \\`to\\` token on chain ${leg.chainId} (${to ?? 'not served'})`, { code: 'FLOOR_DECIMALS_MISMATCH', chainId: leg.chainId, leg: 'to' });\n    }\n    if (minAmount <= 0n) {\n        throw new SettlementLayerRefusal('crossChainPermits: an OFT `to.minAmount` must be positive', { code: 'MIN_AMOUNT_NOT_POSITIVE', chainId: leg.chainId, leg: 'to' });\n    }\n    // USDT0 sends amounts as uint64 in shared decimals; a larger floor admits no\n    // send.\n    if (minAmount > maxUint64) {\n        throw new SettlementLayerRefusal('crossChainPermits: an OFT `to.minAmount` above uint64 cannot be met by any send', { code: 'MIN_AMOUNT_ABOVE_UINT64', chainId: leg.chainId, leg: 'to' });\n    }\n    return atLeast(SEND.minAmountLD, minAmount);\n}\n/** The send call, pinned to the permit's destinations, refund and cap. */\nexport function scopeOft(ctx) {\n    if (ctx.sourceTokens.length !== 1) {\n        throw new SettlementLayerRefusal('crossChainPermits: OFT sends one token (USDT0) per chain; give exactly one `from` token on this chain', { code: 'ONE_SOURCE_TOKEN', chainId: ctx.chainId });\n    }\n    requireUsdt0(ctx.settlement, ctx.chainId, ctx.sourceTokens[0], 'from');\n    if (!ctx.account) {\n        throw new SettlementLayerRefusal('crossChainPermits: OFT refunds its LayerZero fee to the account, so the session definition needs `account`', { code: 'ACCOUNT_REQUIRED' });\n    }\n    const rules = [\n        // Counts its own value against a limit of that value: one send per session.\n        // The burning transaction admits every later op, and each send costs a\n        // native fee no pin bounds.\n        { ...pinValue(SEND.sendParamPointer, 0x80n), usageLimit: 0x80n },\n        pinValue(SEND.extraOptionsPointer, 0xe0n),\n        pinValue(SEND.composeMsgPointer, 0x100n),\n        pinValue(SEND.oftCmdPointer, 0x120n),\n        pinValue(SEND.extraOptionsLength, 0n),\n        pinValue(SEND.composeMsgLength, 0n),\n        pinValue(SEND.oftCmdLength, 0n),\n        // The fee is native only.\n        pinValue(SEND.lzTokenFee, 0n),\n        pin(SEND.refundAddress, ctx.account),\n        // A zero-amount send still costs the account the full LayerZero fee.\n        {\n            condition: 'greaterThan',\n            calldataOffset: SEND.amountLD,\n            referenceValue: 0n,\n        },\n    ];\n    if (ctx.cap !== undefined)\n        rules.push(cumulativeCap(SEND.amountLD, ctx.cap));\n    // Legs whose sends look alike are alternatives the key picks from, so a\n    // looser floor on one would open the other.\n    ctx.destinations.forEach((leg, i) => {\n        const twin = ctx.destinations\n            .slice(i + 1)\n            .find((other) => other.chainId === leg.chainId &&\n            (other.recipient === undefined ||\n                leg.recipient === undefined ||\n                isAddressEqual(other.recipient, leg.recipient)) &&\n            other.minAmount !== leg.minAmount);\n        if (twin) {\n            throw new SettlementLayerRefusal(`crossChainPermits: two OFT \\`to\\` legs on chain ${leg.chainId} admit the same send but set different \\`minAmount\\`s`, { code: 'CONFLICTING_LEG_FLOORS', chainId: leg.chainId, leg: 'to' });\n        }\n    });\n    const legs = ctx.destinations.map((leg) => {\n        requireUsdt0(ctx.settlement, leg.chainId, leg.token, 'to');\n        const legRules = [\n            pinValue(SEND.dstEid, BigInt(served(ctx.settlement, leg.chainId, 'oft').eid)),\n        ];\n        if (leg.recipient !== undefined) {\n            legRules.push(pinWord(SEND.to, pad(leg.recipient)));\n        }\n        if (leg.minAmount !== undefined) {\n            legRules.push(floorMinAmount(ctx, leg, leg.minAmount));\n        }\n        return legRules;\n    });\n    // `msg.value` carries the LayerZero fee, whose size the session cannot know;\n    // the refund pin returns any overpayment to the account.\n    return legs.length === 1\n        ? swapAction(ctx.target, OFT_SEND_SELECTOR, [...rules, ...legs[0]], [], maxUint256)\n        : swapAction(ctx.target, OFT_SEND_SELECTOR, rules, legs, maxUint256);\n}\n","import { domainSeparator, zeroHash } from 'viem';\nimport { encodeErc7739ContentType } from './erc7739.js';\nimport { encodeSessionPolicy } from './policies/encode.js';\nimport { FAR_FUTURE_MS } from './policies/time-frame.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    // Rounded up, so the window never opens early.\n    const validAfter = dateSeconds(input.validAfter ?? new Date(0), 'validAfter', Math.ceil);\n    const validUntil = dateSeconds(input.validUntil ?? new Date(FAR_FUTURE_MS), 'validUntil');\n    if (validUntil <= validAfter) {\n        throw new Error('Session signing validAfter must be earlier than validUntil');\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, round = Math.floor) {\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 = round(milliseconds / 1000);\n    if (milliseconds < 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 { isHyperCoreWireId } from '../../chains/caip2.js';\nimport { buildSmartSessionMockSignature } from '../../modules/validators/smart-sessions/mock-signature.js';\nimport { buildOneTimeUseBurnOp } from '../../modules/validators/smart-sessions/one-time-use.js';\nimport { assertOneTimeUseIdPolicyDeployed } from '../../modules/validators/smart-sessions/policies/addresses.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, input.runtime.identity.address);\n    for (const chain of chains) {\n        const once = selection.byChain[chain.id]?.session.oneTimeUse;\n        if (once?.defaultPolicy)\n            assertOneTimeUseIdPolicyDeployed(once.policy, chain.id);\n    }\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 ||\n            selected.session.hasExplicitPermissions ||\n            Boolean(selected.session.oneTimeUse);\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 forbidsPreClaim = (resolved) => resolved.session.claimPolicies.some(({ originOps }) => originOps?.some(({ chain, required }) => !required && chain.id === resolved.session.chain.id));\n    if (!input.intent.source &&\n        resolvedEntries.some(([, resolved]) => resolved.session.oneTimeUse || forbidsPreClaim(resolved))) {\n        throw new Error('This smart session requires an explicit source for its oneTimeUse burn or pre-claim restrictions');\n    }\n    const origin = input.intent.source && byChain[input.intent.source.chain.id];\n    if (origin &&\n        forbidsPreClaim(origin) &&\n        (origin.enableData || input.intent.source?.calls?.length)) {\n        throw new Error('The session claim may not carry pre-claim calls: enable it first and omit source calls');\n    }\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: 1,\n            targetChainId: chainId,\n            shape: !resolved.verifyExecutions\n                ? 'erc1271'\n                : resolved.enableData\n                    ? 'enable'\n                    : 'use',\n        }),\n    ]));\n    // The source chain carries the enablement. A source-free intent has no\n    // pre-claim slot, so a destination session that still needs enabling is\n    // reported for the caller to refuse.\n    const enablingChain = input.intent.source?.chain ?? input.intent.destination;\n    const enabling = enablingChain.kind === 'evm' ? byChain[enablingChain.id] : undefined;\n    const sourceBurn = origin && oneTimeUseBurnCall(origin);\n    const preClaimCalls = sourceBurn\n        ? [sourceBurn]\n        : enabling?.verifyExecutions && enabling.enableData\n            ? [\n                {\n                    target: DUMMY_PRECLAIMOP_TARGET,\n                    value: 0n,\n                    data: DUMMY_PRECLAIMOP_SELECTOR,\n                },\n            ]\n            : [];\n    const destinationSession = input.intent.destination.kind === 'evm'\n        ? byChain[input.intent.destination.id]\n        : undefined;\n    const destinationBurn = destinationSession &&\n        input.intent.destination.kind === 'evm' &&\n        input.intent.source?.chain.id !== input.intent.destination.id\n        ? oneTimeUseBurnCall(destinationSession)\n        : undefined;\n    return {\n        ...(destinationBurn ? { destinationBurn } : {}),\n        signatureMode: resolvedEntries.some(([, value]) => value.verifyExecutions)\n            ? 5\n            : 1,\n        byChain,\n        mockSignatures,\n        preClaimCalls,\n    };\n}\n// The orchestrator stamps the Permit2 witness; executor settlement ignores it.\nfunction oneTimeUseBurnCall(resolved) {\n    if (!resolved.session.oneTimeUse)\n        return undefined;\n    const op = buildOneTimeUseBurnOp({\n        ...resolved.session.oneTimeUse,\n        route: 'permit2',\n    });\n    return { target: op.to, value: op.value, data: op.data };\n}\n// Virtual venues and other recipients do not host this account's session.\nfunction sessionChains(intent, account) {\n    const chains = new Map();\n    if (intent.source)\n        chains.set(intent.source.chain.id, intent.source.chain);\n    if (intent.destination.kind === 'evm' &&\n        !isHyperCoreWireId(intent.destination.id) &&\n        (!intent.recipient ||\n            intent.recipient.address.toLowerCase() === account.toLowerCase())) {\n        chains.set(intent.destination.id, intent.destination);\n    }\n    return [...chains.values()];\n}\n","import { base64urlnopad } from '@scure/base';\nimport { hexToBytes, isAddress, isAddressEqual, isHex, recoverMessageAddress, } from 'viem';\nimport { isManagedSwigNamespace, } from '../../accounts/solana/address.js';\nimport { isCompressedSec1PublicKey } from '../../accounts/solana/keys.js';\nimport { formatCaip2 } from '../../chains/caip2.js';\nimport { solanaAddress, solanaDevnet, solanaMainnet, } from '../../chains/non-evm.js';\nimport { isSponsoredIntentInput, toSponsorshipApprovalInput, } from '../../clients/orchestrator/sponsorship-approval.js';\nimport { InvalidSolanaTransactionArtifactError, SolanaQuoteExpiredError, } from '../../errors/execution.js';\nimport { normalizeRecovery } from '../../signing/signers/ecdsa.js';\nimport { 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';\nconst AUTHORITY_PERMISSIONS = [\n    'all',\n    'allButManageAuthority',\n    'manageAuthority',\n];\nfunction wireKeyKind(keyType) {\n    return keyType === 'ecdsa' ? 'secp256k1' : 'secp256r1';\n}\n/** The only sponsorship an authority change is quoted with: gas, spelled out. */\nexport const SOLANA_AUTHORITY_SPONSORSHIP = Object.freeze({\n    gas: true,\n    bridgeFees: false,\n    swapFees: false,\n});\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 built(request) {\n    return { request, intentInput: toSponsorshipApprovalInput(request) };\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 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    if (input.action.kind === 'authority') {\n        return buildAuthorityRequest(input, input.action.change, { caip2, account });\n    }\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        const feeToken = input.action.feeToken === undefined\n            ? undefined\n            : solanaAddress(input.action.feeToken);\n        if (!feeToken && input.sponsorSettings?.gas !== true) {\n            throw new InvalidSolanaTransactionArtifactError('an unsponsored Solana instruction execution names the token it pays in');\n        }\n        return built({\n            account,\n            // Only an unsponsored execution names a source: the token its charge is\n            // drafted from.\n            ...(feeToken\n                ? { source: { vm: 'svm', chainId: caip2, token: feeToken } }\n                : {}),\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                execution: {\n                    instructions,\n                    ...(lookupTables ? { addressLookupTables: lookupTables } : {}),\n                },\n            },\n            ...(Object.keys(options).length > 0 ? { options } : {}),\n        });\n    }\n    const mint = solanaAddress(input.action.mint);\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' && mint === NATIVE_SOL_SENTINEL) {\n        throw new InvalidSolanaTransactionArtifactError('native SOL cannot be sent same-chain; provide an SPL mint');\n    }\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    // The one cluster and mint the wallet spends. The orchestrator admits native\n    // SOL only as the named source token; a cap bounds that token alone.\n    const source = {\n        vm: 'svm',\n        chainId: caip2,\n        token: mint,\n        ...(sourceLimit === undefined ? {} : { maxAmount: sourceLimit }),\n    };\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 built({\n            account,\n            source,\n            destination: {\n                vm: 'evm',\n                chainId: formatCaip2(delivery.chainId),\n                token: delivery.token,\n                ...amount,\n                ...recipient,\n                ...(executions\n                    ? {\n                        execution: {\n                            calls: executions,\n                            ...(execution?.gasLimit === undefined\n                                ? {}\n                                : { gasLimit: execution.gasLimit }),\n                        },\n                    }\n                    : {}),\n            },\n            ...(Object.keys(options).length > 0 ? { options } : {}),\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 built({\n        account,\n        source,\n        destination: {\n            vm: 'svm',\n            chainId: caip2,\n            token: mint,\n            ...amount,\n            recipient: { address: recipient },\n        },\n        ...(Object.keys(options).length > 0 ? { options } : {}),\n    });\n}\nfunction wireAuthorityChange(change) {\n    const key = { kind: wireKeyKind(change.keyType), publicKey: change.key };\n    return change.action === 'add'\n        ? { action: 'add', key, permission: change.permission }\n        : { action: 'remove', key };\n}\nfunction buildAuthorityRequest(input, change, context) {\n    if (input.appFees || input.protocolFees) {\n        throw new InvalidSolanaTransactionArtifactError('a Swig authority change carries no value leg to charge fees on');\n    }\n    if (stable(input.sponsorSettings) !== stable(SOLANA_AUTHORITY_SPONSORSHIP) ||\n        input.accountType !== undefined ||\n        input.accountAddress !== input.walletAddress) {\n        throw new InvalidSolanaTransactionArtifactError('a Swig authority change is gas-sponsored and names only the Swig wallet');\n    }\n    if (!change ||\n        typeof change !== 'object' ||\n        (change.keyType !== 'passkey' && change.keyType !== 'ecdsa') ||\n        !isCompressedSec1PublicKey(change.key) ||\n        !(change.action === 'add'\n            ? AUTHORITY_PERMISSIONS.includes(change.permission)\n            : change.action === 'remove' && change.permission === undefined)) {\n        throw new InvalidSolanaTransactionArtifactError('a Swig authority change adds a compressed passkey or secp256k1 key with a permission, or removes one without');\n    }\n    // Source-free: the sponsor pays for the change, so nothing is drafted from\n    // the wallet.\n    return built({\n        account: context.account,\n        destination: {\n            vm: 'svm',\n            chainId: context.caip2,\n            execution: { authority: wireAuthorityChange(change) },\n        },\n        options: { sponsorship: { ...SOLANA_AUTHORITY_SPONSORSHIP } },\n    });\n}\nfunction deliveryKind(input) {\n    return input.action.kind === 'transfer'\n        ? input.action.delivery.kind\n        : 'same-chain';\n}\nfunction isRoleId(value) {\n    return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0;\n}\n/**\n * Whether an orchestrator disclosure is the requested change: the same action,\n * curve and key, the permission on an add only, and a role and rent it sized.\n */\nfunction disclosesChange(disclosure, change) {\n    if (!disclosure || typeof disclosure !== 'object')\n        return false;\n    const { action, key, permission, roleId, rent } = disclosure;\n    const named = key;\n    const sized = rent;\n    return (action === change.action &&\n        named?.kind === wireKeyKind(change.keyType) &&\n        typeof named.publicKey === 'string' &&\n        named.publicKey.toLowerCase() === change.key &&\n        permission === change.permission &&\n        isRoleId(roleId) &&\n        typeof sized?.amount === 'string' &&\n        /^\\d+$/u.test(sized.amount) &&\n        typeof sized.usd === 'number');\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 authorizes = input.action.kind === 'authority' ? 'authority change' : 'spend';\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 ${authorizes} 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 ${authorizes} 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 (input.action.kind === 'authority') {\n        if (scope.vm !== 'svm' || scope.action !== 'manageAuthority') {\n            refuse('the signing request must authorize a Swig authority change');\n        }\n        if (request.purpose !== 'originAuthorization' ||\n            authority.kind !== 'swigRole' ||\n            !isRoleId(authority.roleId)) {\n            refuse('the signing request must be an origin authorization by a Swig role');\n        }\n        const managed = scope;\n        const chainId = formatCaip2(solanaChainId(input.chain));\n        if (!Array.isArray(managed.accounts) ||\n            managed.accounts.length !== 1 ||\n            managed.accounts[0]?.chainId !== chainId ||\n            managed.accounts[0]?.address !== input.swigAddress) {\n            refuse('the signing scope must name the configured Swig state account on the requested cluster');\n        }\n        if (!disclosesChange(managed.authority, input.action.change)) {\n            refuse('the signing scope must disclose the requested authority change');\n        }\n    }\n    else 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    const { request } = spendPayload(quote, input, deliveryKind(input));\n    const chainId = formatCaip2(solanaChainId(input.chain));\n    if (input.action.kind === 'authority') {\n        validateAuthorityQuote(quote, input, request, chainId);\n        return;\n    }\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}\n/**\n * An authority change moves no tokens and runs nothing else: the plan is the\n * one Swig block, run by the state account, disclosing exactly the change the\n * signing scope authorizes.\n */\nfunction validateAuthorityQuote(quote, input, request, chainId) {\n    const refuse = (reason) => {\n        throw new InvalidSolanaTransactionArtifactError(reason, {\n            intentId: quote.intentId,\n        });\n    };\n    const { plan } = quote;\n    if (plan.source.length !== 0 ||\n        plan.deployments.length !== 0 ||\n        quote.requirements.length !== 0 ||\n        quote.cost.input.length !== 0 ||\n        quote.cost.output.length !== 0 ||\n        quote.bridgeFill !== undefined) {\n        refuse('a Swig authority change quote must source, deploy, require and move nothing');\n    }\n    const destination = plan.destination;\n    const account = destination.account;\n    const role = request.authority.authority;\n    const actingAuthority = account.authority;\n    if (destination.vm !== 'svm' ||\n        destination.chainId !== chainId ||\n        account.wallet !== input.walletAddress ||\n        account.swigAccount !== input.swigAddress ||\n        !actingAuthority ||\n        stable(lowercaseAuthority(actingAuthority)) !==\n            stable(lowercaseAuthority(role))) {\n        refuse('the quote plan must name the configured Swig wallet, state account and authority on the requested cluster');\n    }\n    const execution = destination.execution;\n    const scope = request.scope;\n    if (execution?.executedBy?.kind !== 'account' ||\n        execution.executedBy.address !== input.swigAddress ||\n        stable(execution.authority) !== stable(scope.authority)) {\n        refuse('the quote plan must disclose the signed authority change, run by the Swig state account');\n    }\n}\nfunction lowercaseAuthority(authority) {\n    return authority.kind === 'secp256r1'\n        ? {\n            kind: 'secp256r1',\n            publicKey: authority.publicKey.toLowerCase(),\n        }\n        : {\n            kind: 'secp256k1',\n            address: authority.address.toLowerCase(),\n        };\n}\nexport async function prepareSolanaIntent(context, input) {\n    const { request, intentInput } = buildSolanaIntentRequest(input);\n    const response = await context.quoteClient.createQuote(request, {\n        intentInput,\n        sponsored: isSponsoredIntentInput(intentInput),\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        intentInput,\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, intentInput } = 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(intentInput) !== 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        intentInput,\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}\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        ...(action.kind === 'authority' ||\n            (action.kind === 'instructions' && !action.feeToken)\n            ? {}\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","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 { 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","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","// Validates and canonicalizes the public nested `{ source, destination }`\n// transaction before anything is resolved, quoted or signed. The output is the\n// same public shape, frozen, with the same-chain shorthand expanded: an omitted\n// `source.chain` becomes `destination.chain`, and nothing else is ever\n// inferred — no chain or token discovery, no first-source selection.\nimport { isAddress } from 'viem';\nimport { canonicalSecp256k1PublicKey, isEvmAddressLength, } from '../accounts/solana/keys.js';\nimport { canonicalP256PublicKey } from '../accounts/solana/passkey.js';\nimport { formatCaip2 } from '../chains/caip2.js';\nimport { solanaAddress, } from '../chains/non-evm.js';\nimport { AccountVmNotConfiguredError, UnsupportedAccountCapabilityError, } from '../errors/capability.js';\nimport { NATIVE_SOL_SENTINEL, solanaChainId, } from '../transactions/intents/solana.js';\nimport { normalizeSolanaAddressLookupTables, normalizeSolanaInstructions, } from '../transactions/intents/solana-instructions.js';\n/** What each flat top-level field became. */\nconst REPLACED_FIELDS = {\n    chain: '`destination.chain` (`source.chain` defaults to it)',\n    targetChain: '`destination.chain`',\n    sourceChains: '`source.chain`; a transaction spends from one source',\n    sourceAssets: '`source.token` and `source.maxAmount`',\n    sourceTokens: '`source.token`',\n    sourceCalls: '`source.calls`',\n    auxiliaryFunds: '`source.auxiliaryFunds`',\n    tokenRequests: '`destination.token` and `destination.amount`',\n    recipient: '`destination.recipient`',\n    calls: '`destination.calls`',\n    gasLimit: '`destination.gasLimit`',\n    hyperCore: '`destination.hyperCore`',\n    instructions: '`destination.instructions`',\n    addressLookupTables: '`destination.addressLookupTables`',\n    authority: '`destination.authority`',\n};\n/** Earlier spellings inside `source` and `destination`. */\nconst REPLACED_NESTED_FIELDS = {\n    'source.address': '`source.token`',\n    'source.amount': '`source.maxAmount`',\n    'source.selection': '`source.chain` and `source.token`',\n    'source.limits': '`source.maxAmount`',\n    'source.executions': '`source.calls`',\n    'destination.tokenRequests': '`destination.token` and `destination.amount`',\n    'destination.address': '`destination.token`',\n};\nconst EVM_ROOT_FIELDS = [\n    'source',\n    'destination',\n    'signers',\n    'sponsored',\n    'eip7702InitSignature',\n    'appFees',\n    'protocolFees',\n    'settlementLayers',\n    'quoters',\n    'customDeadline',\n    'experimental_accountOverride',\n];\nconst EVM_DESTINATION_FIELDS = {\n    evm: ['chain', 'token', 'amount', 'recipient', 'calls', 'gasLimit'],\n    hypercore: [\n        'chain',\n        'token',\n        'amount',\n        'recipient',\n        'calls',\n        'gasLimit',\n        'hyperCore',\n    ],\n    svm: ['chain', 'token', 'amount', 'recipient'],\n    tvm: ['chain', 'token', 'amount', 'recipient'],\n    stellar: ['chain', 'token', 'amount', 'recipient'],\n};\nconst EVM_SOURCE_FIELDS = [\n    'chain',\n    'token',\n    'maxAmount',\n    'auxiliaryFunds',\n    'calls',\n];\nconst SAME_CHAIN_NATIVE_SOL_MESSAGE = 'A same-chain Solana transfer cannot send native SOL; name an SPL mint.';\nconst unsupported = (field) => `Solana-origin transfers do not support \\`${field}\\`.`;\nfunction refuse(message, field, vm) {\n    throw new UnsupportedAccountCapabilityError(message, {\n        ...(vm ? { vm } : {}),\n        ...(field ? { field } : {}),\n    });\n}\nfunction isRecord(value) {\n    return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\nfunction has(value, key) {\n    return Object.hasOwn(value, key) && value[key] !== undefined;\n}\nfunction assertRecord(value, field, vm) {\n    if (!isRecord(value))\n        refuse(`\\`${field}\\` must be an object.`, field, vm);\n}\n/** Refuses flat top-level fields by name, with what replaced each. */\nfunction assertNoReplacedFields(transaction) {\n    for (const [key, replacement] of Object.entries(REPLACED_FIELDS)) {\n        if (Object.hasOwn(transaction, key)) {\n            refuse(`\\`${key}\\` was replaced by ${replacement}.`, key);\n        }\n    }\n}\nfunction assertFields(value, allowed, label, describe, vm) {\n    for (const key of Object.keys(value)) {\n        if (allowed.includes(key))\n            continue;\n        const field = label ? `${label}.${key}` : key;\n        const replacement = REPLACED_NESTED_FIELDS[field];\n        if (replacement) {\n            refuse(`\\`${field}\\` was replaced by ${replacement}.`, field, vm);\n        }\n        refuse(describe(field), field, vm);\n    }\n}\nfunction chainKind(value, field) {\n    if (!isRecord(value))\n        refuse(`\\`${field}\\` must be a chain.`, field);\n    if (!Object.hasOwn(value, 'kind') && !Object.hasOwn(value, 'caip2')) {\n        const id = value.id;\n        if (typeof id !== 'number' ||\n            !Number.isSafeInteger(id) ||\n            id < 0 ||\n            !formatCaip2(id).startsWith('eip155:')) {\n            refuse('A viem EVM chain must use an eip155 chain ID.', field);\n        }\n        return 'evm';\n    }\n    const { kind, caip2 } = value;\n    const matches = typeof caip2 === 'string' &&\n        ((kind === 'svm' && caip2.startsWith('solana:')) ||\n            (kind === 'tvm' && caip2.startsWith('tron:')) ||\n            (kind === 'stellar' && caip2.startsWith('stellar:')) ||\n            (kind === 'hypercore' &&\n                (caip2 === 'hypercore:spot' || caip2 === 'hypercore:perp')));\n    if (!matches) {\n        refuse('The chain descriptor has mismatched VM and CAIP-2 fields.', field);\n    }\n    return kind;\n}\nfunction sameChain(left, right) {\n    const a = left;\n    const b = right;\n    return a.caip2 !== undefined || b.caip2 !== undefined\n        ? a.caip2 === b.caip2\n        : a.id === b.id;\n}\nfunction assertAmount(value, field, options) {\n    if (typeof value !== 'bigint' ||\n        value < 0n ||\n        (options.positive && value === 0n)) {\n        refuse(`\\`${field}\\` must be a ${options.positive ? 'positive' : 'non-negative'} bigint when provided.`, field, options.vm);\n    }\n}\nfunction isGasSponsored(sponsored) {\n    return (sponsored === true ||\n        (isRecord(sponsored) && sponsored.gas === true));\n}\nfunction freezeSponsorship(sponsored) {\n    if (sponsored === undefined)\n        return {};\n    if (typeof sponsored === 'boolean')\n        return { sponsored };\n    if (!isRecord(sponsored)) {\n        refuse('`sponsored` must be a boolean or a sponsorship object.', 'sponsored');\n    }\n    return { sponsored: Object.freeze({ ...sponsored }) };\n}\nfunction freezeFees(transaction) {\n    const result = {};\n    for (const key of ['appFees', 'protocolFees']) {\n        if (transaction[key] === undefined)\n            continue;\n        assertRecord(transaction[key], key);\n        assertFields(transaction[key], ['feeBps'], key, (field) => `\\`${field}\\` is not a fee field.`);\n        result[key] = Object.freeze({ ...transaction[key] });\n    }\n    return result;\n}\nfunction defined(value) {\n    return Object.fromEntries(Object.entries(value).filter(([, item]) => item !== undefined));\n}\n/**\n * The canonical form of a transaction, refusing anything the nested model\n * does not allow. Idempotent: normalizing a normalized transaction returns an\n * equal one.\n */\nexport function normalizeTransaction(transaction, config) {\n    if (!isRecord(transaction))\n        refuse('A transaction must be an object.');\n    const input = transaction;\n    assertNoReplacedFields(input);\n    if (!has(input, 'destination')) {\n        refuse('A transaction needs a `destination`: `{ chain, token?, amount?, … }`.', 'destination');\n    }\n    assertRecord(input.destination, 'destination');\n    const destination = input.destination;\n    if (!has(destination, 'chain')) {\n        refuse('`destination.chain` is required.', 'destination.chain');\n    }\n    const destinationKind = chainKind(destination.chain, 'destination.chain');\n    const source = input.source;\n    if (source !== undefined)\n        assertRecord(source, 'source');\n    const sourceChain = source === undefined\n        ? undefined\n        : has(source, 'chain')\n            ? source.chain\n            : destination.chain;\n    const sourceKind = sourceChain === undefined\n        ? undefined\n        : chainKind(sourceChain, has(source, 'chain') ? 'source.chain' : 'destination.chain');\n    if (sourceKind === 'svm' || (!source && destinationKind === 'svm')) {\n        return normalizeSolanaOrigin(input, config, destinationKind, sourceChain);\n    }\n    return normalizeEvmOrigin(input, config, {\n        destinationKind,\n        sourceKind,\n        sourceChain,\n    });\n}\nfunction normalizeEvmOrigin(input, config, resolved) {\n    const { destinationKind, sourceKind, sourceChain } = resolved;\n    assertFields(input, EVM_ROOT_FIELDS, '', (field) => `\\`${field}\\` is not a transaction field.`);\n    const destination = input.destination;\n    const destinationFields = EVM_DESTINATION_FIELDS[destinationKind];\n    if (has(destination, 'hyperCore') && destinationKind !== 'hypercore') {\n        refuse('`destination.hyperCore` applies to a HyperCore destination (`hyperCorePerp` or `hyperCoreSpot`) only.', 'destination.hyperCore');\n    }\n    assertFields(destination, destinationFields, 'destination', (field) => `\\`${field}\\` is not supported for a ${destinationKind} destination.`);\n    const delivers = has(destination, 'token');\n    if (has(destination, 'amount') && !delivers) {\n        refuse('`destination.amount` needs `destination.token`: name the token to receive.', 'destination.amount');\n    }\n    const nonEvmDestination = destinationKind === 'svm' ||\n        destinationKind === 'tvm' ||\n        destinationKind === 'stellar';\n    if (delivers) {\n        if (destinationKind === 'evm') {\n            if (typeof destination.token !== 'string' ||\n                !isAddress(destination.token)) {\n                refuse('`destination.token` must be a token address on the destination chain.', 'destination.token');\n            }\n        }\n        else if (typeof destination.token !== 'string' ||\n            destination.token.length === 0) {\n            refuse('`destination.token` must be a token address on the destination chain.', 'destination.token');\n        }\n        if (destinationKind === 'svm') {\n            try {\n                solanaAddress(destination.token);\n            }\n            catch {\n                refuse('`destination.token` must be a Solana token address.', 'destination.token', 'solana');\n            }\n        }\n    }\n    else if (nonEvmDestination) {\n        refuse(`A ${destinationKind} destination only receives tokens; name \\`destination.token\\`.`, 'destination.token');\n    }\n    if (has(destination, 'amount')) {\n        assertAmount(destination.amount, 'destination.amount', {\n            positive: nonEvmDestination,\n        });\n    }\n    const runsCalls = Array.isArray(destination.calls) && destination.calls.length > 0;\n    if (destination.calls !== undefined && !Array.isArray(destination.calls)) {\n        refuse('`destination.calls` must be an array of calls.', 'destination.calls');\n    }\n    const recipient = destination.recipient;\n    if (recipient !== undefined) {\n        if (runsCalls) {\n            refuse('An explicit delivery recipient cannot execute destination calls. Omit `destination.recipient` to execute with the invoking managed EVM account.', 'destination.recipient');\n        }\n        if (!delivers) {\n            refuse('An explicit delivery recipient requires `destination.token`.', 'destination.recipient');\n        }\n        if (destinationKind === 'evm' || destinationKind === 'hypercore') {\n            if (!(typeof recipient === 'string' && isAddress(recipient)) &&\n                !isRecord(recipient)) {\n                refuse('`destination.recipient` must be an EVM address or an EVM account config.', 'destination.recipient');\n            }\n        }\n        else if (typeof recipient !== 'string' || recipient.length === 0) {\n            refuse(`A ${destinationKind} delivery recipient must be an address on that chain.`, 'destination.recipient');\n        }\n        else if (destinationKind === 'svm') {\n            try {\n                solanaAddress(recipient);\n            }\n            catch {\n                refuse('A Solana delivery recipient must be a Solana address.', 'destination.recipient', 'solana');\n            }\n        }\n    }\n    else if (destinationKind === 'tvm' || destinationKind === 'stellar') {\n        refuse(`A ${destinationKind} delivery needs \\`destination.recipient\\`: the account holds no identity there.`, 'destination.recipient');\n    }\n    const gasSponsored = isGasSponsored(input.sponsored);\n    let source;\n    if (input.source === undefined) {\n        if (delivers) {\n            refuse('A delivery needs a `source`: name the chain and token it spends, `source: { chain, token }`.', 'source');\n        }\n        if (destinationKind !== 'evm') {\n            refuse(`A ${destinationKind} destination hosts no account, so the transaction needs a \\`source\\` on an EVM chain.`, 'source');\n        }\n        if (!gasSponsored) {\n            refuse('An execution that is not gas-sponsored needs a `source` to pay from: `source: { token }` spends on the destination chain.', 'source');\n        }\n    }\n    else {\n        const raw = input.source;\n        assertFields(raw, EVM_SOURCE_FIELDS, 'source', (field) => `\\`${field}\\` is not a source field.`);\n        if (sourceKind !== 'evm') {\n            refuse(has(raw, 'chain')\n                ? `A ${sourceKind} chain cannot fund a transaction; \\`source.chain\\` must be an EVM chain.`\n                : `A ${destinationKind} destination cannot fund itself; name \\`source.chain\\`.`, 'source.chain');\n        }\n        if (typeof raw.token !== 'string' || !isAddress(raw.token)) {\n            refuse('`source.token` must be a token address on the source chain.', 'source.token');\n        }\n        if (has(raw, 'maxAmount')) {\n            assertAmount(raw.maxAmount, 'source.maxAmount', { positive: false });\n        }\n        if (has(raw, 'auxiliaryFunds')) {\n            assertAmount(raw.auxiliaryFunds, 'source.auxiliaryFunds', {\n                positive: true,\n            });\n        }\n        if (raw.calls !== undefined) {\n            if (!Array.isArray(raw.calls)) {\n                refuse('`source.calls` must be an array of calls.', 'source.calls');\n            }\n            for (const [index, call] of raw.calls.entries()) {\n                assertRecord(call, `source.calls.${index}`);\n                const provides = call.provides;\n                if (provides === undefined)\n                    continue;\n                if (!Array.isArray(provides)) {\n                    refuse('`provides` must be an array of `{ token, amount }`.', `source.calls.${index}.provides`);\n                }\n                for (const [position, provided] of provides.entries()) {\n                    const field = `source.calls.${index}.provides.${position}`;\n                    assertRecord(provided, field);\n                    if (typeof provided.token !== 'string' ||\n                        provided.token.toLowerCase() !== raw.token.toLowerCase()) {\n                        refuse(`\\`${field}.token\\` must be \\`source.token\\`: source calls can only make more of the source token available.`, `${field}.token`);\n                    }\n                    assertAmount(provided.amount, `${field}.amount`, { positive: true });\n                }\n            }\n        }\n        source = Object.freeze(defined({\n            ...raw,\n            chain: sourceChain,\n            ...(raw.calls === undefined ? {} : { calls: [...raw.calls] }),\n        }));\n    }\n    if (input.customDeadline !== undefined &&\n        source !== undefined &&\n        !sameChain(source.chain, destination.chain)) {\n        refuse('`customDeadline` applies to same-chain transactions only; this one spends on another chain.', 'customDeadline');\n    }\n    const solanaDefault = destinationKind === 'svm' &&\n        recipient === undefined &&\n        config.solana &&\n        'address' in config.solana\n        ? { recipient: config.solana.address }\n        : {};\n    if (destinationKind === 'svm' && recipient === undefined && !config.solana) {\n        throw new AccountVmNotConfiguredError('solana');\n    }\n    return Object.freeze(defined({\n        ...input,\n        ...(source ? { source } : {}),\n        destination: Object.freeze(defined({\n            ...destination,\n            ...solanaDefault,\n            ...(destination.calls === undefined\n                ? {}\n                : { calls: [...destination.calls] }),\n        })),\n        ...freezeFees(input),\n        ...freezeSponsorship(input.sponsored),\n    }));\n}\nfunction requireManagedSolana(config) {\n    if (!config.solana || !('owner' in config.solana)) {\n        refuse('A managed Solana source is required for Solana-origin transfers.', undefined, 'solana');\n    }\n}\nfunction solanaChain(value, field) {\n    try {\n        solanaChainId(value);\n    }\n    catch {\n        refuse(`\\`${field}\\` must be the canonical Solana mainnet or devnet descriptor.`, field, 'solana');\n    }\n    return Object.freeze({ ...value });\n}\nfunction solanaToken(value, field) {\n    try {\n        return solanaAddress(value);\n    }\n    catch {\n        return refuse(`\\`${field}\\` must be a valid Solana token address.`, field, 'solana');\n    }\n}\nfunction normalizeSolanaOrigin(input, config, destinationKind, sourceChain) {\n    const destination = input.destination;\n    const source = input.source;\n    if (source !== undefined) {\n        for (const key of ['auxiliaryFunds', 'calls']) {\n            if (Object.hasOwn(source, key)) {\n                refuse(`\\`source.${key}\\` is EVM-only; a Solana source spends one token and runs no source calls.`, `source.${key}`, 'solana');\n            }\n        }\n    }\n    if (destinationKind === 'evm') {\n        return normalizeSolanaDelivery(input, config, sourceChain);\n    }\n    if (destinationKind !== 'svm') {\n        refuse('A Solana source delivers to Solana or to an EVM chain.', 'destination.chain', 'solana');\n    }\n    const chain = solanaChain(destination.chain, 'destination.chain');\n    if (sourceChain !== undefined && !sameChain(sourceChain, destination.chain)) {\n        refuse('A Solana source funds a transaction on its own cluster only.', 'source.chain', 'solana');\n    }\n    if (has(destination, 'authority')) {\n        assertFields(input, ['destination'], '', unsupported, 'solana');\n        assertFields(destination, ['chain', 'authority'], 'destination', unsupported, 'solana');\n        requireManagedSolana(config);\n        const { keyType, publicKey } = assertSolanaAuthorityChange(destination.authority);\n        const { action, permission } = destination.authority;\n        const key = Object.freeze({ type: keyType, publicKey });\n        return Object.freeze({\n            destination: Object.freeze({\n                chain,\n                authority: Object.freeze(action === 'add' ? { action, key, permission } : { action, key }),\n            }),\n        });\n    }\n    if (has(destination, 'instructions')) {\n        assertFields(input, ['source', 'destination', 'sponsored'], '', unsupported, 'solana');\n        assertFields(destination, ['chain', 'instructions', 'addressLookupTables'], 'destination', unsupported, 'solana');\n        requireManagedSolana(config);\n        let feeSource;\n        if (source !== undefined) {\n            assertFields(source, ['chain', 'token'], 'source', unsupported, 'solana');\n            feeSource = Object.freeze({\n                chain,\n                token: solanaToken(source.token, 'source.token'),\n            });\n        }\n        else if (!isGasSponsored(input.sponsored)) {\n            refuse('An instruction execution that is not gas-sponsored needs `source.token`: the SPL mint or native SOL its charge is paid in.', 'source', 'solana');\n        }\n        const lookupTables = normalizeSolanaAddressLookupTables(destination.addressLookupTables);\n        return Object.freeze({\n            ...(feeSource ? { source: feeSource } : {}),\n            destination: Object.freeze({\n                chain,\n                instructions: normalizeSolanaInstructions(destination.instructions),\n                ...(lookupTables ? { addressLookupTables: lookupTables } : {}),\n            }),\n            ...freezeSponsorship(input.sponsored),\n        });\n    }\n    assertFields(input, ['source', 'destination', 'sponsored', 'appFees', 'protocolFees'], '', unsupported, 'solana');\n    assertFields(destination, ['chain', 'token', 'amount', 'recipient'], 'destination', unsupported, 'solana');\n    requireManagedSolana(config);\n    if (!source) {\n        refuse('A Solana transfer needs a `source`: `source: { token }` names the mint it spends.', 'source', 'solana');\n    }\n    assertFields(source, ['chain', 'token', 'maxAmount'], 'source', unsupported, 'solana');\n    if (!has(destination, 'token')) {\n        refuse('A Solana transfer needs `destination.token`, the SPL mint it sends.', 'destination.token', 'solana');\n    }\n    const mint = solanaToken(destination.token, 'destination.token');\n    if (mint === NATIVE_SOL_SENTINEL) {\n        refuse(SAME_CHAIN_NATIVE_SOL_MESSAGE, 'destination.token', 'solana');\n    }\n    if (solanaToken(source.token, 'source.token') !== mint) {\n        refuse('`source.token` must be the mint the transfer sends, `destination.token`.', 'source.token', 'solana');\n    }\n    if (has(destination, 'amount')) {\n        assertAmount(destination.amount, 'destination.amount', {\n            positive: true,\n            vm: 'solana',\n        });\n    }\n    if (has(source, 'maxAmount')) {\n        assertAmount(source.maxAmount, 'source.maxAmount', {\n            positive: true,\n            vm: 'solana',\n        });\n        if (has(destination, 'amount') &&\n            destination.amount > source.maxAmount) {\n            refuse('The token amount exceeds the `source.maxAmount` that caps it.', 'source.maxAmount', 'solana');\n        }\n    }\n    if (typeof destination.recipient !== 'string') {\n        refuse('Managed Solana transfers require an explicit recipient wallet, `destination.recipient`.', 'destination.recipient', 'solana');\n    }\n    try {\n        solanaAddress(destination.recipient);\n    }\n    catch {\n        refuse('Managed Solana transfers require a valid recipient wallet.', 'destination.recipient', 'solana');\n    }\n    return Object.freeze({\n        source: Object.freeze(defined({ chain, token: mint, maxAmount: source.maxAmount })),\n        destination: Object.freeze(defined({\n            chain,\n            token: mint,\n            amount: destination.amount,\n            recipient: destination.recipient,\n        })),\n        ...freezeFees(input),\n        ...freezeSponsorship(input.sponsored),\n    });\n}\nfunction normalizeSolanaDelivery(input, config, sourceChain) {\n    const destination = input.destination;\n    const source = input.source;\n    assertFields(input, [\n        'source',\n        'destination',\n        'eip7702InitSignature',\n        'sponsored',\n        'appFees',\n        'protocolFees',\n    ], '', unsupported, 'solana');\n    assertFields(destination, ['chain', 'token', 'amount', 'recipient', 'calls', 'gasLimit'], 'destination', unsupported, 'solana');\n    assertFields(source, ['chain', 'token', 'maxAmount'], 'source', unsupported, 'solana');\n    requireManagedSolana(config);\n    const cluster = solanaChain(sourceChain, 'source.chain');\n    const token = solanaToken(source.token, 'source.token');\n    if (has(source, 'maxAmount')) {\n        assertAmount(source.maxAmount, 'source.maxAmount', {\n            positive: true,\n            vm: 'solana',\n        });\n    }\n    if (destination.calls !== undefined && !Array.isArray(destination.calls)) {\n        refuse('`destination.calls` must be an array of destination calls.', 'destination.calls', 'solana');\n    }\n    const runsCalls = Array.isArray(destination.calls) && destination.calls.length > 0;\n    const hasManagedEvm = config.evm !== undefined && !Object.hasOwn(config.evm, 'address');\n    if (runsCalls && !hasManagedEvm) {\n        refuse('Destination calls require a managed EVM account; an address-only receiver can only receive a plain delivery. Omit `destination.calls`.', 'destination.calls', 'solana');\n    }\n    if (runsCalls && destination.recipient !== undefined) {\n        refuse('An explicit delivery recipient cannot execute destination calls. Omit `destination.recipient` to execute with the invoking managed EVM account.', 'destination.recipient', 'solana');\n    }\n    for (const [field, value] of [\n        ['destination.gasLimit', destination.gasLimit],\n        ['eip7702InitSignature', input.eip7702InitSignature],\n    ]) {\n        if (value !== undefined && !runsCalls) {\n            refuse(`\\`${field}\\` applies to \\`destination.calls\\`, and this delivery has none.`, field, 'solana');\n        }\n    }\n    if (typeof destination.token !== 'string' || !isAddress(destination.token)) {\n        refuse('A Solana-origin delivery requires an EVM `destination.token` address.', 'destination.token', 'solana');\n    }\n    if (has(destination, 'amount')) {\n        assertAmount(destination.amount, 'destination.amount', {\n            positive: true,\n            vm: 'solana',\n        });\n    }\n    if (destination.recipient !== undefined &&\n        (typeof destination.recipient !== 'string' ||\n            !isAddress(destination.recipient))) {\n        refuse('A Solana-origin delivery recipient must be an EVM address.', 'destination.recipient', 'solana');\n    }\n    return Object.freeze(defined({\n        ...input,\n        source: Object.freeze(defined({ chain: cluster, token, maxAmount: source.maxAmount })),\n        destination: Object.freeze(defined({\n            ...destination,\n            ...(destination.calls === undefined\n                ? {}\n                : { calls: [...destination.calls] }),\n        })),\n        ...freezeFees(input),\n        ...freezeSponsorship(input.sponsored),\n    }));\n}\n/**\n * Checks an authority change's shape, and returns its key in canonical form.\n * A literal is held to the same rules the `addPasskey`, `addEcdsaKey`,\n * `removePasskey` and `removeEcdsaKey` builders apply.\n */\nfunction assertSolanaAuthorityChange(value) {\n    const fail = (message, field) => refuse(message, field, 'solana');\n    const field = 'destination.authority';\n    const builders = '`addPasskey`, `addEcdsaKey`, `removePasskey` or `removeEcdsaKey`';\n    if (!isRecord(value)) {\n        fail(`\\`${field}\\` must be a change from ${builders}.`, field);\n    }\n    const change = value;\n    if (change.action !== 'add' && change.action !== 'remove') {\n        fail(`\\`${field}.action\\` must be 'add' or 'remove'; build it with ${builders}.`, `${field}.action`);\n    }\n    assertFields(change, change.action === 'add'\n        ? ['action', 'key', 'permission']\n        : ['action', 'key'], field, unsupported, 'solana');\n    if (change.action === 'add' &&\n        change.permission !== 'all' &&\n        change.permission !== 'allButManageAuthority' &&\n        change.permission !== 'manageAuthority') {\n        fail(`Adding a key needs \\`${field}.permission\\`: 'all', 'allButManageAuthority' or 'manageAuthority'.`, `${field}.permission`);\n    }\n    assertRecord(change.key, `${field}.key`, 'solana');\n    const key = change.key;\n    assertFields(key, ['type', 'publicKey'], `${field}.key`, unsupported, 'solana');\n    if (key.type === 'passkey') {\n        const publicKey = canonicalP256PublicKey(key.publicKey);\n        if (!publicKey) {\n            fail(`\\`${field}.key.publicKey\\` must be a P-256 public key as 64-byte x‖y, 65-byte uncompressed or 33-byte compressed hex.`, `${field}.key.publicKey`);\n        }\n        return { keyType: 'passkey', publicKey: publicKey };\n    }\n    if (key.type === 'ecdsa') {\n        if (isEvmAddressLength(key.publicKey)) {\n            fail(`\\`${field}.key.publicKey\\` is an EVM address, not a public key; pass the secp256k1 public key the address derives from.`, `${field}.key.publicKey`);\n        }\n        const publicKey = canonicalSecp256k1PublicKey(key.publicKey);\n        if (!publicKey) {\n            fail(`\\`${field}.key.publicKey\\` must be a secp256k1 public key as 33-byte compressed, 65-byte uncompressed or 64-byte x‖y hex, on the secp256k1 curve.`, `${field}.key.publicKey`);\n        }\n        return { keyType: 'ecdsa', publicKey: publicKey };\n    }\n    return fail(`\\`${field}.key.type\\` must be 'passkey' or 'ecdsa'.`, `${field}.key.type`);\n}\n/**\n * The canonical form of a `getAuthorityStatus` argument, refusing anything\n * that is not a Solana authority change.\n */\nexport function normalizeAuthorityChange(transaction, config) {\n    if (!isRecord(transaction) ||\n        !isRecord(transaction.destination) ||\n        transaction.destination.authority === undefined) {\n        refuse('`getAuthorityStatus` takes a `{ destination: { chain, authority } }` Solana authority change.', 'destination.authority', 'solana');\n    }\n    const normalized = normalizeTransaction(transaction, config);\n    if (!isSolanaAuthorityChange(normalized)) {\n        refuse('`getAuthorityStatus` takes a `{ destination: { chain, authority } }` Solana authority change.', 'destination.authority', 'solana');\n    }\n    return normalized;\n}\nfunction destinationOf(transaction) {\n    return transaction.destination;\n}\nfunction isSvmChain(chain) {\n    return isRecord(chain) && chain.kind === 'svm';\n}\n/** Whether a normalized transaction spends from the managed Solana account. */\nexport function isSolanaOrigin(transaction) {\n    // Resolves the shorthand itself, so an artifact that omits `source.chain` is\n    // routed exactly as its normalized form would be.\n    const source = transaction.source;\n    return isSvmChain(source?.chain ?? destinationOf(transaction).chain);\n}\n/** Whether a normalized transaction delivers from Solana to an EVM chain. */\nexport function isCrossChainSolanaOrigin(transaction) {\n    return (isSolanaOrigin(transaction) && !isSvmChain(destinationOf(transaction).chain));\n}\nexport function isSolanaInstructionExecution(transaction) {\n    return (isSolanaOrigin(transaction) &&\n        destinationOf(transaction).instructions !== undefined);\n}\nexport function isSolanaAuthorityChange(transaction) {\n    return (isSolanaOrigin(transaction) &&\n        destinationOf(transaction).authority !== undefined);\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 { 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, readSessionNonceAndEnabled, } 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, validateSession } 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            rpc: dependencies.rpc,\n            environment: config.environment,\n            definition,\n        }),\n        validateSession: (definition) => validateSession({\n            orchestrator: dependencies.orchestrator,\n            rpc: dependencies.rpc,\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        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, options) => setupAccount(context, chain, options, 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, options) => accountSessionDetails(context.account, sessions, dependencies, options),\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    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    // Refused before any read: an unsponsored intent deployment has nothing to\n    // pay with unless the caller names the token.\n    if (!useUserOperation && !options?.sponsored && !options?.sourceToken) {\n        throw missingSetupSource('deploy', chain.id);\n    }\n    if (await isAccountDeployed(account, chain, dependencies))\n        return false;\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            // Sponsored: source-free. Otherwise the named same-chain token pays.\n            ...(!options?.sponsored && options?.sourceToken\n                ? { source: { chain, token: options.sourceToken } }\n                : {}),\n            calls: [],\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}\nfunction missingSetupSource(method, chainId) {\n    return new UnsupportedAccountCapabilityError(method === 'deploy'\n        ? `An unsponsored deployment on chain ${chainId} runs as an intent and pays in a token on that chain. Pass \\`{ source: { token } }\\`, or \\`{ sponsored: true }\\`.`\n        : `Setup on chain ${chainId} runs as an intent and pays in a token on that chain. Pass \\`{ source: { token } }\\`.`, { field: 'source.token', chainId });\n}\nasync function setupAccount(context, chain, options, 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        if (!options?.sourceToken)\n            throw missingSetupSource('setup', chain.id);\n        const submitted = await sendIntent(intentContext(context, dependencies), {\n            destination: chain,\n            source: { chain, token: options.sourceToken },\n            calls,\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, options = {}) {\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        allowBudgetReset: options.allowBudgetReset,\n        readNonceAndEnabled: (session) => {\n            const chain = toEvmChainReference(session.chain.id);\n            return readSessionNonceAndEnabled({\n                rpc: dependencies.rpc.forChain(chain),\n                chain,\n                account: address,\n                lockTag: SESSION_LOCK_TAG,\n                session,\n                environment,\n            });\n        },\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        intentInput: input.approvalInput,\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                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            ...(input.signers ? { signers: input.signers } : {}),\n        },\n        request: {},\n        intentInput: {},\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 { isAddress } from 'viem';\nimport { chainIdFromCaip2, formatCaip2, isCaip2 } from '../../chains/caip2.js';\n/**\n * Read-only snapshot of the chain facts returned by `GET /chains`, fetched\n * lazily and refreshed by the client after its cache TTL.\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    /** Every chain's served settlement addresses; chains without any are omitted. */\n    getSettlementCatalog() {\n        const out = {};\n        for (const [id, info] of Object.entries(this.chains)) {\n            if (info.settlement)\n                out[Number(id)] = info.settlement;\n        }\n        return out;\n    }\n}\nconst isObject = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);\nconst isAddr = (value) => typeof value === 'string' && isAddress(value);\nconst isIndex = (value) => typeof value === 'number' && Number.isSafeInteger(value) && value >= 0;\nconst isAddrs = (value) => Array.isArray(value) && value.length > 0 && value.every(isAddr);\n// Malformed settlement blocks are omitted independently of other chain facts.\nfunction parseSettlement(value) {\n    if (!isObject(value))\n        return undefined;\n    const out = {};\n    const { cctp, oft, eco, lz, fees } = value;\n    if (isObject(cctp) &&\n        isIndex(cctp.domain) &&\n        isAddr(cctp.tokenMessenger) &&\n        isAddr(cctp.usdc)) {\n        out.cctp = {\n            domain: cctp.domain,\n            tokenMessenger: cctp.tokenMessenger,\n            usdc: cctp.usdc,\n        };\n    }\n    if (isObject(oft) &&\n        isAddr(oft.adapter) &&\n        isIndex(oft.eid) &&\n        isAddr(oft.token)) {\n        out.oft = { adapter: oft.adapter, eid: oft.eid, token: oft.token };\n    }\n    if (isObject(eco) &&\n        isAddr(eco.portal) &&\n        isAddrs(eco.provers) &&\n        isAddrs(eco.stablecoins)) {\n        out.eco = {\n            portal: eco.portal,\n            provers: eco.provers,\n            stablecoins: eco.stablecoins,\n        };\n    }\n    if (isObject(lz) && isAddr(lz.multiCall) && isAddr(lz.transferDelegate)) {\n        const { stargateUsdc: sg, cctp: lc } = lz;\n        out.lz = {\n            multiCall: lz.multiCall,\n            transferDelegate: lz.transferDelegate,\n            ...(isObject(sg) && isAddr(sg.pool) && isAddr(sg.token) && isIndex(sg.eid)\n                ? { stargateUsdc: { pool: sg.pool, token: sg.token, eid: sg.eid } }\n                : {}),\n            ...(isObject(lc) &&\n                isIndex(lc.domain) &&\n                isAddr(lc.token) &&\n                isAddr(lc.feeReceiver)\n                ? {\n                    cctp: {\n                        domain: lc.domain,\n                        token: lc.token,\n                        feeReceiver: lc.feeReceiver,\n                        ...(lc.feeless === true ? { feeless: true } : {}),\n                    },\n                }\n                : {}),\n        };\n    }\n    if (isObject(fees) &&\n        isAddr(fees.appFeeCollector) &&\n        isAddr(fees.paymaster)) {\n        out.fees = {\n            appFeeCollector: fees.appFeeCollector,\n            paymaster: fees.paymaster,\n        };\n    }\n    const { usdStablecoins: stablecoins } = value;\n    if (Array.isArray(stablecoins) && stablecoins.length > 0) {\n        const tokens = stablecoins.filter((t) => isObject(t) &&\n            isAddr(t.address) &&\n            typeof t.symbol === 'string' &&\n            isIndex(t.decimals));\n        if (tokens.length === stablecoins.length) {\n            out.usdStablecoins = tokens.map(({ address, symbol, decimals }) => ({\n                address,\n                symbol,\n                decimals,\n            }));\n        }\n    }\n    return Object.keys(out).length > 0 ? out : undefined;\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        // Native-VM chain facts remain available, but settlement policies are EVM-only.\n        const settlement = Number.isSafeInteger(id) &&\n            id >= 0 &&\n            formatCaip2(id).startsWith('eip155:')\n            ? parseSettlement(entry.settlement)\n            : undefined;\n        out[id] = {\n            name: entry.name,\n            testnet: entry.testnet,\n            supportedTokens: entry.supportedTokens,\n            ...(entry.wrappedNativeToken\n                ? { wrappedNativeToken: entry.wrappedNativeToken }\n                : {}),\n            ...(settlement ? { settlement } : {}),\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 (scope.vm === 'svm' &&\n        scope.action !== 'spend' &&\n        scope.action !== 'manageAuthority') {\n        invalid(`The orchestrator returned a signing request with an unsupported Solana scope action: ${String(scope.action)}.`);\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 { 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 = '3.0.0';\nconst API_VERSION = '2026-09.caucasus';\n// Bounds how long a killed layer or pulled settlement address stays pinnable.\nconst CHAIN_CATALOG_TTL_MS = 10 * 60 * 1000;\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    // Fetched lazily on first use and reused for the TTL, including in-flight reads.\n    let chainCatalog;\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            if (chainCatalog === undefined ||\n                Date.now() - chainCatalog.fetchedAt >= CHAIN_CATALOG_TTL_MS) {\n                const promise = (async () => {\n                    const json = (await request({ path: 'chains' }));\n                    return new ChainCatalog(parseChains(json));\n                })();\n                const entry = { promise, fetchedAt: Date.now() };\n                chainCatalog = entry;\n                promise.catch(() => {\n                    if (chainCatalog === entry)\n                        chainCatalog = undefined;\n                });\n            }\n            return chainCatalog.promise;\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, isAddressEqual, maxUint256, size, sliceHex, } from 'viem';\nimport { getSessionData } from './digest.js';\nimport { getSmartSessionEmissaryAddress } from './module.js';\nimport { CONSUME_SELECTOR } from './one-time-use.js';\nimport { defaultOneTimeUseIdPolicy } from './policies/addresses.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}\n/**\n * Whether a policy's rules hold a crossChainPermits `maxAmount` cap: a\n * `cumulativeCap` (lessThanOrEqual, limited, the cap as reference and limit,\n * nothing used) on the amount word of an approve or a transfer, or, on a\n * SAME_CHAIN_IE swap, on the sell amount with its `to.minAmount` floor\n * (greaterThanOrEqual on the Swapper's output bound, word 96) after it. A plain\n * `swap` scope puts any floor before its cap. Rules are six-word tuples.\n */\nfunction hasCapRule(initData, amountWord) {\n    const words = Array.from({ length: Math.floor(size(initData) / 32) }, (_, i) => BigInt(sliceHex(initData, i * 32, i * 32 + 32)));\n    return words.some((word, i) => word === 4n &&\n        words[i + 2] === 1n &&\n        words[i + 3] !== undefined &&\n        words[i + 3] === words[i + 4] &&\n        words[i + 5] === 0n &&\n        (amountWord\n            ? words[i + 1] === 32n\n            : words.some((floor, j) => j > i &&\n                (j - i) % 6 === 0 &&\n                floor === 3n &&\n                words[j + 1] === 96n &&\n                words[j + 2] === 0n)));\n}\n/**\n * Whether the session is one-time-use as compiled: a `consume` burn on its\n * OneTimeUseIdPolicy (the environment's default, or the one its metadata\n * names) and that policy on every action. A `consume` on any other target,\n * or the metadata alone, proves nothing.\n */\nfunction isOneTimeUse(session, environment) {\n    const policies = [\n        session.oneTimeUse?.policy,\n        defaultOneTimeUseIdPolicy(session.chain.id, environment),\n    ].filter((policy) => policy !== undefined);\n    return policies.some((once) => session.actions.some((a) => a.actionTargetSelector === CONSUME_SELECTOR &&\n        isAddressEqual(a.actionTarget, once)) &&\n        session.actions.every((a) => a.actionPolicies.some(({ policy }) => isAddressEqual(policy, once))));\n}\n/**\n * Whether the session's maxAmount is a lifetime budget, from its actions as\n * well as its metadata, so a stored session missing the flag is still caught.\n * A hand-written rule of the same shape is guarded too, which fails closed.\n */\nexport function hasLifetimeBudget(session, environment) {\n    if (session.lifetimeBudget)\n        return true;\n    if (isOneTimeUse(session, environment))\n        return false;\n    return session.actions.some(({ actionTargetSelector, actionPolicies }) => {\n        // approve(address,uint256), transfer(address,uint256)\n        const amountWord = actionTargetSelector === '0x095ea7b3' ||\n            actionTargetSelector === '0xa9059cbb';\n        return actionPolicies.some(({ initData }) => hasCapRule(initData, amountWord));\n    });\n}\nexport async function getSessionDetails(input) {\n    // An enable re-initialises the session's policies, so signing one for an\n    // enabled session hands whoever submits it a fresh lifetime budget. The\n    // nonce is read with the state: an enable after that block spends it.\n    const guarded = (session) => !input.allowBudgetReset && hasLifetimeBudget(session, input.environment);\n    const nonces = await Promise.all(input.sessions.map(async (session) => {\n        if (!guarded(session))\n            return input.readNonce(session);\n        if (!input.readNonceAndEnabled) {\n            throw new Error('getSessionDetails (internal): a lifetime-budget session needs readNonceAndEnabled');\n        }\n        const { nonce, enabled } = await input.readNonceAndEnabled(session);\n        if (enabled) {\n            throw new Error(`The session ${session.permissionId} is already enabled on chain ${session.chain.id}, and its maxAmount is a lifetime budget: signing its enable again would reset that budget. Leave it out of getSessionDetails, or pass { allowBudgetReset: true } to reset it.`);\n        }\n        return nonce;\n    }));\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/** The nonce and enabled state from one call, so both read the same block. */\nexport async function readSessionNonceAndEnabled(input) {\n    const emissary = getSmartSessionEmissaryAddress(input.environment);\n    const [nonce, enabled] = await input.rpc.multicall({ chain: input.chain }, [\n        {\n            address: emissary,\n            abi: nonceAbi,\n            functionName: 'getNonce',\n            args: [input.account, input.lockTag],\n        },\n        {\n            address: emissary,\n            abi: permissionEnabledAbi,\n            functionName: 'isPermissionEnabled',\n            args: [input.account, getPermissionId(input.session)],\n        },\n    ]);\n    if (nonce?.result === undefined || enabled?.result === undefined) {\n        throw new Error(`Could not read the session nonce and enabled state on chain ${input.chain.id}`);\n    }\n    return { nonce: nonce.result, enabled: enabled.result };\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';\nfunction startaleEnvelopeVersion(context) {\n    const envelope = context.accountCapabilities.signatureEnvelope;\n    if (envelope.kind !== 'startale') {\n        throw new Error('Expected Startale signature envelope');\n    }\n    return envelope.version;\n}\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, startaleEnvelopeVersion(input.context)),\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, hashOpStruct, NO_OPS, } 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    if (policy?.originOps?.some(({ chain, required }) => !required && chain.id === session.session.chain.id) &&\n        hashOpStruct(message.mandate.originOps) !== NO_OPS) {\n        throw new Error('This intent needs a pre-claim call, which the session claim may not carry: provide a Permit2 allowance and omit fees or source calls');\n    }\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 results = independentSlots(prepared).map((request) => {\n        const stage = quorumRootStage\n            ? undefined\n            : transcript.stages.find(({ stage: materialized }) => materialized.stageId === request.artifactId);\n        return (quorumRootResult ??\n            (stage\n                ? Object.entries(stage.results).find(([taskId]) => taskId.includes(owner.ownerId))?.[1]\n                : undefined));\n    });\n    const signature = owner.kind === 'ecdsa'\n        ? {\n            kind: 'ecdsa',\n            signer: owner.identity,\n            slots: results.map((result) => independentEcdsaSlot(owner, result)),\n        }\n        : {\n            kind: 'passkey',\n            publicKey: owner.identity,\n            slots: results.map((result) => independentPasskeySlot(owner, result)),\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 independentEcdsaSlot(owner, result) {\n    if (result?.kind !== 'ecdsa-signature') {\n        throw new Error(`Independent owner ${owner.ownerId} did not sign`);\n    }\n    return result.signature;\n}\nfunction independentPasskeySlot(owner, result) {\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.source\n            ? { sourceChains: [signed.prepared.input.source.chain.id] }\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 { toSponsorshipApprovalInput } from '../../clients/orchestrator/sponsorship-approval.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    const request = {\n        account: { svm },\n        // No source, recipient, execution or token: that is what makes this a\n        // creation, and the sponsor funds it.\n        destination: { vm: 'svm', chainId: caip2 },\n        options: { sponsorship },\n    };\n    return { request, intentInput: toSponsorshipApprovalInput(request) };\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, intentInput } = buildSolanaDeploymentRequest(input);\n    const response = await context.quoteClient.createQuote(request, {\n        intentInput,\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, intentInput, 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        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 { toEvmChainReference } from '../../chains/caip2.js';\nimport { resolvePolicyAddresses } from '../../modules/validators/smart-sessions/policies/addresses.js';\nimport { isCodedRefusal, recover, refusal, refusalLog, refuser, } from '../../modules/validators/smart-sessions/refusals.js';\nimport { assertSessionDefinitionInput, sessionPolicyAddresses, toSession, validateSessionDefinition, } from '../../modules/validators/smart-sessions/resolve.js';\nfunction servedWrappedNativeToken(catalog, chainId) {\n    const wrappedNativeToken = catalog.getWrappedNativeToken(chainId)?.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 refusal('WRAPPED_NATIVE_TOKEN_UNSERVED', `createSession: the orchestrator's /chains has no wrapped-native token for chain ${chainId}. The chain must be supported and advertise its wrappedNativeToken.`);\n    }\n    return wrappedNativeToken;\n}\n/**\n * createSession's reads before it resolves: the UniversalActionPolicy copies'\n * code, then `/chains`. A coded refusal goes to `refuse`; anything else, such\n * as a failed read, throws.\n */\nasync function sessionOptions(input, refuse) {\n    await assertUniversalActionCopies(input.rpc, input.definition).catch((error) => {\n        if (!isCodedRefusal(error))\n            throw error;\n        refuse(error);\n    });\n    const catalog = await input.orchestrator.getChainCatalog();\n    // The token only adds an unrestricted session's `deposit()`, so a dry run\n    // still resolves the session without it.\n    const wrappedNativeToken = recover(refuse, () => servedWrappedNativeToken(catalog, input.definition.chain.id));\n    return {\n        environment: input.environment,\n        settlement: catalog.getSettlementCatalog(),\n        ...(wrappedNativeToken ? { wrappedNativeToken } : {}),\n    };\n}\nexport async function createSession(input) {\n    assertSessionDefinitionInput(input.definition);\n    return toSession(input.definition, await sessionOptions(input, refuser()));\n}\n/** The dry run of `createSession`: the same reads and resolution, every refusal recorded. */\nexport async function validateSession(input) {\n    // One log, so a refusal met before resolving stays first, as createSession throws it.\n    const log = refusalLog();\n    try {\n        assertSessionDefinitionInput(input.definition);\n    }\n    catch (error) {\n        log.collect(error);\n        return { refusals: log.refusals };\n    }\n    const options = await sessionOptions(input, refuser(log.collect));\n    return validateSessionDefinition(input.definition, options, log);\n}\n/**\n * Every configured UniversalActionPolicy copy must hold the same code as\n * `universalAction` on the session's chain: a split installs argument rules\n * there.\n */\nasync function assertUniversalActionCopies(rpc, definition) {\n    const addresses = resolvePolicyAddresses(sessionPolicyAddresses(definition));\n    const copies = addresses.universalActionCopies;\n    if (!copies)\n        return;\n    const chain = toEvmChainReference(definition.chain.id);\n    const port = rpc.forChain(chain);\n    const [canonical, ...codes] = await Promise.all([addresses.universalAction, ...copies].map(async (address) => (await port.getCode({ chain }, address)).code));\n    if (!canonical || canonical === '0x') {\n        throw refusal('UNIVERSAL_ACTION_POLICY_NO_CODE', `createSession: universalAction ${addresses.universalAction} has no code on chain ${chain.id}`);\n    }\n    copies.forEach((copy, i) => {\n        if (codes[i] !== canonical) {\n            throw refusal('UNIVERSAL_ACTION_COPY_CODE_MISMATCH', `createSession: universalActionCopies ${copy} does not hold the code of universalAction ${addresses.universalAction} on chain ${chain.id}`);\n        }\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 *\n * The constructor example requires `apiKey`, your integrator's API key loaded\n * securely from your environment. Prefer the explicit `auth` configuration.\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 an authenticated Rhinestone SDK instance.\n     *\n     * `apiKey` is your integrator's API key, loaded securely from your environment.\n     * @param options Shared configuration applied to every account created by this instance\n     * @example\n     * ```ts\n     * import { RhinestoneSDK } from '@rhinestone/sdk'\n     *\n     * const sdk = new RhinestoneSDK({\n     *   auth: { mode: 'apiKey', apiKey },\n     * })\n     * ```\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     *\n     * `owner` is a configured viem signing account; `apiKey` is your integrator's\n     * API key. Account creation derives a handle; it does not deploy it onchain.\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     *\n     * const sdk = new RhinestoneSDK({\n     *   auth: { mode: 'apiKey', apiKey },\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     * Resolves served settlement addresses and verifies deployed UniversalActionPolicy\n     * copies against the canonical bytecode. Store the resolved session rather than\n     * rebuilding an authorized definition under changing catalog defaults.\n     * For a fully offline build, use the standalone `toSession` and pass\n     * `wrappedNativeToken` yourself. Use `crossChainPermits` for settlement scope;\n     * definition-input `claimPolicies` is rejected before any reads, even when empty\n     * or undefined. A stored `Session` is an artifact for enable/sign methods, not\n     * a new definition.\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    /**\n     * Validate a session definition with the same reads as `createSession`.\n     *\n     * Reports stable refusal codes instead of throwing the first refusal. Network\n     * failures still throw. Removed definition-input `claimPolicies` returns a\n     * refusal without network reads. Successful validation includes access and settlement\n     * coverage metadata; it does not enable or sign the session.\n     * For a network-free check, use `validateSession` from `@rhinestone/sdk/smart-sessions`.\n     * @param definition The session definition to resolve\n     * @returns Refusals, warnings and successful access/coverage metadata\n     * @example\n     * ```ts\n     * const { refusals, access } = await sdk.validateSession(definition)\n     * for (const { code, message } of refusals) console.warn(code, message)\n     * if (access?.kind === 'open') console.warn('The session keeps a wildcard fallback')\n     * ```\n     */\n    validateSession(definition) {\n        return this.#sdk.composition.project.validateSession(definition);\n    }\n}\nexport { RhinestoneSDK };\n"],"mappings":";;;;;;;;;;;;AAAA,SAAS,uBAAAA,uBAAqB,aAAAC,mBAAwE;;;ACI/F,IAAM,iCAAiC;AACvC,IAAM,0CACX,iCAAiC,IAAI;;;ACmHvC,IAAM,WAAW,CAAO,OAAsB,QAC5C,UAAU,SAAY,SAAY,IAAI,KAAK;AAE7C,IAAM,mBAAmB,CAAmB,UAC1C,OAAO,YAAY,OAAO,QAAQ,KAAK,EAAE,OAAO,CAAC,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mBAAmB,UAAU,OAAO,MAAM;AACnD;","names":["encodeAbiParameters","keccak256","options","chain","chainId","source","isAddress","crypto","array","pad","crypto","_32n","object","_0n","_1n","_0n","_1n","gcd","Fp","Fp","_1n","_0n","_1n","_0n","_1n","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","bytesToHex","hexToBytes","account","account","hexToBytes","account","account","account","bytesToHex","hexToBytes","isAddress","isAddressEqual","chain","chainId","id","chain","chainId","isAddress","chainId","record","chainId","keccak256","encodeAbiParameters","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","account","delegations","types","array","hashTypedData","keccak256","stringToHex","calls","serializeBigInts","options","signature","instruction","serializeBigInts","options","batch","chain","chainId","options","source","calls","chainId","evmExecution","account","source","sameChain","leg","include","concat","zeroHash","encodeAbiParameters","encodePacked","size","zeroAddress","zeroHash","encodeAbiParameters","keccak256","bytesToHex","hexToBytes","encodePacked","size","encodeAbiParameters","zeroHash","zeroAddress","zeroHash","concat","encodeAbiParameters","encodeFunctionData","concat","encodeAbiParameters","encodePacked","keccak256","maxUint256","toHex","keccak256","concat","encodeAbiParameters","encodePacked","toHex","maxUint256","chainId","refuse","chainId","encodeAbiParameters","isAddressEqual","keccak256","zeroHash","isAddress","size","toFunctionSelector","array","isAddress","size","toFunctionSelector","policies","refuse","chain","isAddressEqual","account","chain","isAddressEqual","policies","encodeAbiParameters","encodePacked","isHex","padHex","toHex","zeroHash","isHex","padHex","toHex","nodeIndex","zeroHash","encodeAbiParameters","encodePacked","policies","policy","split","isAddressEqual","zeroAddress","isAddressEqual","toFunctionSelector","stable","isAddressEqual","toFunctionSelector","zeroAddress","toFunctionSelector","toFunctionSelector","toFunctionSelector","toFunctionSelector","toFunctionSelector","toFunctionSelector","options","chainId","token","toFunctionSelector","isAddressEqual","zeroAddress","leg","account","policies","chainId","TRANSFER_SELECTOR","toFunctionSelector","chain","stable","isAddressEqual","policies","isAddressEqual","zeroAddress","chainId","chain","isAddressEqual","isAddressEqual","pad","toFunctionSelector","chainId","toFunctionSelector","chainId","isAddressEqual","pad","concat","isAddressEqual","pad","parseAbi","slice","toFunctionSelector","parseAbi","toFunctionSelector","TRANSFER_SELECTOR","BPS","chainId","isAddressEqual","refuse","source","destination","concat","slice","pad","allOf","anyOf","isAddressEqual","maxUint64","maxUint256","pad","toFunctionSelector","isAddressEqual","maxUint256","pad","toFunctionSelector","toFunctionSelector","chainId","isAddressEqual","pad","maxUint256","toFunctionSelector","sameRule","calls","account","source","pad","isAddressEqual","chainId","maxUint64","maxUint256","chainId","options","permit","refuse","isAddressEqual","chain","minAmount","settlement","settlementLayers","sameChain","actions","zeroHash","types","zeroHash","types","seconds","seconds","refuse","options","chain","refuse","seconds","chainId","isAddressEqual","signing","seen","zeroHash","policies","keccak256","encodeAbiParameters","account","chain","chainId","account","calls","source","chain","hashTypedData","refuse","account","keccak256","stringToHex","hexToBytes","isAddress","isAddressEqual","isHex","concat","hexToBytes","toHex","chain","account","chain","hexToBytes","concat","toHex","fail","base58","padding","account","chain","toSponsorship","chainId","options","account","source","isAddress","recipient","refuse","destination","isHex","hexToBytes","isAddressEqual","account","chainId","isAddress","unsupported","isRecord","options","destination","source","isAddress","chain","fail","field","options","chain","source","isAddress","account","solana","ctx","destination","chainId","internal","swigId","refuse","hexToBytes","bytesToHex","isAddressEqual","adaptSessionSelection","isAddressEqual","chainId","chainId","chainId","chainId","chain","headers","isAddress","chainId","isObject","isAddress","body","serializeBigInts","chain","isObject","account","options","chainId","custom","entryPoint07Address","chainId","chainId","custom","chain","entryPoint07Address","createPublicClient","chain","createPublicClient","encodeAbiParameters","hashStruct","isAddressEqual","maxUint256","size","account","maxUint256","size","policies","isAddressEqual","hashStruct","isAddressEqual","zeroAddress","isAddressEqual","account","encodeAbiParameters","hashTypedData","keccak256","batch","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","batch","encodePacked","pad","chain","requireSession","account","validatorOwners","encodePacked","pad","chainId","signerInvoker","options","source","owner","sameValidatorId","hexToBytes","isHex","refuse","chainId","isHex","hexToBytes","account","seconds","slowDelayMs","options","entryPoint07Address","chain","concat","toHex","zeroAddress","entryPoint07Address","calls","chain","encodePacked","hashMessage","hashTypedData","pad","zeroHash","hashMessage","hashMessage","hashMessage","hashTypedData","encodePacked","pad","zeroHash","chainId","chainId","refuse","options","chain","canonical","options","chain","account","calls","signRequestedDelegations","referenceChain","zeroAddress","chainId","isAddressEqual","delegations","validatorOwners","isAddress","account","swigAccount","captured","options","chainId","options","keccak256","encodeAbiParameters","chain","account"]}