@aave/client 4.0.0-next.4 → 4.0.0-next.41
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -3
- package/dist/{AaveClient-CgHY2iS9.d.ts → AaveClient-BPNG2Fua.d.ts} +5 -7
- package/dist/{AaveClient-L3v8kWvn.d.cts → AaveClient-CYavo882.d.cts} +5 -7
- package/dist/actions/index.cjs +1 -1
- package/dist/actions/index.cjs.map +1 -1
- package/dist/actions/index.d.cts +289 -171
- package/dist/actions/index.d.ts +289 -171
- package/dist/actions/index.js +1 -1
- package/dist/chunk-N4LXBTGY.js +2 -0
- package/dist/chunk-N4LXBTGY.js.map +1 -0
- package/dist/chunk-TO3PPVNH.js +2 -0
- package/dist/chunk-TO3PPVNH.js.map +1 -0
- package/dist/chunk-XT6Q6AZR.js +2 -0
- package/dist/chunk-XT6Q6AZR.js.map +1 -0
- package/dist/ethers.cjs +1 -1
- package/dist/ethers.cjs.map +1 -1
- package/dist/ethers.d.cts +45 -11
- package/dist/ethers.d.ts +45 -11
- package/dist/ethers.js +1 -1
- package/dist/ethers.js.map +1 -1
- package/dist/index.cjs +2 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +21 -4
- package/dist/index.d.ts +21 -4
- package/dist/index.js +2 -1
- package/dist/index.js.map +1 -1
- package/dist/{options-vB2peXdE.d.cts → options-BX6n3sbh.d.cts} +17 -1
- package/dist/{options-vB2peXdE.d.ts → options-BX6n3sbh.d.ts} +17 -1
- package/dist/privy.cjs +1 -2
- package/dist/privy.cjs.map +1 -1
- package/dist/privy.d.cts +49 -12
- package/dist/privy.d.ts +49 -12
- package/dist/privy.js +1 -1
- package/dist/privy.js.map +1 -1
- package/dist/testing.d.ts +3838 -0
- package/dist/testing.js +546 -0
- package/dist/testing.js.map +1 -0
- package/dist/thirdweb.cjs +1 -2
- package/dist/thirdweb.cjs.map +1 -1
- package/dist/thirdweb.d.cts +52 -16
- package/dist/thirdweb.d.ts +52 -16
- package/dist/thirdweb.js +1 -2
- package/dist/thirdweb.js.map +1 -1
- package/dist/{types-Bu63z0x6.d.cts → types-4gDcMKeo.d.cts} +9 -5
- package/dist/{types-Bu63z0x6.d.ts → types-4gDcMKeo.d.ts} +9 -5
- package/dist/viem.cjs +1 -2
- package/dist/viem.cjs.map +1 -1
- package/dist/viem.d.cts +57 -17
- package/dist/viem.d.ts +57 -17
- package/dist/viem.js +1 -1
- package/package.json +10 -11
- package/dist/chunk-2URLJFKP.js +0 -3
- package/dist/chunk-2URLJFKP.js.map +0 -1
- package/dist/chunk-IFRZEVIE.js +0 -3
- package/dist/chunk-IFRZEVIE.js.map +0 -1
- package/dist/chunk-UXJVSHNC.js +0 -2
- package/dist/chunk-UXJVSHNC.js.map +0 -1
- package/dist/test-utils.cjs +0 -3
- package/dist/test-utils.cjs.map +0 -1
- package/dist/test-utils.d.cts +0 -50
- package/dist/test-utils.d.ts +0 -50
- package/dist/test-utils.js +0 -3
- package/dist/test-utils.js.map +0 -1
package/dist/privy.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/viem.ts","../src/privy.ts"],"names":["devnetChain","defineChain","supportedChains","chainId","transactionError","chain","txHash","request","baseUrl","link","TransactionError","sendTransaction","privy","walletId","hash","sendTransactionAndWait","publicClient","createPublicClient","http","ResultAsync","err","SigningError","waitForTransactionReceipt","receipt","errAsync","okAsync","executePlan","result","ValidationError","sendWith","signERC20Permit","response","signatureFrom","signERC20PermitWith","signSwapTypedData","message","signSwapTypedDataWith"],"mappings":"8HAuEO,IAAMA,CAAAA,CAAqBC,gBAAAA,CAAY,CAC5C,EAAA,CAAI,MAAA,CAAO,QAAA,CAAS,WAAA,CAA2C,EAAE,CAAA,CACjE,IAAA,CAAM,QAAA,CACN,OAAA,CAAS,eAAA,CACT,cAAA,CAAgB,CAAE,KAAM,OAAA,CAAS,MAAA,CAAQ,KAAA,CAAO,QAAA,CAAU,EAAG,CAA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AA,CACkC,CAClC,IAAMQ,CAAAA,CAAU,IAAA,CAAK,KAAA,CAAMR,EAAO,OAAO,CAAA,CACzC,OAAOR,iBAAAA,CAAY,WAAA,CACjBP,CAAAA,CAAM,SAAA,CAAU,QAAA,CAAS,aAAA,CAAc,CACrC,QAAA,CAAAC,CAAAA,CACA,SAAA,CAAW,CACT,MAAA,CAAQc,CAAAA,CAAO,MAAA,CACf,KAAA,CAAOA,CAAAA,CAAO,KAAA,CACd,OAAA,CAAAQ,CAAAA,CACA,WAAA,CAAaR,CAAAA,CAAO,WACtB,CACF,CAAC,CAAA,CACAP,CAAAA,EAAQC,iBAAAA,CAAa,IAAA,CAAKD,CAAG,CAChC,CAAA,CAAE,GAAA,CAAKW,CAAAA,GAAc,CACnB,QAAA,CAAUI,CAAAA,CAAQ,QAAA,CAClB,KAAA,CAAOH,mBAAAA,CAAcD,CAAAA,CAAS,SAAS,CACzC,CAAA,CAAE,CACJ,CAmBO,SAASK,EAAAA,CACdxB,CAAAA,CACAC,CAAAA,CACAc,CAAAA,CACyD,CACzD,OAAOA,CAAAA,CACHO,CAAAA,CAAkBtB,CAAAA,CAAOC,CAAAA,CAAUc,CAAM,CAAA,CACzCO,CAAAA,CAAkB,IAAA,CAAK,IAAA,CAAMtB,CAAAA,CAAOC,CAAQ,CAClD","file":"privy.cjs","sourcesContent":["import {\n CancelError,\n SigningError,\n TransactionError,\n UnexpectedError,\n ValidationError,\n} from '@aave/core';\nimport type {\n CancelSwapTypedData,\n ExecutionPlan,\n PermitTypedDataResponse,\n SwapByIntentTypedData,\n TransactionRequest,\n} from '@aave/graphql';\nimport {\n type ChainId,\n chainId,\n errAsync,\n invariant,\n isObject,\n okAsync,\n ResultAsync,\n signatureFrom,\n type TxHash,\n txHash,\n} from '@aave/types';\nimport {\n type Account,\n type Chain,\n defineChain,\n type ProviderRpcError,\n type RpcError,\n SwitchChainError,\n TransactionExecutionError,\n type Transport,\n type TypedData,\n type TypedDataDomain,\n UserRejectedRequestError,\n type WalletClient,\n} from 'viem';\nimport {\n estimateGas as estimateGasWithViem,\n sendTransaction as sendTransactionWithViem,\n signTypedData,\n waitForTransactionReceipt,\n} from 'viem/actions';\nimport type {\n ERC20PermitHandler,\n ExecutionPlanHandler,\n SwapSignatureHandler,\n TransactionResult,\n} from './types';\n\nfunction isRpcError(err: unknown): err is RpcError {\n return isObject(err) && 'code' in err && 'message' in err;\n}\n\nfunction isProviderRpcError(\n err: unknown,\n): err is ProviderRpcError<{ originalError?: { code: number } }> {\n return isObject(err) &&\n 'name' in err &&\n 'message' in err &&\n 'originalError' in err\n ? isRpcError(err.originalError) && 'code' in err.originalError\n : true;\n}\n\n/**\n * @internal\n */\nexport const devnetChain: Chain = defineChain({\n id: Number.parseInt(import.meta.env.ETHEREUM_TENDERLY_FORK_ID, 10),\n name: 'Devnet',\n network: 'ethereum-fork',\n nativeCurrency: { name: 'Ether', symbol: 'ETH', decimals: 18 },\n rpcUrls: {\n default: { http: [import.meta.env.ETHEREUM_TENDERLY_PUBLIC_RPC] },\n },\n blockExplorers: {\n default: {\n name: 'Devnet Explorer',\n url: import.meta.env.ETHEREUM_TENDERLY_BLOCKEXPLORER,\n },\n },\n});\n\n/**\n * @internal\n */\nexport const supportedChains: Record<\n ChainId,\n ReturnType<typeof defineChain>\n> = {\n // TODO add them back when deployed on these chains\n // [chainId(mainnet.id)]: mainnet,\n // [chainId(sepolia.id)]: sepolia,\n [chainId(devnetChain.id)]: devnetChain,\n};\n\nfunction ensureChain(\n walletClient: WalletClient,\n request: TransactionRequest,\n): ResultAsync<void, CancelError | SigningError> {\n return ResultAsync.fromPromise(walletClient.getChainId(), (err) =>\n SigningError.from(err),\n ).andThen((chainId) => {\n if (chainId === request.chainId) {\n return okAsync();\n }\n\n return ResultAsync.fromPromise(\n walletClient.switchChain({ id: request.chainId }),\n (err) => SigningError.from(err),\n ).orElse((err) => {\n const code = isRpcError(err.cause)\n ? err.cause.code\n : // Unwrapping for MetaMask Mobile\n // https://github.com/MetaMask/metamask-mobile/issues/2944#issuecomment-976988719\n isProviderRpcError(err.cause)\n ? err.cause.data?.originalError?.code\n : undefined;\n\n if (\n code === SwitchChainError.code &&\n request.chainId in supportedChains\n ) {\n return ResultAsync.fromPromise(\n walletClient.addChain({ chain: supportedChains[request.chainId] }),\n (err) => {\n if (isRpcError(err) && err.code === UserRejectedRequestError.code) {\n return CancelError.from(err);\n }\n return SigningError.from(err);\n },\n );\n }\n\n return err.asResultAsync();\n });\n });\n}\n\nfunction estimateGas(\n walletClient: WalletClient,\n request: TransactionRequest,\n): ResultAsync<bigint, SigningError> {\n return ResultAsync.fromPromise(\n estimateGasWithViem(walletClient, {\n account: walletClient.account,\n data: request.data,\n to: request.to,\n value: BigInt(request.value),\n }),\n (err) => SigningError.from(err),\n ).map((gas) => (gas * 115n) / 100n); // 15% buffer\n}\n\nfunction sendEip1559Transaction(\n walletClient: WalletClient<Transport, Chain, Account>,\n request: TransactionRequest,\n): ResultAsync<TxHash, CancelError | SigningError> {\n return estimateGas(walletClient, request)\n .andThen((gas) =>\n ResultAsync.fromPromise(\n sendTransactionWithViem(walletClient, {\n account: walletClient.account,\n data: request.data,\n to: request.to,\n value: BigInt(request.value),\n chain: walletClient.chain,\n gas,\n }),\n (err) => {\n if (err instanceof TransactionExecutionError) {\n const rejected = err.walk(\n (err) => err instanceof UserRejectedRequestError,\n );\n\n if (rejected) {\n return CancelError.from(rejected);\n }\n }\n return SigningError.from(err);\n },\n ),\n )\n .map(txHash);\n}\n\nfunction isWalletClientWithAccount(\n walletClient: WalletClient,\n): walletClient is WalletClient<Transport, Chain, Account> {\n return walletClient.account !== undefined;\n}\n\n/**\n * @internal\n */\nexport function sendTransaction(\n walletClient: WalletClient,\n request: TransactionRequest,\n): ResultAsync<TxHash, CancelError | SigningError> {\n invariant(\n isWalletClientWithAccount(walletClient),\n 'Wallet client with account is required',\n );\n\n return ensureChain(walletClient, request).andThen((_) =>\n sendEip1559Transaction(walletClient, request),\n );\n}\n\n/**\n * @internal\n */\nexport function transactionError(\n chain: Chain | undefined,\n txHash: TxHash,\n request: TransactionRequest,\n): TransactionError {\n const baseUrl = chain?.blockExplorers?.default?.url;\n const link = baseUrl && new URL(`/tx/${txHash}`, baseUrl).toString();\n\n return TransactionError.new({ txHash, request, link });\n}\n\n/**\n * @internal\n */\nexport function waitForTransactionResult(\n walletClient: WalletClient,\n request: TransactionRequest,\n initialTxHash: TxHash,\n): ResultAsync<\n TransactionResult,\n CancelError | TransactionError | UnexpectedError\n> {\n return ResultAsync.fromPromise(\n waitForTransactionReceipt(walletClient, {\n hash: initialTxHash,\n pollingInterval: 100,\n retryCount: 20,\n retryDelay: 50,\n }),\n (err) => UnexpectedError.from(err),\n ).andThen((receipt) => {\n const hash = txHash(receipt.transactionHash);\n\n switch (receipt.status) {\n case 'reverted':\n if (initialTxHash !== hash) {\n return errAsync(CancelError.from(`Transaction replaced by ${hash}`));\n }\n return errAsync(transactionError(walletClient.chain, hash, request));\n case 'success':\n return okAsync({\n // viem's waitForTransactionReceipt supports transaction replacement\n // so it's important to use the transaction hash from the receipt\n txHash: hash,\n operations: request.operations,\n });\n }\n });\n}\n\nfunction sendTransactionAndWait(\n walletClient: WalletClient,\n request: TransactionRequest,\n): ResultAsync<\n TransactionResult,\n CancelError | SigningError | TransactionError | UnexpectedError\n> {\n return sendTransaction(walletClient, request).andThen((hash) =>\n waitForTransactionResult(walletClient, request, hash),\n );\n}\n\nfunction executePlan(\n walletClient: WalletClient,\n result: ExecutionPlan,\n): ReturnType<ExecutionPlanHandler> {\n switch (result.__typename) {\n case 'TransactionRequest':\n return sendTransactionAndWait(walletClient, result);\n\n case 'Erc20ApprovalRequired':\n case 'PreContractActionRequired':\n return sendTransactionAndWait(walletClient, result.transaction).andThen(\n () => sendTransactionAndWait(walletClient, result.originalTransaction),\n );\n\n case 'InsufficientBalanceError':\n return errAsync(ValidationError.fromGqlNode(result));\n }\n}\n\n/**\n * Creates an execution plan handler that sends transactions using the provided wallet client.\n */\nexport function sendWith(walletClient: WalletClient): ExecutionPlanHandler;\n/**\n * Sends execution plan transactions using the provided wallet client.\n */\nexport function sendWith<T extends ExecutionPlan = ExecutionPlan>(\n walletClient: WalletClient,\n result: T,\n): ReturnType<ExecutionPlanHandler<T>>;\nexport function sendWith<T extends ExecutionPlan = ExecutionPlan>(\n walletClient: WalletClient,\n result?: T,\n): ExecutionPlanHandler<T> | ReturnType<ExecutionPlanHandler<T>> {\n return result\n ? executePlan(walletClient, result)\n : executePlan.bind(null, walletClient);\n}\n\nfunction signERC20Permit(\n walletClient: WalletClient,\n result: PermitTypedDataResponse,\n): ReturnType<ERC20PermitHandler> {\n invariant(walletClient.account, 'Wallet account is required');\n\n return ResultAsync.fromPromise(\n signTypedData(walletClient, {\n account: walletClient.account,\n domain: result.domain as TypedDataDomain,\n types: result.types as TypedData,\n primaryType: result.primaryType as keyof typeof result.types,\n message: result.message,\n }),\n (err) => SigningError.from(err),\n ).map((hex) => ({\n deadline: result.message.deadline,\n value: signatureFrom(hex),\n }));\n}\n\n/**\n * Creates an ERC20 permit handler that signs ERC20 permits using the provided wallet client.\n */\nexport function signERC20PermitWith(\n walletClient: WalletClient,\n): ERC20PermitHandler {\n return signERC20Permit.bind(null, walletClient);\n}\n\nfunction signSwapTypedData(\n walletClient: WalletClient,\n result: SwapByIntentTypedData | CancelSwapTypedData,\n): ReturnType<SwapSignatureHandler> {\n invariant(walletClient.account, 'Wallet account is required');\n\n return ResultAsync.fromPromise(\n signTypedData(walletClient, {\n account: walletClient.account,\n domain: result.domain as TypedDataDomain,\n types: result.types as TypedData,\n primaryType: result.primaryType,\n message: JSON.parse(result.message),\n }),\n (err) => SigningError.from(err),\n ).map((hex) => ({\n deadline: JSON.parse(result.message).deadline,\n value: signatureFrom(hex),\n }));\n}\n\n/**\n * @internal\n * Creates a swap signature handler that signs swap typed data using the provided wallet client.\n */\nexport function signSwapTypedDataWith(\n walletClient: WalletClient,\n): SwapSignatureHandler;\n/**\n * @internal\n * Signs swap typed data using the provided wallet client.\n */\nexport function signSwapTypedDataWith(\n walletClient: WalletClient,\n result: SwapByIntentTypedData | CancelSwapTypedData,\n): ReturnType<SwapSignatureHandler>;\nexport function signSwapTypedDataWith(\n walletClient: WalletClient,\n result?: SwapByIntentTypedData | CancelSwapTypedData,\n): SwapSignatureHandler | ReturnType<SwapSignatureHandler> {\n return result\n ? signSwapTypedData(walletClient, result)\n : signSwapTypedData.bind(null, walletClient);\n}\n","import {\n SigningError,\n type TransactionError,\n ValidationError,\n} from '@aave/core';\nimport type {\n CancelSwapTypedData,\n ExecutionPlan,\n PermitTypedDataResponse,\n SwapByIntentTypedData,\n TransactionRequest,\n} from '@aave/graphql';\nimport {\n errAsync,\n okAsync,\n ResultAsync,\n signatureFrom,\n type TxHash,\n txHash,\n} from '@aave/types';\nimport type { PrivyClient } from '@privy-io/server-auth';\nimport { createPublicClient, http } from 'viem';\nimport { waitForTransactionReceipt } from 'viem/actions';\nimport type {\n ERC20PermitHandler,\n ExecutionPlanHandler,\n SwapSignatureHandler,\n TransactionResult,\n} from './types';\nimport { supportedChains, transactionError } from './viem';\n\nasync function sendTransaction(\n privy: PrivyClient,\n request: TransactionRequest,\n walletId: string,\n): Promise<TxHash> {\n const { hash } = await privy.walletApi.ethereum.sendTransaction({\n walletId,\n caip2: `eip155:${request.chainId}`,\n transaction: {\n from: request.from,\n to: request.to,\n value: `0x${BigInt(request.value).toString(16)}`,\n chainId: request.chainId,\n data: request.data,\n },\n });\n return txHash(hash);\n}\n\nfunction sendTransactionAndWait(\n privy: PrivyClient,\n request: TransactionRequest,\n walletId: string,\n): ResultAsync<TransactionResult, SigningError | TransactionError> {\n // TODO: verify it's on the correct chain, ask to switch if possible\n // TODO: verify if wallet account is correct, switch if possible\n const publicClient = createPublicClient({\n chain: supportedChains[request.chainId],\n transport: http(),\n });\n\n return ResultAsync.fromPromise(\n sendTransaction(privy, request, walletId),\n (err) => SigningError.from(err),\n )\n .map(async (hash) =>\n waitForTransactionReceipt(publicClient, {\n hash,\n pollingInterval: 100,\n retryCount: 20,\n retryDelay: 50,\n }),\n )\n .andThen((receipt) => {\n const hash = txHash(receipt.transactionHash);\n\n if (receipt.status === 'reverted') {\n return errAsync(\n transactionError(supportedChains[request.chainId], hash, request),\n );\n }\n return okAsync({\n txHash: hash,\n operations: request.operations,\n });\n });\n}\n\nfunction executePlan(\n privy: PrivyClient,\n walletId: string,\n result: ExecutionPlan,\n): ReturnType<ExecutionPlanHandler> {\n switch (result.__typename) {\n case 'TransactionRequest':\n return sendTransactionAndWait(privy, result, walletId);\n\n case 'Erc20ApprovalRequired':\n case 'PreContractActionRequired':\n return sendTransactionAndWait(\n privy,\n result.transaction,\n walletId,\n ).andThen(() =>\n sendTransactionAndWait(privy, result.originalTransaction, walletId),\n );\n\n case 'InsufficientBalanceError':\n return errAsync(ValidationError.fromGqlNode(result));\n }\n}\n\n/**\n * Creates an execution plan handler that sends transactions using the specified Privy wallet.\n */\nexport function sendWith<T extends ExecutionPlan = ExecutionPlan>(\n privy: PrivyClient,\n walletId: string,\n): ExecutionPlanHandler<T>;\n/**\n * Sends execution plan transactions using the specified Privy wallet.\n */\nexport function sendWith<T extends ExecutionPlan = ExecutionPlan>(\n privy: PrivyClient,\n walletId: string,\n result: T,\n): ReturnType<ExecutionPlanHandler<T>>;\nexport function sendWith<T extends ExecutionPlan = ExecutionPlan>(\n privy: PrivyClient,\n walletId: string,\n result?: T,\n): ExecutionPlanHandler<T> | ReturnType<ExecutionPlanHandler<T>> {\n return result\n ? executePlan(privy, walletId, result)\n : executePlan.bind(null, privy, walletId);\n}\n\nfunction signERC20Permit(\n privy: PrivyClient,\n walletId: string,\n result: PermitTypedDataResponse,\n): ReturnType<ERC20PermitHandler> {\n return ResultAsync.fromPromise(\n privy.walletApi.ethereum.signTypedData({\n walletId,\n typedData: {\n domain: result.domain,\n types: result.types,\n message: result.message,\n primaryType: result.primaryType,\n },\n }),\n (err) => SigningError.from(err),\n ).map((response) => ({\n deadline: result.message.deadline,\n value: signatureFrom(response.signature),\n }));\n}\n\n/**\n * Creates an ERC20 permit handler that signs ERC20 permits using the specified Privy wallet.\n */\nexport function signERC20PermitWith(\n privy: PrivyClient,\n walletId: string,\n): ERC20PermitHandler {\n return signERC20Permit.bind(null, privy, walletId);\n}\n\nfunction signSwapTypedData(\n privy: PrivyClient,\n walletId: string,\n result: SwapByIntentTypedData | CancelSwapTypedData,\n): ReturnType<SwapSignatureHandler> {\n const message = JSON.parse(result.message);\n return ResultAsync.fromPromise(\n privy.walletApi.ethereum.signTypedData({\n walletId,\n typedData: {\n domain: result.domain,\n types: result.types,\n message,\n primaryType: result.primaryType,\n },\n }),\n (err) => SigningError.from(err),\n ).map((response) => ({\n deadline: message.deadline,\n value: signatureFrom(response.signature),\n }));\n}\n\n/**\n * @internal\n * Creates a swap signature handler that signs swap typed data using the specified Privy wallet.\n */\nexport function signSwapTypedDataWith(\n privy: PrivyClient,\n walletId: string,\n): SwapSignatureHandler;\n/**\n * @internal\n * Signs swap typed data using the specified Privy wallet.\n */\nexport function signSwapTypedDataWith(\n privy: PrivyClient,\n walletId: string,\n result: SwapByIntentTypedData | CancelSwapTypedData,\n): ReturnType<SwapSignatureHandler>;\nexport function signSwapTypedDataWith(\n privy: PrivyClient,\n walletId: string,\n result?: SwapByIntentTypedData | CancelSwapTypedData,\n): SwapSignatureHandler | ReturnType<SwapSignatureHandler> {\n return result\n ? signSwapTypedData(privy, walletId, result)\n : signSwapTypedData.bind(null, privy, walletId);\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/adapters.ts","../src/viem.ts","../src/privy.ts"],"names":["hasApprovals","plan","supportsPermit","isOneEntryArray","transactionError","chain","txHash","request","baseUrl","link","TransactionError","allChains","viemChains","sendTransaction","privy","walletId","hash","sendTransactionAndWait","extractChain","publicClient","createPublicClient","http","ResultAsync","err","SigningError","waitForTransactionReceipt","UnexpectedError","receipt","errAsync","okAsync","executePlan","result","approval","ValidationError","sendWith","permitWith","action","permitTypedData","signTypedDataWith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edData } from '@aave/graphql';\nimport { isOneEntryArray } from '@aave/types';\n\ntype WithApprovals = { approvals: Erc20Approval[] };\n\nfunction hasApprovals(plan: unknown): plan is WithApprovals {\n return (\n typeof plan === 'object' &&\n plan !== null &&\n 'approvals' in plan &&\n Array.isArray(plan.approvals)\n );\n}\n\n/**\n * Checks if a plan supports permit (single approval with bySignature).\n * Works with union types - picks any member that has an `approvals` array\n * with a single entry containing `bySignature`.\n *\n * @internal\n */\nexport function supportsPermit<T>(plan: T): plan is T &\n Extract<T, WithApprovals> & {\n approvals: [Erc20Approval & { bySignature: PermitTypedData }];\n } {\n return (\n hasApprovals(plan) &&\n isOneEntryArray(plan.approvals) &&\n !!plan.approvals[0].bySignature\n );\n}\n","import {\n CancelError,\n SigningError,\n TransactionError,\n UnexpectedError,\n ValidationError,\n} from '@aave/core';\nimport type {\n Chain,\n ERC20PermitSignature,\n ExecutionPlan,\n TransactionRequest,\n} from '@aave/graphql';\nimport {\n chainId,\n errAsync,\n invariant,\n isObject,\n okAsync,\n ResultAsync,\n type Signature,\n signatureFrom,\n type TxHash,\n txHash,\n} from '@aave/types';\nimport {\n type Account,\n defineChain,\n type ProviderRpcError,\n type RpcError,\n SwitchChainError,\n TransactionExecutionError,\n type Transport,\n UserRejectedRequestError,\n type Chain as ViemChain,\n type WalletClient,\n} from 'viem';\nimport {\n estimateGas as estimateGasWithViem,\n sendTransaction as sendTransactionWithViem,\n waitForTransactionReceipt,\n} from 'viem/actions';\nimport { mainnet, sepolia } from 'viem/chains';\nimport type { AaveClient } from './AaveClient';\nimport { chain as fetchChain } from './actions';\nimport { supportsPermit } from './adapters';\nimport type {\n ExecutionPlanHandler,\n SignTypedDataError,\n TransactionResult,\n TypedData,\n TypedDataHandler,\n} from './types';\n\nfunction isRpcError(err: unknown): err is RpcError {\n return isObject(err) && 'code' in err && 'message' in err;\n}\n\nfunction isProviderRpcError(\n err: unknown,\n): err is ProviderRpcError<{ originalError?: { code: number } }> {\n return isObject(err) &&\n 'name' in err &&\n 'message' in err &&\n 'originalError' in err\n ? isRpcError(err.originalError) && 'code' in err.originalError\n : true;\n}\n\nfunction signTypedData(\n walletClient: WalletClient,\n data: TypedData,\n): ResultAsync<Signature, SignTypedDataError> {\n invariant(\n walletClient.account,\n 'Wallet account is required to sign typed data',\n );\n\n return ResultAsync.fromPromise(\n walletClient.signTypedData({\n account: walletClient.account,\n domain: data.domain,\n types: data.types,\n primaryType: data.primaryType,\n message: data.message,\n }),\n (err) => {\n if (err instanceof UserRejectedRequestError) {\n return CancelError.from(err);\n }\n return SigningError.from(err);\n },\n ).map(signatureFrom);\n}\n\n/**\n * @internal\n */\nexport function toViemChain(chain: Chain): ViemChain {\n // known chains\n switch (chain.chainId) {\n case chainId(mainnet.id):\n return mainnet;\n\n case chainId(sepolia.id):\n return sepolia;\n }\n\n // most likely a tenderly fork\n return defineChain({\n id: chain.chainId,\n name: chain.name,\n nativeCurrency: {\n name: chain.nativeInfo.name,\n symbol: chain.nativeInfo.symbol,\n decimals: chain.nativeInfo.decimals,\n },\n rpcUrls: { default: { http: [chain.rpcUrl] } },\n blockExplorers: {\n default: {\n name: `${chain.name} Explorer`,\n url: chain.explorerUrl,\n },\n },\n });\n}\n\n/**\n * @internal\n */\nexport function viemChainsFrom(chains: Chain[]): ViemChain[] {\n return chains.map(toViemChain);\n}\n\n/**\n * @internal\n */\nexport function ensureChain(\n aaveClient: AaveClient,\n walletClient: WalletClient,\n request: TransactionRequest,\n): ResultAsync<void, CancelError | SigningError | UnexpectedError> {\n return ResultAsync.fromPromise(walletClient.getChainId(), (err) =>\n SigningError.from(err),\n ).andThen((chainId) => {\n if (chainId === request.chainId) {\n return okAsync();\n }\n\n return fetchChain(\n aaveClient,\n { chainId: request.chainId },\n { batch: false },\n ).andThen((chain) => {\n invariant(chain, `Chain ${request.chainId} is not supported`);\n\n return ResultAsync.fromPromise(\n walletClient.switchChain({ id: request.chainId }),\n (err) => SigningError.from(err),\n ).orElse((err) => {\n const code = isRpcError(err.cause)\n ? err.cause.code\n : // Unwrapping for MetaMask Mobile\n // https://github.com/MetaMask/metamask-mobile/issues/2944#issuecomment-976988719\n isProviderRpcError(err.cause)\n ? err.cause.data?.originalError?.code\n : undefined;\n\n if (code === SwitchChainError.code) {\n return ResultAsync.fromPromise(\n walletClient.addChain({ chain: toViemChain(chain) }),\n (err) => {\n if (\n isRpcError(err) &&\n err.code === UserRejectedRequestError.code\n ) {\n return CancelError.from(err);\n }\n return SigningError.from(err);\n },\n );\n }\n\n return err.asResultAsync();\n });\n });\n });\n}\n\nfunction estimateGas(\n walletClient: WalletClient,\n request: TransactionRequest,\n): ResultAsync<bigint, SigningError> {\n return ResultAsync.fromPromise(\n estimateGasWithViem(walletClient, {\n account: walletClient.account,\n data: request.data,\n to: request.to,\n value: BigInt(request.value),\n }),\n (err) => SigningError.from(err),\n ).map((gas) => (gas * 115n) / 100n); // 15% buffer\n}\n\nfunction sendEip1559Transaction(\n walletClient: WalletClient<Transport, ViemChain, Account>,\n request: TransactionRequest,\n): ResultAsync<TxHash, CancelError | SigningError> {\n return estimateGas(walletClient, request)\n .andThen((gas) =>\n ResultAsync.fromPromise(\n sendTransactionWithViem(walletClient, {\n account: walletClient.account,\n data: request.data,\n to: request.to,\n value: BigInt(request.value),\n chain: walletClient.chain,\n gas,\n }),\n (err) => {\n if (err instanceof TransactionExecutionError) {\n const rejected = err.walk(\n (err) => err instanceof UserRejectedRequestError,\n );\n\n if (rejected) {\n return CancelError.from(rejected);\n }\n }\n return SigningError.from(err);\n },\n ),\n )\n .map(txHash);\n}\n\nfunction isWalletClientWithAccount(\n walletClient: WalletClient,\n): walletClient is WalletClient<Transport, ViemChain, Account> {\n return walletClient.account !== undefined;\n}\n\n/**\n * @internal\n */\nexport function sendTransaction(\n walletClient: WalletClient,\n request: TransactionRequest,\n): ResultAsync<TxHash, CancelError | SigningError> {\n invariant(\n isWalletClientWithAccount(walletClient),\n 'Wallet client with account is required',\n );\n\n return sendEip1559Transaction(walletClient, request);\n}\n\n/**\n * @internal\n */\nexport function transactionError(\n chain: ViemChain | undefined,\n txHash: TxHash,\n request: TransactionRequest,\n): TransactionError {\n const baseUrl = chain?.blockExplorers?.default?.url;\n const link = baseUrl && new URL(`/tx/${txHash}`, baseUrl).toString();\n\n return TransactionError.new({ txHash, request, link });\n}\n\n/**\n * @internal\n */\nexport function waitForTransactionResult(\n walletClient: WalletClient,\n request: TransactionRequest,\n initialTxHash: TxHash,\n): ResultAsync<\n TransactionResult,\n CancelError | TransactionError | UnexpectedError\n> {\n return ResultAsync.fromPromise(\n waitForTransactionReceipt(walletClient, {\n hash: initialTxHash,\n pollingInterval: 100,\n retryCount: 20,\n retryDelay: 50,\n }),\n (err) => UnexpectedError.from(err),\n ).andThen((receipt) => {\n const hash = txHash(receipt.transactionHash);\n\n switch (receipt.status) {\n case 'reverted':\n if (initialTxHash !== hash) {\n return errAsync(CancelError.from(`Transaction replaced by ${hash}`));\n }\n return errAsync(transactionError(walletClient.chain, hash, request));\n case 'success':\n return okAsync({\n // viem's waitForTransactionReceipt supports transaction replacement\n // so it's important to use the transaction hash from the receipt\n txHash: hash,\n operations: request.operations,\n });\n }\n });\n}\n\nfunction sendTransactionAndWait(\n walletClient: WalletClient,\n request: TransactionRequest,\n): ResultAsync<\n TransactionResult,\n CancelError | SigningError | TransactionError | UnexpectedError\n> {\n return sendTransaction(walletClient, request).andThen((hash) =>\n waitForTransactionResult(walletClient, request, hash),\n );\n}\n\nfunction executePlan(\n walletClient: WalletClient,\n result: ExecutionPlan,\n): ReturnType<ExecutionPlanHandler> {\n switch (result.__typename) {\n case 'TransactionRequest':\n return sendTransactionAndWait(walletClient, result);\n\n case 'Erc20ApprovalRequired':\n return result.approvals\n .reduce<ReturnType<typeof sendTransactionAndWait>>(\n (chain, approval) =>\n chain.andThen(() =>\n sendTransactionAndWait(walletClient, approval.byTransaction),\n ),\n okAsync(undefined as never),\n )\n .andThen(() =>\n sendTransactionAndWait(walletClient, result.originalTransaction),\n );\n\n case 'PreContractActionRequired':\n return sendTransactionAndWait(walletClient, result.transaction).andThen(\n () => sendTransactionAndWait(walletClient, result.originalTransaction),\n );\n\n case 'InsufficientBalanceError':\n return errAsync(ValidationError.fromGqlNode(result));\n }\n}\n\n/**\n * Creates an execution plan handler that sends transactions using the provided wallet client.\n */\nexport function sendWith(walletClient: WalletClient): ExecutionPlanHandler;\n/**\n * Sends execution plan transactions using the provided wallet client.\n */\nexport function sendWith<T extends ExecutionPlan = ExecutionPlan>(\n walletClient: WalletClient,\n result: T,\n): ReturnType<ExecutionPlanHandler<T>>;\nexport function sendWith<T extends ExecutionPlan = ExecutionPlan>(\n walletClient: WalletClient,\n result?: T,\n): ExecutionPlanHandler<T> | ReturnType<ExecutionPlanHandler<T>> {\n return result\n ? executePlan(walletClient, result)\n : executePlan.bind(null, walletClient);\n}\n\n/**\n * Creates a function that signs EIP-712 typed data (ERC-20 permits, swap intents, etc.) using the provided wallet client.\n *\n * @param walletClient - The wallet client to use for signing.\n * @returns A function that takes typed data and returns a ResultAsync containing the raw signature.\n *\n * ```ts\n * const result = await prepareSwapCancel(client, request)\n * .andThen(signTypedDataWith(wallet));\n * ```\n */\nexport function signTypedDataWith(walletClient: WalletClient): TypedDataHandler;\n\n/**\n * Signs EIP-712 typed data (ERC-20 permits, swap intents, etc.) using the provided wallet client.\n *\n * @param walletClient - The wallet client to use for signing.\n * @param data - The typed data to sign.\n * @returns A ResultAsync containing the raw signature.\n *\n * ```ts\n * const result = await signTypedDataWith(wallet, typedData);\n * ```\n */\nexport function signTypedDataWith(\n walletClient: WalletClient,\n data: TypedData,\n): ReturnType<TypedDataHandler>;\n\nexport function signTypedDataWith(\n walletClient: WalletClient,\n data?: TypedData,\n): TypedDataHandler | ReturnType<TypedDataHandler> {\n if (data === undefined) {\n return signTypedData.bind(null, walletClient);\n }\n return signTypedData(walletClient, data);\n}\n\n/**\n * Handles ERC20 permit signing for actions that require token approval.\n *\n * Calls the action to get an initial execution plan. If the plan requires ERC20 approval\n * and the token supports permit signatures, signs the permit and re-calls the action\n * with the signature to get a new plan that can be sent directly.\n *\n * ```ts\n * const result = await permitWith(walletClient, (permitSig) =>\n * supply(client, {\n * reserve: reserve.id,\n * amount: { erc20: { value: amount, permitSig } },\n * sender: evmAddress(walletClient.account.address),\n * })\n * )\n * .andThen(sendWith(walletClient))\n * .andThen(client.waitForTransaction);\n * ```\n *\n * @param walletClient - The wallet client to use for signing permits.\n * @param action - A function that returns an execution plan, accepting an optional permit signature.\n * @returns A ResultAsync containing the resolved ExecutionPlan ready to be sent with `sendWith`.\n */\nexport function permitWith<E>(\n walletClient: WalletClient,\n action: (permitSig?: ERC20PermitSignature) => ResultAsync<ExecutionPlan, E>,\n): ResultAsync<ExecutionPlan, E | SignTypedDataError> {\n return action().andThen((result) => {\n if (supportsPermit(result)) {\n const permitTypedData = result.approvals[0].bySignature;\n // Sign and wrap with deadline\n return signTypedDataWith(walletClient, permitTypedData)\n .map((signature) => ({\n deadline: permitTypedData.message.deadline as number,\n value: signature,\n }))\n .andThen((permitSig) => action(permitSig));\n }\n return okAsync(result);\n });\n}\n","import {\n SigningError,\n type TransactionError,\n UnexpectedError,\n ValidationError,\n} from '@aave/core';\nimport type {\n ERC20PermitSignature,\n ExecutionPlan,\n TransactionRequest,\n} from '@aave/graphql';\nimport {\n errAsync,\n okAsync,\n ResultAsync,\n signatureFrom,\n type TxHash,\n txHash,\n} from '@aave/types';\nimport type { PrivyClient } from '@privy-io/server-auth';\nimport { createPublicClient, extractChain, http } from 'viem';\nimport { waitForTransactionReceipt } from 'viem/actions';\nimport * as viemChains from 'viem/chains';\nimport { supportsPermit } from './adapters';\nimport type {\n ExecutionPlanHandler,\n SignTypedDataError,\n TransactionResult,\n TypedData,\n TypedDataHandler,\n} from './types';\nimport { transactionError } from './viem';\n\nconst allChains = Object.values(viemChains);\n\nasync function sendTransaction(\n privy: PrivyClient,\n request: TransactionRequest,\n walletId: string,\n): Promise<TxHash> {\n const { hash } = await privy.walletApi.ethereum.sendTransaction({\n walletId,\n caip2: `eip155:${request.chainId}`,\n transaction: {\n from: request.from,\n to: request.to,\n value: `0x${BigInt(request.value).toString(16)}`,\n chainId: request.chainId,\n data: request.data,\n },\n });\n return txHash(hash);\n}\n\nfunction sendTransactionAndWait(\n privy: PrivyClient,\n request: TransactionRequest,\n walletId: string,\n): ResultAsync<\n TransactionResult,\n SigningError | TransactionError | UnexpectedError\n> {\n const chain = extractChain({\n chains: allChains,\n id: request.chainId as (typeof allChains)[number]['id'],\n });\n\n const publicClient = createPublicClient({\n chain,\n transport: http(),\n });\n\n return ResultAsync.fromPromise(\n sendTransaction(privy, request, walletId),\n (err) => SigningError.from(err),\n )\n .andThen((hash) =>\n ResultAsync.fromPromise(\n waitForTransactionReceipt(publicClient, {\n hash,\n pollingInterval: 100,\n retryCount: 20,\n retryDelay: 50,\n }),\n (err) => UnexpectedError.from(err),\n ),\n )\n .andThen((receipt) => {\n const hash = txHash(receipt.transactionHash);\n\n if (receipt.status === 'reverted') {\n return errAsync(transactionError(chain, hash, request));\n }\n return okAsync({\n txHash: hash,\n operations: request.operations,\n });\n });\n}\n\nfunction executePlan(\n privy: PrivyClient,\n walletId: string,\n result: ExecutionPlan,\n): ReturnType<ExecutionPlanHandler> {\n switch (result.__typename) {\n case 'TransactionRequest':\n return sendTransactionAndWait(privy, result, walletId);\n\n case 'Erc20ApprovalRequired':\n return result.approvals\n .reduce<ReturnType<typeof sendTransactionAndWait>>(\n (chain, approval) =>\n chain.andThen(() =>\n sendTransactionAndWait(privy, approval.byTransaction, walletId),\n ),\n okAsync(undefined as never),\n )\n .andThen(() =>\n sendTransactionAndWait(privy, result.originalTransaction, walletId),\n );\n\n case 'PreContractActionRequired':\n return sendTransactionAndWait(\n privy,\n result.transaction,\n walletId,\n ).andThen(() =>\n sendTransactionAndWait(privy, result.originalTransaction, walletId),\n );\n\n case 'InsufficientBalanceError':\n return errAsync(ValidationError.fromGqlNode(result));\n }\n}\n\n/**\n * Creates an execution plan handler that sends transactions using the specified Privy wallet.\n */\nexport function sendWith<T extends ExecutionPlan = ExecutionPlan>(\n privy: PrivyClient,\n walletId: string,\n): ExecutionPlanHandler<T>;\n/**\n * Sends execution plan transactions using the specified Privy wallet.\n */\nexport function sendWith<T extends ExecutionPlan = ExecutionPlan>(\n privy: PrivyClient,\n walletId: string,\n result: T,\n): ReturnType<ExecutionPlanHandler<T>>;\nexport function sendWith<T extends ExecutionPlan = ExecutionPlan>(\n privy: PrivyClient,\n walletId: string,\n result?: T,\n): ExecutionPlanHandler<T> | ReturnType<ExecutionPlanHandler<T>> {\n return result\n ? executePlan(privy, walletId, result)\n : executePlan.bind(null, privy, walletId);\n}\n\n/**\n * Handles ERC20 permit signing for actions that require token approval.\n *\n * Calls the action to get an initial execution plan. If the plan requires ERC20 approval\n * and the token supports permit signatures, signs the permit and re-calls the action\n * with the signature to get a new plan that can be sent directly.\n *\n * ```ts\n * const result = await permitWith(privy, walletId, (permitSig) =>\n * supply(client, {\n * reserve: reserve.id,\n * amount: { erc20: { value: amount, permitSig } },\n * sender: evmAddress(walletAddress),\n * })\n * )\n * .andThen(sendWith(privy, walletId))\n * .andThen(client.waitForTransaction);\n * ```\n *\n * @param privy - The Privy client for signing permits.\n * @param walletId - The ID of the Privy wallet to use.\n * @param action - A function that returns an execution plan, accepting an optional permit signature.\n * @returns A ResultAsync containing the resolved ExecutionPlan ready to be sent with `sendWith`.\n */\nexport function permitWith<E>(\n privy: PrivyClient,\n walletId: string,\n action: (permitSig?: ERC20PermitSignature) => ResultAsync<ExecutionPlan, E>,\n): ResultAsync<ExecutionPlan, E | SignTypedDataError> {\n return action().andThen((result) => {\n if (supportsPermit(result)) {\n const permitTypedData = result.approvals[0].bySignature;\n return signTypedDataWith(privy, walletId, permitTypedData)\n .map((signature) => ({\n deadline: permitTypedData.message.deadline as number,\n value: signature,\n }))\n .andThen((permitSig) => action(permitSig));\n }\n return okAsync(result);\n });\n}\n\nfunction signTypedData(\n privy: PrivyClient,\n walletId: string,\n data: TypedData,\n): ResultAsync<string, SigningError> {\n return ResultAsync.fromPromise(\n privy.walletApi.ethereum.signTypedData({\n walletId,\n typedData: {\n domain: data.domain,\n types: data.types,\n message: data.message,\n primaryType: data.primaryType,\n },\n }),\n (err) => SigningError.from(err),\n ).map((response) => response.signature);\n}\n\n/**\n * Creates a function that signs EIP-712 typed data (ERC-20 permits, swap intents, etc.) using the specified Privy wallet.\n *\n * @param privy - The Privy client instance.\n * @param walletId - The wallet ID to use for signing.\n * @returns A function that takes typed data and returns a ResultAsync containing the raw signature.\n *\n * ```ts\n * const result = await prepareSwapCancel(client, request)\n * .andThen(signTypedDataWith(privy, walletId));\n * ```\n */\nexport function signTypedDataWith(\n privy: PrivyClient,\n walletId: string,\n): TypedDataHandler;\n\n/**\n * Signs EIP-712 typed data (ERC-20 permits, swap intents, etc.) using the specified Privy wallet.\n *\n * @param privy - The Privy client instance.\n * @param walletId - The wallet ID to use for signing.\n * @param data - The typed data to sign.\n * @returns A ResultAsync containing the raw signature.\n *\n * ```ts\n * const result = await signTypedDataWith(privy, walletId, typedData);\n * ```\n */\nexport function signTypedDataWith(\n privy: PrivyClient,\n walletId: string,\n data: TypedData,\n): ReturnType<TypedDataHandler>;\n\nexport function signTypedDataWith(\n privy: PrivyClient,\n walletId: string,\n data?: TypedData,\n): TypedDataHandler | ReturnType<TypedDataHandler> {\n if (data === undefined) {\n return (typedData: TypedData) =>\n signTypedData(privy, walletId, typedData).map(signatureFrom);\n }\n return signTypedData(privy, walletId, data).map(signatureFrom);\n}\n"]}
|
package/dist/privy.d.cts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { ExecutionPlan,
|
|
1
|
+
import { ExecutionPlan, ERC20PermitSignature } from '@aave/graphql';
|
|
2
|
+
import { ResultAsync } from '@aave/types';
|
|
2
3
|
import { PrivyClient } from '@privy-io/server-auth';
|
|
3
|
-
import { E as ExecutionPlanHandler, a as
|
|
4
|
+
import { E as ExecutionPlanHandler, S as SignTypedDataError, a as TypedDataHandler, b as TypedData } from './types-4gDcMKeo.cjs';
|
|
4
5
|
import '@aave/core';
|
|
5
|
-
import '@aave/types';
|
|
6
6
|
|
|
7
7
|
/**
|
|
8
8
|
* Creates an execution plan handler that sends transactions using the specified Privy wallet.
|
|
@@ -13,18 +13,55 @@ declare function sendWith<T extends ExecutionPlan = ExecutionPlan>(privy: PrivyC
|
|
|
13
13
|
*/
|
|
14
14
|
declare function sendWith<T extends ExecutionPlan = ExecutionPlan>(privy: PrivyClient, walletId: string, result: T): ReturnType<ExecutionPlanHandler<T>>;
|
|
15
15
|
/**
|
|
16
|
-
*
|
|
16
|
+
* Handles ERC20 permit signing for actions that require token approval.
|
|
17
|
+
*
|
|
18
|
+
* Calls the action to get an initial execution plan. If the plan requires ERC20 approval
|
|
19
|
+
* and the token supports permit signatures, signs the permit and re-calls the action
|
|
20
|
+
* with the signature to get a new plan that can be sent directly.
|
|
21
|
+
*
|
|
22
|
+
* ```ts
|
|
23
|
+
* const result = await permitWith(privy, walletId, (permitSig) =>
|
|
24
|
+
* supply(client, {
|
|
25
|
+
* reserve: reserve.id,
|
|
26
|
+
* amount: { erc20: { value: amount, permitSig } },
|
|
27
|
+
* sender: evmAddress(walletAddress),
|
|
28
|
+
* })
|
|
29
|
+
* )
|
|
30
|
+
* .andThen(sendWith(privy, walletId))
|
|
31
|
+
* .andThen(client.waitForTransaction);
|
|
32
|
+
* ```
|
|
33
|
+
*
|
|
34
|
+
* @param privy - The Privy client for signing permits.
|
|
35
|
+
* @param walletId - The ID of the Privy wallet to use.
|
|
36
|
+
* @param action - A function that returns an execution plan, accepting an optional permit signature.
|
|
37
|
+
* @returns A ResultAsync containing the resolved ExecutionPlan ready to be sent with `sendWith`.
|
|
17
38
|
*/
|
|
18
|
-
declare function
|
|
39
|
+
declare function permitWith<E>(privy: PrivyClient, walletId: string, action: (permitSig?: ERC20PermitSignature) => ResultAsync<ExecutionPlan, E>): ResultAsync<ExecutionPlan, E | SignTypedDataError>;
|
|
19
40
|
/**
|
|
20
|
-
*
|
|
21
|
-
*
|
|
41
|
+
* Creates a function that signs EIP-712 typed data (ERC-20 permits, swap intents, etc.) using the specified Privy wallet.
|
|
42
|
+
*
|
|
43
|
+
* @param privy - The Privy client instance.
|
|
44
|
+
* @param walletId - The wallet ID to use for signing.
|
|
45
|
+
* @returns A function that takes typed data and returns a ResultAsync containing the raw signature.
|
|
46
|
+
*
|
|
47
|
+
* ```ts
|
|
48
|
+
* const result = await prepareSwapCancel(client, request)
|
|
49
|
+
* .andThen(signTypedDataWith(privy, walletId));
|
|
50
|
+
* ```
|
|
22
51
|
*/
|
|
23
|
-
declare function
|
|
52
|
+
declare function signTypedDataWith(privy: PrivyClient, walletId: string): TypedDataHandler;
|
|
24
53
|
/**
|
|
25
|
-
*
|
|
26
|
-
*
|
|
54
|
+
* Signs EIP-712 typed data (ERC-20 permits, swap intents, etc.) using the specified Privy wallet.
|
|
55
|
+
*
|
|
56
|
+
* @param privy - The Privy client instance.
|
|
57
|
+
* @param walletId - The wallet ID to use for signing.
|
|
58
|
+
* @param data - The typed data to sign.
|
|
59
|
+
* @returns A ResultAsync containing the raw signature.
|
|
60
|
+
*
|
|
61
|
+
* ```ts
|
|
62
|
+
* const result = await signTypedDataWith(privy, walletId, typedData);
|
|
63
|
+
* ```
|
|
27
64
|
*/
|
|
28
|
-
declare function
|
|
65
|
+
declare function signTypedDataWith(privy: PrivyClient, walletId: string, data: TypedData): ReturnType<TypedDataHandler>;
|
|
29
66
|
|
|
30
|
-
export {
|
|
67
|
+
export { permitWith, sendWith, signTypedDataWith };
|
package/dist/privy.d.ts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { ExecutionPlan,
|
|
1
|
+
import { ExecutionPlan, ERC20PermitSignature } from '@aave/graphql';
|
|
2
|
+
import { ResultAsync } from '@aave/types';
|
|
2
3
|
import { PrivyClient } from '@privy-io/server-auth';
|
|
3
|
-
import { E as ExecutionPlanHandler, a as
|
|
4
|
+
import { E as ExecutionPlanHandler, S as SignTypedDataError, a as TypedDataHandler, b as TypedData } from './types-4gDcMKeo.js';
|
|
4
5
|
import '@aave/core';
|
|
5
|
-
import '@aave/types';
|
|
6
6
|
|
|
7
7
|
/**
|
|
8
8
|
* Creates an execution plan handler that sends transactions using the specified Privy wallet.
|
|
@@ -13,18 +13,55 @@ declare function sendWith<T extends ExecutionPlan = ExecutionPlan>(privy: PrivyC
|
|
|
13
13
|
*/
|
|
14
14
|
declare function sendWith<T extends ExecutionPlan = ExecutionPlan>(privy: PrivyClient, walletId: string, result: T): ReturnType<ExecutionPlanHandler<T>>;
|
|
15
15
|
/**
|
|
16
|
-
*
|
|
16
|
+
* Handles ERC20 permit signing for actions that require token approval.
|
|
17
|
+
*
|
|
18
|
+
* Calls the action to get an initial execution plan. If the plan requires ERC20 approval
|
|
19
|
+
* and the token supports permit signatures, signs the permit and re-calls the action
|
|
20
|
+
* with the signature to get a new plan that can be sent directly.
|
|
21
|
+
*
|
|
22
|
+
* ```ts
|
|
23
|
+
* const result = await permitWith(privy, walletId, (permitSig) =>
|
|
24
|
+
* supply(client, {
|
|
25
|
+
* reserve: reserve.id,
|
|
26
|
+
* amount: { erc20: { value: amount, permitSig } },
|
|
27
|
+
* sender: evmAddress(walletAddress),
|
|
28
|
+
* })
|
|
29
|
+
* )
|
|
30
|
+
* .andThen(sendWith(privy, walletId))
|
|
31
|
+
* .andThen(client.waitForTransaction);
|
|
32
|
+
* ```
|
|
33
|
+
*
|
|
34
|
+
* @param privy - The Privy client for signing permits.
|
|
35
|
+
* @param walletId - The ID of the Privy wallet to use.
|
|
36
|
+
* @param action - A function that returns an execution plan, accepting an optional permit signature.
|
|
37
|
+
* @returns A ResultAsync containing the resolved ExecutionPlan ready to be sent with `sendWith`.
|
|
17
38
|
*/
|
|
18
|
-
declare function
|
|
39
|
+
declare function permitWith<E>(privy: PrivyClient, walletId: string, action: (permitSig?: ERC20PermitSignature) => ResultAsync<ExecutionPlan, E>): ResultAsync<ExecutionPlan, E | SignTypedDataError>;
|
|
19
40
|
/**
|
|
20
|
-
*
|
|
21
|
-
*
|
|
41
|
+
* Creates a function that signs EIP-712 typed data (ERC-20 permits, swap intents, etc.) using the specified Privy wallet.
|
|
42
|
+
*
|
|
43
|
+
* @param privy - The Privy client instance.
|
|
44
|
+
* @param walletId - The wallet ID to use for signing.
|
|
45
|
+
* @returns A function that takes typed data and returns a ResultAsync containing the raw signature.
|
|
46
|
+
*
|
|
47
|
+
* ```ts
|
|
48
|
+
* const result = await prepareSwapCancel(client, request)
|
|
49
|
+
* .andThen(signTypedDataWith(privy, walletId));
|
|
50
|
+
* ```
|
|
22
51
|
*/
|
|
23
|
-
declare function
|
|
52
|
+
declare function signTypedDataWith(privy: PrivyClient, walletId: string): TypedDataHandler;
|
|
24
53
|
/**
|
|
25
|
-
*
|
|
26
|
-
*
|
|
54
|
+
* Signs EIP-712 typed data (ERC-20 permits, swap intents, etc.) using the specified Privy wallet.
|
|
55
|
+
*
|
|
56
|
+
* @param privy - The Privy client instance.
|
|
57
|
+
* @param walletId - The wallet ID to use for signing.
|
|
58
|
+
* @param data - The typed data to sign.
|
|
59
|
+
* @returns A ResultAsync containing the raw signature.
|
|
60
|
+
*
|
|
61
|
+
* ```ts
|
|
62
|
+
* const result = await signTypedDataWith(privy, walletId, typedData);
|
|
63
|
+
* ```
|
|
27
64
|
*/
|
|
28
|
-
declare function
|
|
65
|
+
declare function signTypedDataWith(privy: PrivyClient, walletId: string, data: TypedData): ReturnType<TypedDataHandler>;
|
|
29
66
|
|
|
30
|
-
export {
|
|
67
|
+
export { permitWith, sendWith, signTypedDataWith };
|
package/dist/privy.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import {e}from'./chunk-TO3PPVNH.js';import {a}from'./chunk-N4LXBTGY.js';import'./chunk-XT6Q6AZR.js';import {ValidationError,SigningError,UnexpectedError}from'@aave/core';import {okAsync,signatureFrom,errAsync,ResultAsync,txHash}from'@aave/types';import {extractChain,createPublicClient,http}from'viem';import {waitForTransactionReceipt}from'viem/actions';import*as R from'viem/chains';var D=Object.values(R);async function H(e,n,t){let{hash:r}=await e.walletApi.ethereum.sendTransaction({walletId:t,caip2:`eip155:${n.chainId}`,transaction:{from:n.from,to:n.to,value:`0x${BigInt(n.value).toString(16)}`,chainId:n.chainId,data:n.data}});return txHash(r)}function o(e$1,n,t){let r=extractChain({chains:D,id:n.chainId}),i=createPublicClient({chain:r,transport:http()});return ResultAsync.fromPromise(H(e$1,n,t),a=>SigningError.from(a)).andThen(a=>ResultAsync.fromPromise(waitForTransactionReceipt(i,{hash:a,pollingInterval:100,retryCount:20,retryDelay:50}),s=>UnexpectedError.from(s))).andThen(a=>{let s=txHash(a.transactionHash);return a.status==="reverted"?errAsync(e(r,s,n)):okAsync({txHash:s,operations:n.operations})})}function y(e,n,t){switch(t.__typename){case "TransactionRequest":return o(e,t,n);case "Erc20ApprovalRequired":return t.approvals.reduce((r,i)=>r.andThen(()=>o(e,i.byTransaction,n)),okAsync(void 0)).andThen(()=>o(e,t.originalTransaction,n));case "PreContractActionRequired":return o(e,t.transaction,n).andThen(()=>o(e,t.originalTransaction,n));case "InsufficientBalanceError":return errAsync(ValidationError.fromGqlNode(t))}}function F(e,n,t){return t?y(e,n,t):y.bind(null,e,n)}function U(e,n,t){return t().andThen(r=>{if(a(r)){let i=r.approvals[0].bySignature;return A(e,n,i).map(a=>({deadline:i.message.deadline,value:a})).andThen(a=>t(a))}return okAsync(r)})}function T(e,n,t){return ResultAsync.fromPromise(e.walletApi.ethereum.signTypedData({walletId:n,typedData:{domain:t.domain,types:t.types,message:t.message,primaryType:t.primaryType}}),r=>SigningError.from(r)).map(r=>r.signature)}function A(e,n,t){return t===void 0?r=>T(e,n,r).map(signatureFrom):T(e,n,t).map(signatureFrom)}export{U as permitWith,F as sendWith,A as signTypedDataWith};//# sourceMappingURL=privy.js.map
|
|
2
2
|
//# sourceMappingURL=privy.js.map
|
package/dist/privy.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/privy.ts"],"names":["sendTransaction","privy","request","walletId","hash","txHash","sendTransactionAndWait","publicClient","createPublicClient","supportedChains","http","ResultAsync","err","SigningError","waitForTransactionReceipt","receipt","errAsync","transactionError","okAsync","executePlan","result","ValidationError","sendWith","signERC20Permit","response","signatureFrom","signERC20PermitWith","signSwapTypedData","message","signSwapTypedDataWith"],"mappings":"+QA+BA,eAAeA,EACbC,CAAAA,CACAC,CAAAA,CACAC,EACiB,CACjB,GAAM,CAAE,IAAA,CAAAC,CAAK,EAAI,MAAMH,CAAAA,CAAM,UAAU,QAAA,CAAS,eAAA,CAAgB,CAC9D,QAAA,CAAAE,CAAAA,CACA,MAAO,CAAA,OAAA,EAAUD,CAAAA,CAAQ,OAAO,CAAA,CAAA,CAChC,WAAA,CAAa,CACX,IAAA,CAAMA,CAAAA,CAAQ,KACd,EAAA,CAAIA,CAAAA,CAAQ,GACZ,KAAA,CAAO,CAAA,EAAA,EAAK,OAAOA,CAAAA,CAAQ,KAAK,EAAE,QAAA,CAAS,EAAE,CAAC,CAAA,CAAA,CAC9C,OAAA,CAASA,EAAQ,OAAA,CACjB,IAAA,CAAMA,EAAQ,IAChB,CACF,CAAC,CAAA,CACD,OAAOG,OAAOD,CAAI,CACpB,CAEA,SAASE,CAAAA,CACPL,EACAC,CAAAA,CACAC,CAAAA,CACiE,CAGjE,IAAMI,CAAAA,CAAeC,mBAAmB,CACtC,KAAA,CAAOC,EAAgBP,CAAAA,CAAQ,OAAO,EACtC,SAAA,CAAWQ,IAAAA,EACb,CAAC,CAAA,CAED,OAAOC,WAAAA,CAAY,WAAA,CACjBX,EAAgBC,CAAAA,CAAOC,CAAAA,CAASC,CAAQ,CAAA,CACvCS,CAAAA,EAAQC,aAAa,IAAA,CAAKD,CAAG,CAChC,CAAA,CACG,GAAA,CAAI,MAAOR,CAAAA,EACVU,yBAAAA,CAA0BP,EAAc,CACtC,IAAA,CAAAH,EAC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ourcesContent":["import {\n SigningError,\n type TransactionError,\n ValidationError,\n} from '@aave/core';\nimport type {\n CancelSwapTypedData,\n ExecutionPlan,\n PermitTypedDataResponse,\n SwapByIntentTypedData,\n TransactionRequest,\n} from '@aave/graphql';\nimport {\n errAsync,\n okAsync,\n ResultAsync,\n signatureFrom,\n type TxHash,\n txHash,\n} from '@aave/types';\nimport type { PrivyClient } from '@privy-io/server-auth';\nimport { createPublicClient, http } from 'viem';\nimport { waitForTransactionReceipt } from 'viem/actions';\nimport type {\n ERC20PermitHandler,\n ExecutionPlanHandler,\n SwapSignatureHandler,\n TransactionResult,\n} from './types';\nimport { supportedChains, transactionError } from './viem';\n\nasync function sendTransaction(\n privy: PrivyClient,\n request: TransactionRequest,\n walletId: string,\n): Promise<TxHash> {\n const { hash } = await privy.walletApi.ethereum.sendTransaction({\n walletId,\n caip2: `eip155:${request.chainId}`,\n transaction: {\n from: request.from,\n to: request.to,\n value: `0x${BigInt(request.value).toString(16)}`,\n chainId: request.chainId,\n data: request.data,\n },\n });\n return txHash(hash);\n}\n\nfunction sendTransactionAndWait(\n privy: PrivyClient,\n request: TransactionRequest,\n walletId: string,\n): ResultAsync<TransactionResult, SigningError | TransactionError> {\n // TODO: verify it's on the correct chain, ask to switch if possible\n // TODO: verify if wallet account is correct, switch if possible\n const publicClient = createPublicClient({\n chain: supportedChains[request.chainId],\n transport: http(),\n });\n\n return ResultAsync.fromPromise(\n sendTransaction(privy, request, walletId),\n (err) => SigningError.from(err),\n )\n .map(async (hash) =>\n waitForTransactionReceipt(publicClient, {\n hash,\n pollingInterval: 100,\n retryCount: 20,\n retryDelay: 50,\n }),\n )\n .andThen((receipt) => {\n const hash = txHash(receipt.transactionHash);\n\n if (receipt.status === 'reverted') {\n return errAsync(\n transactionError(supportedChains[request.chainId], hash, request),\n );\n }\n return okAsync({\n txHash: hash,\n operations: request.operations,\n });\n });\n}\n\nfunction executePlan(\n privy: PrivyClient,\n walletId: string,\n result: ExecutionPlan,\n): ReturnType<ExecutionPlanHandler> {\n switch (result.__typename) {\n case 'TransactionRequest':\n return sendTransactionAndWait(privy, result, walletId);\n\n case 'Erc20ApprovalRequired':\n case 'PreContractActionRequired':\n return sendTransactionAndWait(\n privy,\n result.transaction,\n walletId,\n ).andThen(() =>\n sendTransactionAndWait(privy, result.originalTransaction, walletId),\n );\n\n case 'InsufficientBalanceError':\n return errAsync(ValidationError.fromGqlNode(result));\n }\n}\n\n/**\n * Creates an execution plan handler that sends transactions using the specified Privy wallet.\n */\nexport function sendWith<T extends ExecutionPlan = ExecutionPlan>(\n privy: PrivyClient,\n walletId: string,\n): ExecutionPlanHandler<T>;\n/**\n * Sends execution plan transactions using the specified Privy wallet.\n */\nexport function sendWith<T extends ExecutionPlan = ExecutionPlan>(\n privy: PrivyClient,\n walletId: string,\n result: T,\n): ReturnType<ExecutionPlanHandler<T>>;\nexport function sendWith<T extends ExecutionPlan = ExecutionPlan>(\n privy: PrivyClient,\n walletId: string,\n result?: T,\n): ExecutionPlanHandler<T> | ReturnType<ExecutionPlanHandler<T>> {\n return result\n ? executePlan(privy, walletId, result)\n : executePlan.bind(null, privy, walletId);\n}\n\nfunction signERC20Permit(\n privy: PrivyClient,\n walletId: string,\n result: PermitTypedDataResponse,\n): ReturnType<ERC20PermitHandler> {\n return ResultAsync.fromPromise(\n privy.walletApi.ethereum.signTypedData({\n walletId,\n typedData: {\n domain: result.domain,\n types: result.types,\n message: result.message,\n primaryType: result.primaryType,\n },\n }),\n (err) => SigningError.from(err),\n ).map((response) => ({\n deadline: result.message.deadline,\n value: signatureFrom(response.signature),\n }));\n}\n\n/**\n * Creates an ERC20 permit handler that signs ERC20 permits using the specified Privy wallet.\n */\nexport function signERC20PermitWith(\n privy: PrivyClient,\n walletId: string,\n): ERC20PermitHandler {\n return signERC20Permit.bind(null, privy, walletId);\n}\n\nfunction signSwapTypedData(\n privy: PrivyClient,\n walletId: string,\n result: SwapByIntentTypedData | CancelSwapTypedData,\n): ReturnType<SwapSignatureHandler> {\n const message = JSON.parse(result.message);\n return ResultAsync.fromPromise(\n privy.walletApi.ethereum.signTypedData({\n walletId,\n typedData: {\n domain: result.domain,\n types: result.types,\n message,\n primaryType: result.primaryType,\n },\n }),\n (err) => SigningError.from(err),\n ).map((response) => ({\n deadline: message.deadline,\n value: signatureFrom(response.signature),\n }));\n}\n\n/**\n * @internal\n * Creates a swap signature handler that signs swap typed data using the specified Privy wallet.\n */\nexport function signSwapTypedDataWith(\n privy: PrivyClient,\n walletId: string,\n): SwapSignatureHandler;\n/**\n * @internal\n * Signs swap typed data using the specified Privy wallet.\n */\nexport function signSwapTypedDataWith(\n privy: PrivyClient,\n walletId: string,\n result: SwapByIntentTypedData | CancelSwapTypedData,\n): ReturnType<SwapSignatureHandler>;\nexport function signSwapTypedDataWith(\n privy: PrivyClient,\n walletId: string,\n result?: SwapByIntentTypedData | CancelSwapTypedData,\n): SwapSignatureHandler | ReturnType<SwapSignatureHandler> {\n return result\n ? signSwapTypedData(privy, walletId, result)\n : signSwapTypedData.bind(null, privy, walletId);\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/privy.ts"],"names":["allChains","viemChains","sendTransaction","privy","request","walletId","hash","txHash","sendTransactionAndWait","chain","extractChain","publicClient","createPublicClient","http","ResultAsync","err","SigningError","waitForTransactionReceipt","UnexpectedError","receipt","errAsync","transactionError","okAsync","executePlan","result","approval","ValidationError","sendWith","permitWith","action","supportsPermit","permitTypedData","signTypedDataWith","signature","permitSig","signTypedData","data","response","typedData","signatureFrom"],"mappings":"iYAiCA,IAAMA,CAAAA,CAAY,MAAA,CAAO,OAAOC,CAAU,CAAA,CAE1C,eAAeC,CAAAA,CACbC,CAAAA,CACAC,EACAC,CAAAA,CACiB,CACjB,GAAM,CAAE,IAAA,CAAAC,CAAK,EAAI,MAAMH,CAAAA,CAAM,UAAU,QAAA,CAAS,eAAA,CAAgB,CAC9D,QAAA,CAAAE,CAAAA,CACA,KAAA,CAAO,CAAA,OAAA,EAAUD,CAAAA,C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,CAAAA,CAAO,SAAA,CAAU,CAAC,CAAA,CAAE,WAAA,CAC5C,OAAOQ,CAAAA,CAAkB7B,CAAAA,CAAOE,EAAU0B,CAAe,CAAA,CACtD,GAAA,CAAKE,CAAAA,GAAe,CACnB,QAAA,CAAUF,EAAgB,OAAA,CAAQ,QAAA,CAClC,MAAOE,CACT,CAAA,CAAE,EACD,OAAA,CAASC,CAAAA,EAAcL,CAAAA,CAAOK,CAAS,CAAC,CAC7C,CACA,OAAOZ,OAAAA,CAAQE,CAAM,CACvB,CAAC,CACH,CAEA,SAASW,CAAAA,CACPhC,CAAAA,CACAE,CAAAA,CACA+B,CAAAA,CACmC,CACnC,OAAOtB,WAAAA,CAAY,WAAA,CACjBX,CAAAA,CAAM,SAAA,CAAU,QAAA,CAAS,cAAc,CACrC,QAAA,CAAAE,CAAAA,CACA,SAAA,CAAW,CACT,MAAA,CAAQ+B,EAAK,MAAA,CACb,KAAA,CAAOA,EAAK,KAAA,CACZ,OAAA,CAASA,EAAK,OAAA,CACd,WAAA,CAAaA,CAAAA,CAAK,WACpB,CACF,CAAC,EACArB,CAAAA,EAAQC,YAAAA,CAAa,KAAKD,CAAG,CAChC,EAAE,GAAA,CAAKsB,CAAAA,EAAaA,CAAAA,CAAS,SAAS,CACxC,CAqCO,SAASL,CAAAA,CACd7B,CAAAA,CACAE,EACA+B,CAAAA,CACiD,CACjD,OAAIA,CAAAA,GAAS,MAAA,CACHE,CAAAA,EACNH,CAAAA,CAAchC,CAAAA,CAAOE,CAAAA,CAAUiC,CAAS,CAAA,CAAE,GAAA,CAAIC,aAAa,CAAA,CAExDJ,CAAAA,CAAchC,CAAAA,CAAOE,EAAU+B,CAAI,CAAA,CAAE,GAAA,CAAIG,aAAa,CAC/D","file":"privy.js","sourcesContent":["import {\n SigningError,\n type TransactionError,\n UnexpectedError,\n ValidationError,\n} from '@aave/core';\nimport type {\n ERC20PermitSignature,\n ExecutionPlan,\n TransactionRequest,\n} from '@aave/graphql';\nimport {\n errAsync,\n okAsync,\n ResultAsync,\n signatureFrom,\n type TxHash,\n txHash,\n} from '@aave/types';\nimport type { PrivyClient } from '@privy-io/server-auth';\nimport { createPublicClient, extractChain, http } from 'viem';\nimport { waitForTransactionReceipt } from 'viem/actions';\nimport * as viemChains from 'viem/chains';\nimport { supportsPermit } from './adapters';\nimport type {\n ExecutionPlanHandler,\n SignTypedDataError,\n TransactionResult,\n TypedData,\n TypedDataHandler,\n} from './types';\nimport { transactionError } from './viem';\n\nconst allChains = Object.values(viemChains);\n\nasync function sendTransaction(\n privy: PrivyClient,\n request: TransactionRequest,\n walletId: string,\n): Promise<TxHash> {\n const { hash } = await privy.walletApi.ethereum.sendTransaction({\n walletId,\n caip2: `eip155:${request.chainId}`,\n transaction: {\n from: request.from,\n to: request.to,\n value: `0x${BigInt(request.value).toString(16)}`,\n chainId: request.chainId,\n data: request.data,\n },\n });\n return txHash(hash);\n}\n\nfunction sendTransactionAndWait(\n privy: PrivyClient,\n request: TransactionRequest,\n walletId: string,\n): ResultAsync<\n TransactionResult,\n SigningError | TransactionError | UnexpectedError\n> {\n const chain = extractChain({\n chains: allChains,\n id: request.chainId as (typeof allChains)[number]['id'],\n });\n\n const publicClient = createPublicClient({\n chain,\n transport: http(),\n });\n\n return ResultAsync.fromPromise(\n sendTransaction(privy, request, walletId),\n (err) => SigningError.from(err),\n )\n .andThen((hash) =>\n ResultAsync.fromPromise(\n waitForTransactionReceipt(publicClient, {\n hash,\n pollingInterval: 100,\n retryCount: 20,\n retryDelay: 50,\n }),\n (err) => UnexpectedError.from(err),\n ),\n )\n .andThen((receipt) => {\n const hash = txHash(receipt.transactionHash);\n\n if (receipt.status === 'reverted') {\n return errAsync(transactionError(chain, hash, request));\n }\n return okAsync({\n txHash: hash,\n operations: request.operations,\n });\n });\n}\n\nfunction executePlan(\n privy: PrivyClient,\n walletId: string,\n result: ExecutionPlan,\n): ReturnType<ExecutionPlanHandler> {\n switch (result.__typename) {\n case 'TransactionRequest':\n return sendTransactionAndWait(privy, result, walletId);\n\n case 'Erc20ApprovalRequired':\n return result.approvals\n .reduce<ReturnType<typeof sendTransactionAndWait>>(\n (chain, approval) =>\n chain.andThen(() =>\n sendTransactionAndWait(privy, approval.byTransaction, walletId),\n ),\n okAsync(undefined as never),\n )\n .andThen(() =>\n sendTransactionAndWait(privy, result.originalTransaction, walletId),\n );\n\n case 'PreContractActionRequired':\n return sendTransactionAndWait(\n privy,\n result.transaction,\n walletId,\n ).andThen(() =>\n sendTransactionAndWait(privy, result.originalTransaction, walletId),\n );\n\n case 'InsufficientBalanceError':\n return errAsync(ValidationError.fromGqlNode(result));\n }\n}\n\n/**\n * Creates an execution plan handler that sends transactions using the specified Privy wallet.\n */\nexport function sendWith<T extends ExecutionPlan = ExecutionPlan>(\n privy: PrivyClient,\n walletId: string,\n): ExecutionPlanHandler<T>;\n/**\n * Sends execution plan transactions using the specified Privy wallet.\n */\nexport function sendWith<T extends ExecutionPlan = ExecutionPlan>(\n privy: PrivyClient,\n walletId: string,\n result: T,\n): ReturnType<ExecutionPlanHandler<T>>;\nexport function sendWith<T extends ExecutionPlan = ExecutionPlan>(\n privy: PrivyClient,\n walletId: string,\n result?: T,\n): ExecutionPlanHandler<T> | ReturnType<ExecutionPlanHandler<T>> {\n return result\n ? executePlan(privy, walletId, result)\n : executePlan.bind(null, privy, walletId);\n}\n\n/**\n * Handles ERC20 permit signing for actions that require token approval.\n *\n * Calls the action to get an initial execution plan. If the plan requires ERC20 approval\n * and the token supports permit signatures, signs the permit and re-calls the action\n * with the signature to get a new plan that can be sent directly.\n *\n * ```ts\n * const result = await permitWith(privy, walletId, (permitSig) =>\n * supply(client, {\n * reserve: reserve.id,\n * amount: { erc20: { value: amount, permitSig } },\n * sender: evmAddress(walletAddress),\n * })\n * )\n * .andThen(sendWith(privy, walletId))\n * .andThen(client.waitForTransaction);\n * ```\n *\n * @param privy - The Privy client for signing permits.\n * @param walletId - The ID of the Privy wallet to use.\n * @param action - A function that returns an execution plan, accepting an optional permit signature.\n * @returns A ResultAsync containing the resolved ExecutionPlan ready to be sent with `sendWith`.\n */\nexport function permitWith<E>(\n privy: PrivyClient,\n walletId: string,\n action: (permitSig?: ERC20PermitSignature) => ResultAsync<ExecutionPlan, E>,\n): ResultAsync<ExecutionPlan, E | SignTypedDataError> {\n return action().andThen((result) => {\n if (supportsPermit(result)) {\n const permitTypedData = result.approvals[0].bySignature;\n return signTypedDataWith(privy, walletId, permitTypedData)\n .map((signature) => ({\n deadline: permitTypedData.message.deadline as number,\n value: signature,\n }))\n .andThen((permitSig) => action(permitSig));\n }\n return okAsync(result);\n });\n}\n\nfunction signTypedData(\n privy: PrivyClient,\n walletId: string,\n data: TypedData,\n): ResultAsync<string, SigningError> {\n return ResultAsync.fromPromise(\n privy.walletApi.ethereum.signTypedData({\n walletId,\n typedData: {\n domain: data.domain,\n types: data.types,\n message: data.message,\n primaryType: data.primaryType,\n },\n }),\n (err) => SigningError.from(err),\n ).map((response) => response.signature);\n}\n\n/**\n * Creates a function that signs EIP-712 typed data (ERC-20 permits, swap intents, etc.) using the specified Privy wallet.\n *\n * @param privy - The Privy client instance.\n * @param walletId - The wallet ID to use for signing.\n * @returns A function that takes typed data and returns a ResultAsync containing the raw signature.\n *\n * ```ts\n * const result = await prepareSwapCancel(client, request)\n * .andThen(signTypedDataWith(privy, walletId));\n * ```\n */\nexport function signTypedDataWith(\n privy: PrivyClient,\n walletId: string,\n): TypedDataHandler;\n\n/**\n * Signs EIP-712 typed data (ERC-20 permits, swap intents, etc.) using the specified Privy wallet.\n *\n * @param privy - The Privy client instance.\n * @param walletId - The wallet ID to use for signing.\n * @param data - The typed data to sign.\n * @returns A ResultAsync containing the raw signature.\n *\n * ```ts\n * const result = await signTypedDataWith(privy, walletId, typedData);\n * ```\n */\nexport function signTypedDataWith(\n privy: PrivyClient,\n walletId: string,\n data: TypedData,\n): ReturnType<TypedDataHandler>;\n\nexport function signTypedDataWith(\n privy: PrivyClient,\n walletId: string,\n data?: TypedData,\n): TypedDataHandler | ReturnType<TypedDataHandler> {\n if (data === undefined) {\n return (typedData: TypedData) =>\n signTypedData(privy, walletId, typedData).map(signatureFrom);\n }\n return signTypedData(privy, walletId, data).map(signatureFrom);\n}\n"]}
|