viem 2.57.13 → 2.57.15
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/CHANGELOG.md +60 -0
- package/_cjs/account-abstraction/utils/formatters/userOperationReceipt.js +2 -0
- package/_cjs/account-abstraction/utils/formatters/userOperationReceipt.js.map +1 -1
- package/_cjs/actions/public/estimateGas.js +5 -2
- package/_cjs/actions/public/estimateGas.js.map +1 -1
- package/_cjs/actions/public/fillTransaction.js +2 -0
- package/_cjs/actions/public/fillTransaction.js.map +1 -1
- package/_cjs/actions/public/getFilterChanges.js +1 -0
- package/_cjs/actions/public/getFilterChanges.js.map +1 -1
- package/_cjs/actions/public/getFilterLogs.js +1 -0
- package/_cjs/actions/public/getFilterLogs.js.map +1 -1
- package/_cjs/actions/public/watchBlockNumber.js +3 -1
- package/_cjs/actions/public/watchBlockNumber.js.map +1 -1
- package/_cjs/actions/public/watchBlocks.js +20 -8
- package/_cjs/actions/public/watchBlocks.js.map +1 -1
- package/_cjs/actions/public/watchContractEvent.js +10 -3
- package/_cjs/actions/public/watchContractEvent.js.map +1 -1
- package/_cjs/actions/public/watchEvent.js +5 -0
- package/_cjs/actions/public/watchEvent.js.map +1 -1
- package/_cjs/actions/wallet/prepareTransactionRequest.js +3 -2
- package/_cjs/actions/wallet/prepareTransactionRequest.js.map +1 -1
- package/_cjs/actions/wallet/sendTransaction.js +4 -2
- package/_cjs/actions/wallet/sendTransaction.js.map +1 -1
- package/_cjs/actions/wallet/sendTransactionSync.js +48 -7
- package/_cjs/actions/wallet/sendTransactionSync.js.map +1 -1
- package/_cjs/chains/definitions/hashKeyChain.js +4 -4
- package/_cjs/chains/definitions/hashKeyChain.js.map +1 -1
- package/_cjs/chains/definitions/hashkeyChainTestnet.js +4 -4
- package/_cjs/chains/definitions/hashkeyChainTestnet.js.map +1 -1
- package/_cjs/chains/definitions/turkchain.js +26 -0
- package/_cjs/chains/definitions/turkchain.js.map +1 -0
- package/_cjs/chains/definitions/zksync.js +1 -1
- package/_cjs/chains/definitions/zksync.js.map +1 -1
- package/_cjs/chains/index.js +4 -2
- package/_cjs/chains/index.js.map +1 -1
- package/_cjs/clients/createClient.js.map +1 -1
- package/_cjs/clients/transports/fallback.js +5 -0
- package/_cjs/clients/transports/fallback.js.map +1 -1
- package/_cjs/errors/node.js +10 -4
- package/_cjs/errors/node.js.map +1 -1
- package/_cjs/errors/typedData.js +4 -2
- package/_cjs/errors/typedData.js.map +1 -1
- package/_cjs/errors/version.js +1 -1
- package/_cjs/index.js +5 -4
- package/_cjs/index.js.map +1 -1
- package/_cjs/tempo/Account.js +85 -12
- package/_cjs/tempo/Account.js.map +1 -1
- package/_cjs/tempo/Formatters.js +4 -1
- package/_cjs/tempo/Formatters.js.map +1 -1
- package/_cjs/tempo/Relay.js +5 -0
- package/_cjs/tempo/Relay.js.map +1 -1
- package/_cjs/tempo/Transaction.js +2 -1
- package/_cjs/tempo/Transaction.js.map +1 -1
- package/_cjs/tempo/chainConfig.js +10 -13
- package/_cjs/tempo/chainConfig.js.map +1 -1
- package/_cjs/tempo/internal/relay/autoSwap.js +200 -0
- package/_cjs/tempo/internal/relay/autoSwap.js.map +1 -0
- package/_cjs/tempo/internal/relay/error.js +5 -1
- package/_cjs/tempo/internal/relay/error.js.map +1 -1
- package/_cjs/tempo/internal/relay/feePayer.js +18 -5
- package/_cjs/tempo/internal/relay/feePayer.js.map +1 -1
- package/_cjs/tempo/internal/relay/feeToken.js +14 -1
- package/_cjs/tempo/internal/relay/feeToken.js.map +1 -1
- package/_cjs/tempo/internal/relay/simulate.js +57 -15
- package/_cjs/tempo/internal/relay/simulate.js.map +1 -1
- package/_cjs/utils/abi/decodeEventLog.js +57 -7
- package/_cjs/utils/abi/decodeEventLog.js.map +1 -1
- package/_cjs/utils/abi/getAbiItem.js +27 -6
- package/_cjs/utils/abi/getAbiItem.js.map +1 -1
- package/_cjs/utils/abi/parseEventLogs.js +27 -4
- package/_cjs/utils/abi/parseEventLogs.js.map +1 -1
- package/_cjs/utils/authorization/recoverAuthorizationAddress.js +9 -2
- package/_cjs/utils/authorization/recoverAuthorizationAddress.js.map +1 -1
- package/_cjs/utils/authorization/verifyAuthorization.js +14 -4
- package/_cjs/utils/authorization/verifyAuthorization.js.map +1 -1
- package/_cjs/utils/ccip.js +134 -28
- package/_cjs/utils/ccip.js.map +1 -1
- package/_cjs/utils/ccipTunnel.js +5 -1
- package/_cjs/utils/ccipTunnel.js.map +1 -1
- package/_cjs/utils/ens/localBatchGatewayRequest.js +55 -5
- package/_cjs/utils/ens/localBatchGatewayRequest.js.map +1 -1
- package/_cjs/utils/internal/http.js +79 -0
- package/_cjs/utils/internal/http.js.map +1 -0
- package/_cjs/utils/nonceManager.js.map +1 -1
- package/_cjs/utils/rpc/http.js +3 -73
- package/_cjs/utils/rpc/http.js.map +1 -1
- package/_cjs/utils/transaction/assertRequest.js +2 -2
- package/_cjs/utils/transaction/assertRequest.js.map +1 -1
- package/_cjs/utils/transaction/assertTransaction.js +2 -2
- package/_cjs/utils/transaction/assertTransaction.js.map +1 -1
- package/_cjs/utils/transaction/parseTransaction.js +21 -7
- package/_cjs/utils/transaction/parseTransaction.js.map +1 -1
- package/_cjs/utils/typedData.js +19 -6
- package/_cjs/utils/typedData.js.map +1 -1
- package/_esm/account-abstraction/utils/formatters/userOperationReceipt.js +2 -0
- package/_esm/account-abstraction/utils/formatters/userOperationReceipt.js.map +1 -1
- package/_esm/actions/public/estimateGas.js +10 -5
- package/_esm/actions/public/estimateGas.js.map +1 -1
- package/_esm/actions/public/fillTransaction.js +2 -0
- package/_esm/actions/public/fillTransaction.js.map +1 -1
- package/_esm/actions/public/getFilterChanges.js +1 -0
- package/_esm/actions/public/getFilterChanges.js.map +1 -1
- package/_esm/actions/public/getFilterLogs.js +1 -0
- package/_esm/actions/public/getFilterLogs.js.map +1 -1
- package/_esm/actions/public/watchBlockNumber.js +5 -1
- package/_esm/actions/public/watchBlockNumber.js.map +1 -1
- package/_esm/actions/public/watchBlocks.js +28 -8
- package/_esm/actions/public/watchBlocks.js.map +1 -1
- package/_esm/actions/public/watchContractEvent.js +15 -5
- package/_esm/actions/public/watchContractEvent.js.map +1 -1
- package/_esm/actions/public/watchEvent.js +11 -2
- package/_esm/actions/public/watchEvent.js.map +1 -1
- package/_esm/actions/wallet/prepareTransactionRequest.js +3 -2
- package/_esm/actions/wallet/prepareTransactionRequest.js.map +1 -1
- package/_esm/actions/wallet/sendTransaction.js +6 -2
- package/_esm/actions/wallet/sendTransaction.js.map +1 -1
- package/_esm/actions/wallet/sendTransactionSync.js +59 -8
- package/_esm/actions/wallet/sendTransactionSync.js.map +1 -1
- package/_esm/chains/definitions/hashKeyChain.js +4 -4
- package/_esm/chains/definitions/hashKeyChain.js.map +1 -1
- package/_esm/chains/definitions/hashkeyChainTestnet.js +4 -4
- package/_esm/chains/definitions/hashkeyChainTestnet.js.map +1 -1
- package/_esm/chains/definitions/turkchain.js +23 -0
- package/_esm/chains/definitions/turkchain.js.map +1 -0
- package/_esm/chains/definitions/zksync.js +1 -1
- package/_esm/chains/definitions/zksync.js.map +1 -1
- package/_esm/chains/index.js +1 -0
- package/_esm/chains/index.js.map +1 -1
- package/_esm/clients/createClient.js.map +1 -1
- package/_esm/clients/transports/fallback.js +8 -0
- package/_esm/clients/transports/fallback.js.map +1 -1
- package/_esm/errors/node.js +10 -4
- package/_esm/errors/node.js.map +1 -1
- package/_esm/errors/typedData.js +5 -2
- package/_esm/errors/typedData.js.map +1 -1
- package/_esm/errors/version.js +1 -1
- package/_esm/index.js +1 -1
- package/_esm/index.js.map +1 -1
- package/_esm/tempo/Account.js +122 -11
- package/_esm/tempo/Account.js.map +1 -1
- package/_esm/tempo/Formatters.js +5 -2
- package/_esm/tempo/Formatters.js.map +1 -1
- package/_esm/tempo/Relay.js +20 -0
- package/_esm/tempo/Relay.js.map +1 -1
- package/_esm/tempo/Transaction.js +2 -0
- package/_esm/tempo/Transaction.js.map +1 -1
- package/_esm/tempo/chainConfig.js +20 -14
- package/_esm/tempo/chainConfig.js.map +1 -1
- package/_esm/tempo/internal/relay/autoSwap.js +218 -0
- package/_esm/tempo/internal/relay/autoSwap.js.map +1 -0
- package/_esm/tempo/internal/relay/error.js +6 -2
- package/_esm/tempo/internal/relay/error.js.map +1 -1
- package/_esm/tempo/internal/relay/feePayer.js +24 -7
- package/_esm/tempo/internal/relay/feePayer.js.map +1 -1
- package/_esm/tempo/internal/relay/feeToken.js +17 -3
- package/_esm/tempo/internal/relay/feeToken.js.map +1 -1
- package/_esm/tempo/internal/relay/simulate.js +68 -17
- package/_esm/tempo/internal/relay/simulate.js.map +1 -1
- package/_esm/utils/abi/decodeEventLog.js +69 -7
- package/_esm/utils/abi/decodeEventLog.js.map +1 -1
- package/_esm/utils/abi/getAbiItem.js +34 -6
- package/_esm/utils/abi/getAbiItem.js.map +1 -1
- package/_esm/utils/abi/parseEventLogs.js +43 -10
- package/_esm/utils/abi/parseEventLogs.js.map +1 -1
- package/_esm/utils/authorization/recoverAuthorizationAddress.js +11 -2
- package/_esm/utils/authorization/recoverAuthorizationAddress.js.map +1 -1
- package/_esm/utils/authorization/verifyAuthorization.js +15 -4
- package/_esm/utils/authorization/verifyAuthorization.js.map +1 -1
- package/_esm/utils/ccip.js +163 -31
- package/_esm/utils/ccip.js.map +1 -1
- package/_esm/utils/ccipTunnel.js +5 -1
- package/_esm/utils/ccipTunnel.js.map +1 -1
- package/_esm/utils/ens/localBatchGatewayRequest.js +69 -4
- package/_esm/utils/ens/localBatchGatewayRequest.js.map +1 -1
- package/_esm/utils/internal/http.js +83 -0
- package/_esm/utils/internal/http.js.map +1 -0
- package/_esm/utils/nonceManager.js.map +1 -1
- package/_esm/utils/rpc/http.js +1 -75
- package/_esm/utils/rpc/http.js.map +1 -1
- package/_esm/utils/transaction/assertRequest.js +2 -2
- package/_esm/utils/transaction/assertRequest.js.map +1 -1
- package/_esm/utils/transaction/assertTransaction.js +2 -2
- package/_esm/utils/transaction/assertTransaction.js.map +1 -1
- package/_esm/utils/transaction/parseTransaction.js +24 -7
- package/_esm/utils/transaction/parseTransaction.js.map +1 -1
- package/_esm/utils/typedData.js +25 -8
- package/_esm/utils/typedData.js.map +1 -1
- package/_types/account-abstraction/utils/formatters/userOperationReceipt.d.ts.map +1 -1
- package/_types/actions/public/estimateGas.d.ts.map +1 -1
- package/_types/actions/public/fillTransaction.d.ts.map +1 -1
- package/_types/actions/public/getFilterChanges.d.ts.map +1 -1
- package/_types/actions/public/getFilterLogs.d.ts.map +1 -1
- package/_types/actions/public/watchBlockNumber.d.ts +6 -2
- package/_types/actions/public/watchBlockNumber.d.ts.map +1 -1
- package/_types/actions/public/watchBlocks.d.ts +7 -2
- package/_types/actions/public/watchBlocks.d.ts.map +1 -1
- package/_types/actions/public/watchContractEvent.d.ts.map +1 -1
- package/_types/actions/public/watchEvent.d.ts.map +1 -1
- package/_types/actions/wallet/prepareTransactionRequest.d.ts.map +1 -1
- package/_types/actions/wallet/sendTransaction.d.ts.map +1 -1
- package/_types/actions/wallet/sendTransactionSync.d.ts.map +1 -1
- package/_types/chains/definitions/hashKeyChain.d.ts +4 -4
- package/_types/chains/definitions/hashkeyChainTestnet.d.ts +4 -4
- package/_types/chains/definitions/turkchain.d.ts +53 -0
- package/_types/chains/definitions/turkchain.d.ts.map +1 -0
- package/_types/chains/definitions/zksync.d.ts +1 -1
- package/_types/chains/index.d.ts +1 -0
- package/_types/chains/index.d.ts.map +1 -1
- package/_types/clients/createClient.d.ts +6 -0
- package/_types/clients/createClient.d.ts.map +1 -1
- package/_types/clients/transports/fallback.d.ts.map +1 -1
- package/_types/errors/node.d.ts.map +1 -1
- package/_types/errors/typedData.d.ts.map +1 -1
- package/_types/errors/version.d.ts +1 -1
- package/_types/index.d.ts +1 -1
- package/_types/index.d.ts.map +1 -1
- package/_types/tempo/Account.d.ts +78 -5
- package/_types/tempo/Account.d.ts.map +1 -1
- package/_types/tempo/Capabilities.d.ts +32 -2
- package/_types/tempo/Capabilities.d.ts.map +1 -1
- package/_types/tempo/Relay.d.ts +27 -1
- package/_types/tempo/Relay.d.ts.map +1 -1
- package/_types/tempo/Transaction.d.ts +2 -0
- package/_types/tempo/Transaction.d.ts.map +1 -1
- package/_types/tempo/actions/accessKey.d.ts +2 -2
- package/_types/tempo/chainConfig.d.ts.map +1 -1
- package/_types/tempo/internal/relay/autoSwap.d.ts +3 -0
- package/_types/tempo/internal/relay/autoSwap.d.ts.map +1 -0
- package/_types/tempo/internal/relay/error.d.ts.map +1 -1
- package/_types/tempo/internal/relay/feePayer.d.ts.map +1 -1
- package/_types/tempo/internal/relay/feeToken.d.ts.map +1 -1
- package/_types/tempo/internal/relay/simulate.d.ts +4 -0
- package/_types/tempo/internal/relay/simulate.d.ts.map +1 -1
- package/_types/tempo/internal/relay/utils.d.ts +8 -8
- package/_types/utils/abi/decodeEventLog.d.ts +13 -1
- package/_types/utils/abi/decodeEventLog.d.ts.map +1 -1
- package/_types/utils/abi/getAbiItem.d.ts.map +1 -1
- package/_types/utils/abi/parseEventLogs.d.ts.map +1 -1
- package/_types/utils/authorization/recoverAuthorizationAddress.d.ts +2 -1
- package/_types/utils/authorization/recoverAuthorizationAddress.d.ts.map +1 -1
- package/_types/utils/authorization/verifyAuthorization.d.ts.map +1 -1
- package/_types/utils/ccip.d.ts +24 -4
- package/_types/utils/ccip.d.ts.map +1 -1
- package/_types/utils/ccipTunnel.d.ts.map +1 -1
- package/_types/utils/ens/localBatchGatewayRequest.d.ts +26 -0
- package/_types/utils/ens/localBatchGatewayRequest.d.ts.map +1 -1
- package/_types/utils/internal/http.d.ts +16 -0
- package/_types/utils/internal/http.d.ts.map +1 -0
- package/_types/utils/nonceManager.d.ts +15 -1
- package/_types/utils/nonceManager.d.ts.map +1 -1
- package/_types/utils/rpc/http.d.ts.map +1 -1
- package/_types/utils/transaction/parseTransaction.d.ts.map +1 -1
- package/_types/utils/typedData.d.ts.map +1 -1
- package/account-abstraction/utils/formatters/userOperationReceipt.ts +1 -0
- package/actions/public/estimateGas.ts +12 -5
- package/actions/public/fillTransaction.ts +2 -0
- package/actions/public/getFilterChanges.ts +1 -0
- package/actions/public/getFilterLogs.ts +1 -0
- package/actions/public/watchBlockNumber.ts +11 -2
- package/actions/public/watchBlocks.ts +46 -14
- package/actions/public/watchContractEvent.ts +22 -4
- package/actions/public/watchEvent.ts +17 -1
- package/actions/wallet/prepareTransactionRequest.ts +6 -2
- package/actions/wallet/sendTransaction.ts +9 -3
- package/actions/wallet/sendTransactionSync.ts +74 -12
- package/chains/definitions/hashKeyChain.ts +4 -4
- package/chains/definitions/hashkeyChainTestnet.ts +4 -4
- package/chains/definitions/turkchain.ts +23 -0
- package/chains/definitions/zksync.ts +1 -1
- package/chains/index.ts +1 -0
- package/clients/createClient.ts +6 -0
- package/clients/transports/fallback.ts +11 -0
- package/errors/node.ts +11 -5
- package/errors/typedData.ts +5 -2
- package/errors/version.ts +1 -1
- package/index.ts +2 -0
- package/package.json +1 -1
- package/tempo/Account.ts +203 -17
- package/tempo/Capabilities.ts +34 -2
- package/tempo/Formatters.ts +5 -5
- package/tempo/Relay.ts +32 -1
- package/tempo/Transaction.ts +3 -0
- package/tempo/actions/accessKey.ts +2 -2
- package/tempo/chainConfig.ts +22 -14
- package/tempo/internal/relay/autoSwap.ts +263 -0
- package/tempo/internal/relay/error.ts +7 -2
- package/tempo/internal/relay/feePayer.ts +30 -7
- package/tempo/internal/relay/feeToken.ts +21 -3
- package/tempo/internal/relay/simulate.ts +106 -19
- package/utils/abi/decodeEventLog.ts +97 -10
- package/utils/abi/getAbiItem.ts +35 -5
- package/utils/abi/parseEventLogs.ts +48 -11
- package/utils/authorization/recoverAuthorizationAddress.ts +18 -2
- package/utils/authorization/verifyAuthorization.ts +12 -7
- package/utils/ccip.ts +199 -33
- package/utils/ccipTunnel.ts +5 -1
- package/utils/ens/localBatchGatewayRequest.ts +82 -4
- package/utils/internal/http.ts +92 -0
- package/utils/nonceManager.ts +16 -1
- package/utils/rpc/http.ts +1 -83
- package/utils/transaction/assertRequest.ts +2 -2
- package/utils/transaction/assertTransaction.ts +2 -2
- package/utils/transaction/parseTransaction.ts +32 -7
- package/utils/typedData.ts +31 -8
|
@@ -0,0 +1,263 @@
|
|
|
1
|
+
import type { Address } from 'abitype'
|
|
2
|
+
import { Hex, RpcResponse } from 'ox'
|
|
3
|
+
import { formatUnits } from '../../../utils/unit/formatUnits.js'
|
|
4
|
+
import * as Actions from '../../actions/index.js'
|
|
5
|
+
import type * as Capabilities from '../../Capabilities.js'
|
|
6
|
+
import * as ExecutionError from '../../ExecutionError.js'
|
|
7
|
+
import type * as Relay from '../../Relay.js'
|
|
8
|
+
import { isExecutionError } from './error.js'
|
|
9
|
+
import { resolveTokenMetadata } from './feeToken.js'
|
|
10
|
+
|
|
11
|
+
export function create(options: Relay.autoSwap.Options): Relay.Plugin {
|
|
12
|
+
const slippage = options.slippage ?? 0.05
|
|
13
|
+
if (!Number.isFinite(slippage) || slippage < 0 || slippage > 1)
|
|
14
|
+
throw new RangeError('Expected `slippage` between 0 and 1.')
|
|
15
|
+
return {
|
|
16
|
+
async handleRequest(context, next) {
|
|
17
|
+
if (context.request.method !== 'eth_fillTransaction') return next()
|
|
18
|
+
try {
|
|
19
|
+
await next()
|
|
20
|
+
} catch (error) {
|
|
21
|
+
const parameters = context.request.params![0] as Record<string, unknown>
|
|
22
|
+
// Swaps change what the sender signs, so callers opt in per request.
|
|
23
|
+
const requested = parseRequest(parameters.capabilities)
|
|
24
|
+
if (requested === undefined) throw error
|
|
25
|
+
const deficit = parseDeficit(error)
|
|
26
|
+
const from = parameters.from as Address | undefined
|
|
27
|
+
if (!deficit || !from) throw error
|
|
28
|
+
|
|
29
|
+
// A request may tighten, never loosen, the configured slippage bound.
|
|
30
|
+
const slippage_request = Math.min(
|
|
31
|
+
slippage,
|
|
32
|
+
requested.slippage ?? slippage,
|
|
33
|
+
)
|
|
34
|
+
// Rounded down to parts per million so the maximum input never exceeds the bound.
|
|
35
|
+
const ppm = BigInt(Math.floor(slippage_request * 1_000_000))
|
|
36
|
+
const maxAmountIn = deficit.amount + (deficit.amount * ppm) / 1_000_000n
|
|
37
|
+
const tokenIn = await selectTokenIn(context, {
|
|
38
|
+
account: from,
|
|
39
|
+
amountOut: deficit.amount,
|
|
40
|
+
exclude: deficit.token,
|
|
41
|
+
feeToken: parameters.feeToken as Address | undefined,
|
|
42
|
+
maxAmountIn,
|
|
43
|
+
})
|
|
44
|
+
if (!tokenIn) throw error
|
|
45
|
+
|
|
46
|
+
// The stablecoin DEX debits the sender directly, so the swap needs no allowance.
|
|
47
|
+
const buy = Actions.dex.buy.call({
|
|
48
|
+
amountOut: deficit.amount,
|
|
49
|
+
maxAmountIn,
|
|
50
|
+
tokenIn,
|
|
51
|
+
tokenOut: deficit.token,
|
|
52
|
+
})
|
|
53
|
+
const swap = [{ data: buy.data, to: buy.to, value: '0x0' }]
|
|
54
|
+
const { calls: _, data: __, to: ___, value: ____, ...rest } = parameters
|
|
55
|
+
const calls = [...swap, ...getCalls(parameters)]
|
|
56
|
+
// `next()` may run once, so the swap refills through the downstream client.
|
|
57
|
+
const result = (await context.client
|
|
58
|
+
.request({
|
|
59
|
+
method: 'eth_fillTransaction',
|
|
60
|
+
params: [{ ...rest, calls }],
|
|
61
|
+
} as never)
|
|
62
|
+
.catch(() => {
|
|
63
|
+
throw error
|
|
64
|
+
})) as Relay.Plugin.FillResult
|
|
65
|
+
const tx = result.tx as Record<string, unknown>
|
|
66
|
+
const capability: Capability = {
|
|
67
|
+
calls: swap.map(({ data, to }) => ({ data, to })),
|
|
68
|
+
maxIn: { token: tokenIn, value: Hex.fromNumber(maxAmountIn) },
|
|
69
|
+
minOut: {
|
|
70
|
+
token: deficit.token,
|
|
71
|
+
value: Hex.fromNumber(deficit.amount),
|
|
72
|
+
},
|
|
73
|
+
slippage: slippage_request,
|
|
74
|
+
}
|
|
75
|
+
return {
|
|
76
|
+
...result,
|
|
77
|
+
// Replaced by `afterFill` with token metadata.
|
|
78
|
+
capabilities: { ...result.capabilities, autoSwap: capability },
|
|
79
|
+
// Nodes may omit filled calls; outer plugins would otherwise restore the unswapped request.
|
|
80
|
+
tx:
|
|
81
|
+
Array.isArray(tx.calls) && tx.calls.length > 0
|
|
82
|
+
? tx
|
|
83
|
+
: { ...tx, calls },
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
},
|
|
87
|
+
async afterFill(filled, context) {
|
|
88
|
+
const capability = filled.capabilities?.autoSwap as Capability | undefined
|
|
89
|
+
if (!capability) return undefined
|
|
90
|
+
const store = context.getStore(options.store)
|
|
91
|
+
const [metadata_in, metadata_out] = await Promise.all(
|
|
92
|
+
[capability.maxIn.token, capability.minOut.token].map((token) =>
|
|
93
|
+
resolveTokenMetadata(context.client, { store, token }).catch(
|
|
94
|
+
() => undefined,
|
|
95
|
+
),
|
|
96
|
+
),
|
|
97
|
+
)
|
|
98
|
+
// Without both tokens' metadata the swap still executes, but cannot be described.
|
|
99
|
+
if (!metadata_in || !metadata_out)
|
|
100
|
+
return { capabilities: { autoSwap: undefined } }
|
|
101
|
+
return {
|
|
102
|
+
capabilities: {
|
|
103
|
+
autoSwap: {
|
|
104
|
+
calls: capability.calls,
|
|
105
|
+
maxIn: describe(capability.maxIn, metadata_in),
|
|
106
|
+
minOut: describe(capability.minOut, metadata_out),
|
|
107
|
+
slippage: capability.slippage,
|
|
108
|
+
},
|
|
109
|
+
},
|
|
110
|
+
}
|
|
111
|
+
},
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** Swap facts carried from the fill to `afterFill` in the response capability. */
|
|
116
|
+
type Capability = Omit<Capabilities.AutoSwap, 'maxIn' | 'minOut'> & {
|
|
117
|
+
maxIn: Pick<Capabilities.AutoSwapAmount, 'token' | 'value'>
|
|
118
|
+
minOut: Pick<Capabilities.AutoSwapAmount, 'token' | 'value'>
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** Returns the request's auto-swap opt-in, or `undefined` when the caller did not opt in. */
|
|
122
|
+
function parseRequest(
|
|
123
|
+
capabilities: unknown,
|
|
124
|
+
): { slippage?: number } | undefined {
|
|
125
|
+
const value = (capabilities as Record<string, unknown> | undefined)?.autoSwap
|
|
126
|
+
if (value === true) return {}
|
|
127
|
+
if (!value || typeof value !== 'object') return undefined
|
|
128
|
+
const { slippage } = value as { slippage?: unknown }
|
|
129
|
+
if (slippage === undefined) return {}
|
|
130
|
+
if (
|
|
131
|
+
typeof slippage !== 'number' ||
|
|
132
|
+
!Number.isFinite(slippage) ||
|
|
133
|
+
slippage < 0 ||
|
|
134
|
+
slippage > 1
|
|
135
|
+
)
|
|
136
|
+
throw new RpcResponse.InvalidParamsError({
|
|
137
|
+
message: 'Expected `capabilities.autoSwap.slippage` between 0 and 1.',
|
|
138
|
+
})
|
|
139
|
+
return { slippage }
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** Returns the missing token and amount of an `InsufficientBalance` revert. */
|
|
143
|
+
function parseDeficit(error: unknown) {
|
|
144
|
+
if (!isExecutionError(error)) return undefined
|
|
145
|
+
const revert = ExecutionError.from(error)
|
|
146
|
+
if (revert.errorName !== 'InsufficientBalance' || revert.args?.length !== 3)
|
|
147
|
+
return undefined
|
|
148
|
+
const [available, required, token] = revert.args
|
|
149
|
+
if (required <= available) return undefined
|
|
150
|
+
return { amount: required - available, token }
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* Returns the first token whose DEX quote for the missing amount is within `maxAmountIn` and the sender's balance,
|
|
155
|
+
* trying the named fee token and the sender's preferred token before the best-funded candidates.
|
|
156
|
+
*/
|
|
157
|
+
// biome-ignore lint/correctness/noUnusedVariables: declaration merge
|
|
158
|
+
async function selectTokenIn(
|
|
159
|
+
context: Relay.Plugin.Context,
|
|
160
|
+
options: selectTokenIn.Options,
|
|
161
|
+
) {
|
|
162
|
+
const { account, amountOut, exclude, feeToken, maxAmountIn } = options
|
|
163
|
+
// A speculative sponsored fill names the sponsor's token, so the sender's own preference also ranks first.
|
|
164
|
+
const [preference, tokens] = await Promise.all([
|
|
165
|
+
Actions.fee
|
|
166
|
+
.getUserToken(context.client, { account })
|
|
167
|
+
.then((token) => token?.address)
|
|
168
|
+
.catch(() => undefined),
|
|
169
|
+
context.resolveTokens(),
|
|
170
|
+
])
|
|
171
|
+
const preferred = [feeToken, preference].flatMap((token) =>
|
|
172
|
+
token ? [token.toLowerCase() as Address] : [],
|
|
173
|
+
)
|
|
174
|
+
const candidates = [
|
|
175
|
+
...new Set([
|
|
176
|
+
...preferred,
|
|
177
|
+
...tokens.map((token) => token.toLowerCase() as Address),
|
|
178
|
+
]),
|
|
179
|
+
]
|
|
180
|
+
.filter((token) => token !== exclude.toLowerCase())
|
|
181
|
+
// Bounds reads for one fill, matching the fee-token candidate limit.
|
|
182
|
+
.slice(0, 100)
|
|
183
|
+
const balances = await Promise.all(
|
|
184
|
+
candidates.map(async (token) => ({
|
|
185
|
+
balance: await Actions.token
|
|
186
|
+
.getBalance(context.client, { account, token })
|
|
187
|
+
.then(({ amount }) => amount)
|
|
188
|
+
.catch(() => 0n),
|
|
189
|
+
token,
|
|
190
|
+
})),
|
|
191
|
+
)
|
|
192
|
+
const rank = (token: Address) => {
|
|
193
|
+
const index = preferred.indexOf(token)
|
|
194
|
+
return index === -1 ? preferred.length : index
|
|
195
|
+
}
|
|
196
|
+
const funded = balances
|
|
197
|
+
.filter(({ balance }) => balance > 0n)
|
|
198
|
+
.sort((a, b) => {
|
|
199
|
+
if (rank(a.token) !== rank(b.token)) return rank(a.token) - rank(b.token)
|
|
200
|
+
return a.balance === b.balance ? 0 : a.balance > b.balance ? -1 : 1
|
|
201
|
+
})
|
|
202
|
+
// Quotes fail for tokens without a DEX route or enough liquidity. The DEX spends only the
|
|
203
|
+
// quoted input, so a balance covering the quote suffices even below `maxAmountIn`.
|
|
204
|
+
const quotes = await Promise.all(
|
|
205
|
+
funded.map(({ token }) =>
|
|
206
|
+
Actions.dex
|
|
207
|
+
.getBuyQuote(context.client, {
|
|
208
|
+
amountOut,
|
|
209
|
+
tokenIn: token,
|
|
210
|
+
tokenOut: exclude,
|
|
211
|
+
})
|
|
212
|
+
.catch(() => undefined),
|
|
213
|
+
),
|
|
214
|
+
)
|
|
215
|
+
return funded.find(({ balance }, index) => {
|
|
216
|
+
const quote = quotes[index]
|
|
217
|
+
return quote !== undefined && quote <= maxAmountIn && balance >= quote
|
|
218
|
+
})?.token
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
declare namespace selectTokenIn {
|
|
222
|
+
type Options = {
|
|
223
|
+
/** Sender whose balances fund the swap. */
|
|
224
|
+
account: Address
|
|
225
|
+
/** Missing amount of the token being bought. */
|
|
226
|
+
amountOut: bigint
|
|
227
|
+
/** Token being bought. */
|
|
228
|
+
exclude: Address
|
|
229
|
+
/** Fee token the fill names, preferred when funded. */
|
|
230
|
+
feeToken?: Address | undefined
|
|
231
|
+
/** Largest accepted input. */
|
|
232
|
+
maxAmountIn: bigint
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/** Returns the request's calls, including a legacy single call. */
|
|
237
|
+
function getCalls(parameters: Record<string, unknown>): readonly unknown[] {
|
|
238
|
+
if (Array.isArray(parameters.calls)) return parameters.calls
|
|
239
|
+
const { data, to, value } = parameters
|
|
240
|
+
if (to === undefined && data === undefined && value === undefined) return []
|
|
241
|
+
return [
|
|
242
|
+
{
|
|
243
|
+
...(to !== undefined ? { to } : {}),
|
|
244
|
+
...(data !== undefined ? { data } : {}),
|
|
245
|
+
...(value !== undefined ? { value } : {}),
|
|
246
|
+
},
|
|
247
|
+
]
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/** Formats one side of a swap with its token metadata. */
|
|
251
|
+
function describe(
|
|
252
|
+
amount: Capability['maxIn'],
|
|
253
|
+
metadata: { decimals: number; name: string; symbol: string },
|
|
254
|
+
): Capabilities.AutoSwapAmount {
|
|
255
|
+
return {
|
|
256
|
+
decimals: metadata.decimals,
|
|
257
|
+
formatted: formatUnits(Hex.toBigInt(amount.value), metadata.decimals),
|
|
258
|
+
name: metadata.name,
|
|
259
|
+
symbol: metadata.symbol,
|
|
260
|
+
token: amount.token,
|
|
261
|
+
value: amount.value,
|
|
262
|
+
}
|
|
263
|
+
}
|
|
@@ -62,8 +62,13 @@ export async function formatError(
|
|
|
62
62
|
|
|
63
63
|
const normalized = Utils.normalizeFillTransactionRequest(parameters)
|
|
64
64
|
|
|
65
|
-
// Simulate from zero address for optimistic balance diffs.
|
|
66
|
-
const optimisticCalls =
|
|
65
|
+
// Simulate from zero address for optimistic balance diffs, when the caller opted in.
|
|
66
|
+
const optimisticCalls =
|
|
67
|
+
normalized &&
|
|
68
|
+
(parameters.capabilities as Record<string, unknown> | undefined)
|
|
69
|
+
?.balanceDiffs === true
|
|
70
|
+
? extractCalls(normalized)
|
|
71
|
+
: undefined
|
|
67
72
|
const [{ balanceDiffs, tokenMetadata }, virtualAddresses] = optimisticCalls
|
|
68
73
|
? await Promise.all([
|
|
69
74
|
simulateAndParseDiffs(client, {
|
|
@@ -19,6 +19,7 @@ import { getBlockNumber } from '../../../actions/public/getBlockNumber.js'
|
|
|
19
19
|
import { readContract } from '../../../actions/public/readContract.js'
|
|
20
20
|
import { type Client, createClient } from '../../../clients/createClient.js'
|
|
21
21
|
import { http } from '../../../clients/transports/http.js'
|
|
22
|
+
import { maxUint256 } from '../../../constants/number.js'
|
|
22
23
|
import * as AccessKey from '../../actions/accessKey.js'
|
|
23
24
|
import type * as Relay from '../../Relay.js'
|
|
24
25
|
import * as Transaction from '../../Transaction.js'
|
|
@@ -180,7 +181,10 @@ export function create(options: Relay.feePayer.Options): Relay.Plugin {
|
|
|
180
181
|
// Bound before validation so the validated envelope is the one signed, and returned signatures expire.
|
|
181
182
|
const signs = !!options.account && !external && !defer
|
|
182
183
|
if (signs && filled.validBefore == null)
|
|
183
|
-
filled.validBefore = Validity.generate({
|
|
184
|
+
filled.validBefore = Validity.generate({
|
|
185
|
+
nonceKey: filled.nonceKey,
|
|
186
|
+
validity,
|
|
187
|
+
})
|
|
184
188
|
|
|
185
189
|
const sponsored =
|
|
186
190
|
external ||
|
|
@@ -835,27 +839,37 @@ const defaultValidity = 3_600
|
|
|
835
839
|
/** Granularity, in seconds, of a generated `validBefore`, so identical fill retries share one sign payload. */
|
|
836
840
|
const validityStep = 300
|
|
837
841
|
|
|
842
|
+
/** Headroom, in seconds, that generated expiring windows leave under the protocol limit. */
|
|
843
|
+
const skew = 30
|
|
844
|
+
|
|
838
845
|
/** Bounds on how long a returned fee-payer signature stays valid on chain. */
|
|
839
846
|
namespace Validity {
|
|
840
|
-
/** Returns a `validBefore` rounded down to the generation step, then extended by
|
|
847
|
+
/** Returns a `validBefore` rounded down to the generation step, then extended by the window's limit. */
|
|
841
848
|
export function generate(options: generate.Options) {
|
|
842
|
-
|
|
843
|
-
const
|
|
849
|
+
// Generated expiring windows stay under the protocol limit to allow for clock skew against the node.
|
|
850
|
+
const max =
|
|
851
|
+
options.nonceKey === maxUint256
|
|
852
|
+
? Math.min(limit(options), Transaction.expiringNonceMaxExpiry - skew)
|
|
853
|
+
: limit(options)
|
|
854
|
+
// A step of at most a tenth of the limit keeps every generated window at least 90% of it.
|
|
855
|
+
const step = Math.min(validityStep, Math.ceil(max / 10))
|
|
844
856
|
const time = Math.floor(Date.now() / 1_000)
|
|
845
|
-
return time - (time % step) +
|
|
857
|
+
return time - (time % step) + max
|
|
846
858
|
}
|
|
847
859
|
|
|
848
860
|
export declare namespace generate {
|
|
849
861
|
type Options = {
|
|
862
|
+
/** Nonce lane of the transaction. An expiring nonce lane caps the window at the protocol limit. */
|
|
863
|
+
nonceKey?: bigint | undefined
|
|
850
864
|
/** Longest validity window, in seconds. */
|
|
851
865
|
validity: number
|
|
852
866
|
}
|
|
853
867
|
}
|
|
854
868
|
|
|
855
|
-
/** Throws unless `validBefore` is a future time within
|
|
869
|
+
/** Throws unless `validBefore` is a future time within the window's limit that opens after `validAfter`. */
|
|
856
870
|
export function assert(window: assert.Window, options: assert.Options) {
|
|
857
871
|
const { validAfter, validBefore } = window
|
|
858
|
-
const {
|
|
872
|
+
const validity = limit({ nonceKey: window.nonceKey, ...options })
|
|
859
873
|
const time = Math.floor(Date.now() / 1_000)
|
|
860
874
|
if (
|
|
861
875
|
validBefore === undefined ||
|
|
@@ -875,6 +889,8 @@ namespace Validity {
|
|
|
875
889
|
export declare namespace assert {
|
|
876
890
|
/** Validity window of the transaction being co-signed, in unix seconds. */
|
|
877
891
|
type Window = {
|
|
892
|
+
/** Nonce lane. An expiring nonce lane caps the window at the protocol limit. */
|
|
893
|
+
nonceKey?: bigint | undefined
|
|
878
894
|
/** Earliest inclusion time. */
|
|
879
895
|
validAfter?: number | null | undefined
|
|
880
896
|
/** Latest inclusion time. */
|
|
@@ -886,6 +902,13 @@ namespace Validity {
|
|
|
886
902
|
validity: number
|
|
887
903
|
}
|
|
888
904
|
}
|
|
905
|
+
|
|
906
|
+
/** Returns `validity`, capped at the protocol limit for expiring nonce lanes. */
|
|
907
|
+
function limit(options: generate.Options) {
|
|
908
|
+
const { nonceKey, validity } = options
|
|
909
|
+
if (nonceKey !== maxUint256) return validity
|
|
910
|
+
return Math.min(validity, Transaction.expiringNonceMaxExpiry)
|
|
911
|
+
}
|
|
889
912
|
}
|
|
890
913
|
|
|
891
914
|
/** Facts of one sponsorship commitment, emitted at fee-payer signing time. */
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import type { Address } from 'abitype'
|
|
2
2
|
import { RpcResponse } from 'ox'
|
|
3
|
+
import { readContract } from '../../../actions/public/readContract.js'
|
|
3
4
|
import type { Client } from '../../../clients/createClient.js'
|
|
5
|
+
import { erc20Abi } from '../../../constants/abis.js'
|
|
4
6
|
import { tokens as tokenSets } from '../../../tokens/sets.js'
|
|
5
7
|
import * as Actions from '../../actions/index.js'
|
|
6
8
|
import type * as Relay from '../../Relay.js'
|
|
@@ -163,9 +165,12 @@ export async function resolveTokenMetadata(
|
|
|
163
165
|
// Tempo simulation metadata covers TIP-20 tokens, whose decimals are always six.
|
|
164
166
|
if (isTip20(token) && meta)
|
|
165
167
|
return { decimals: 6, symbol: meta.symbol, name: meta.name }
|
|
166
|
-
//
|
|
167
|
-
// long-term. Skips the
|
|
168
|
-
const fetcher = () =>
|
|
168
|
+
// Token metadata (decimals/symbol/name) is immutable per token, so cache
|
|
169
|
+
// long-term. Skips the RPC reads on cache hits.
|
|
170
|
+
const fetcher = () =>
|
|
171
|
+
isTip20(token)
|
|
172
|
+
? Actions.token.getMetadata(client, { token })
|
|
173
|
+
: readErc20Metadata(client, token)
|
|
169
174
|
const fallback = store
|
|
170
175
|
? await Store.memoize(fetcher, {
|
|
171
176
|
key: `tokenMetadata:${client.chain?.id ?? 0}:${token.toLowerCase()}`,
|
|
@@ -180,6 +185,19 @@ export async function resolveTokenMetadata(
|
|
|
180
185
|
}
|
|
181
186
|
}
|
|
182
187
|
|
|
188
|
+
/** Reads the standard metadata of a non-TIP-20 token, such as a vault share; `name` is optional in ERC-20. */
|
|
189
|
+
async function readErc20Metadata(client: Client, token: Address) {
|
|
190
|
+
const read = <const functionName extends 'decimals' | 'name' | 'symbol'>(
|
|
191
|
+
functionName: functionName,
|
|
192
|
+
) => readContract(client, { abi: erc20Abi, address: token, functionName })
|
|
193
|
+
const [decimals, symbol, name] = await Promise.all([
|
|
194
|
+
read('decimals'),
|
|
195
|
+
read('symbol'),
|
|
196
|
+
read('name').catch(() => undefined),
|
|
197
|
+
])
|
|
198
|
+
return { decimals, name: name ?? symbol, symbol }
|
|
199
|
+
}
|
|
200
|
+
|
|
183
201
|
export declare namespace resolveTokenMetadata {
|
|
184
202
|
type Options = {
|
|
185
203
|
token: Address
|
|
@@ -44,9 +44,10 @@ export function create(options: Relay.simulate.Options): Relay.Plugin {
|
|
|
44
44
|
const signal = context.options.signal
|
|
45
45
|
const transaction = Utils.normalizeTempoTransaction(result.tx)
|
|
46
46
|
const feeToken = transaction.feeToken as Address | undefined
|
|
47
|
+
// Balance diffs cost a simulation, so callers opt in; the fee is always estimated.
|
|
47
48
|
const simulation =
|
|
48
49
|
(parameters.capabilities as Record<string, unknown> | undefined)
|
|
49
|
-
?.balanceDiffs
|
|
50
|
+
?.balanceDiffs === true
|
|
50
51
|
? await simulateAndParseDiffs(context.client, {
|
|
51
52
|
account: parameters.from as Address | undefined,
|
|
52
53
|
calls: extractCalls(transaction),
|
|
@@ -77,7 +78,16 @@ export async function simulateAndParseDiffs(
|
|
|
77
78
|
client: Client,
|
|
78
79
|
options: simulateAndParseDiffs.Options,
|
|
79
80
|
) {
|
|
80
|
-
const {
|
|
81
|
+
const {
|
|
82
|
+
account,
|
|
83
|
+
blockNumber,
|
|
84
|
+
calls,
|
|
85
|
+
feeToken,
|
|
86
|
+
gas,
|
|
87
|
+
store,
|
|
88
|
+
maxFeePerGas,
|
|
89
|
+
signal,
|
|
90
|
+
} = options
|
|
81
91
|
signal?.throwIfAborted()
|
|
82
92
|
|
|
83
93
|
try {
|
|
@@ -94,6 +104,7 @@ export async function simulateAndParseDiffs(
|
|
|
94
104
|
: []
|
|
95
105
|
const simulation = await Actions.simulate.simulateCalls(client, {
|
|
96
106
|
account: account === zeroAddress ? undefined : account,
|
|
107
|
+
blockNumber,
|
|
97
108
|
calls: [...calls, ...probe] as Call[],
|
|
98
109
|
traceTransfers: true,
|
|
99
110
|
})
|
|
@@ -109,10 +120,18 @@ export async function simulateAndParseDiffs(
|
|
|
109
120
|
}[])
|
|
110
121
|
if (result.logs) logs.push(...result.logs)
|
|
111
122
|
|
|
123
|
+
const allowances =
|
|
124
|
+
account && account !== zeroAddress
|
|
125
|
+
? await readAllowances(client, { account, blockNumber, calls, logs })
|
|
126
|
+
: undefined
|
|
127
|
+
|
|
128
|
+
signal?.throwIfAborted()
|
|
129
|
+
|
|
112
130
|
// Build per-token balance diffs relative to the sender.
|
|
113
131
|
const balanceDiffs = account
|
|
114
132
|
? await buildBalanceDiffs(client, {
|
|
115
133
|
account,
|
|
134
|
+
allowances,
|
|
116
135
|
store,
|
|
117
136
|
signal,
|
|
118
137
|
logs,
|
|
@@ -149,6 +168,8 @@ export async function simulateAndParseDiffs(
|
|
|
149
168
|
export declare namespace simulateAndParseDiffs {
|
|
150
169
|
type Options = {
|
|
151
170
|
account?: Address | undefined
|
|
171
|
+
/** Block to simulate against. Defaults to the latest block. */
|
|
172
|
+
blockNumber?: bigint | undefined
|
|
152
173
|
calls: readonly Call[]
|
|
153
174
|
feeToken?: Address | undefined
|
|
154
175
|
gas?: bigint | undefined
|
|
@@ -163,7 +184,7 @@ export async function buildBalanceDiffs(
|
|
|
163
184
|
client: Client,
|
|
164
185
|
options: buildBalanceDiffs.Options,
|
|
165
186
|
) {
|
|
166
|
-
const { account, store, logs, tokenMetadata, signal } = options
|
|
187
|
+
const { account, allowances, store, logs, tokenMetadata, signal } = options
|
|
167
188
|
signal?.throwIfAborted()
|
|
168
189
|
const accountLower = account.toLowerCase()
|
|
169
190
|
|
|
@@ -178,7 +199,7 @@ export async function buildBalanceDiffs(
|
|
|
178
199
|
logs,
|
|
179
200
|
})
|
|
180
201
|
|
|
181
|
-
// Track
|
|
202
|
+
// Track gross movement per token, so a token received and passed on in one transaction stays visible.
|
|
182
203
|
const tokenMap = new Map<
|
|
183
204
|
string,
|
|
184
205
|
{
|
|
@@ -194,6 +215,8 @@ export async function buildBalanceDiffs(
|
|
|
194
215
|
const token = log.address.toLowerCase()
|
|
195
216
|
const fromLower = log.args.from.toLowerCase()
|
|
196
217
|
const toLower = log.args.to.toLowerCase()
|
|
218
|
+
// Transfers to oneself move nothing.
|
|
219
|
+
if (fromLower === accountLower && toLower === accountLower) continue
|
|
197
220
|
|
|
198
221
|
const entry = tokenMap.get(token) ?? {
|
|
199
222
|
incoming: 0n,
|
|
@@ -220,10 +243,13 @@ export async function buildBalanceDiffs(
|
|
|
220
243
|
)
|
|
221
244
|
}
|
|
222
245
|
|
|
223
|
-
// Transfers do not identify allowance consumption, so
|
|
246
|
+
// Transfers do not identify allowance consumption, so exposure is the allowance read after the calls, else the final approval.
|
|
224
247
|
for (const log of approvals.values()) {
|
|
225
|
-
if (log.args.amount === 0n) continue
|
|
226
248
|
const token = log.address.toLowerCase()
|
|
249
|
+
const amount =
|
|
250
|
+
allowances?.get(`${token}:${log.args.spender.toLowerCase()}`) ??
|
|
251
|
+
log.args.amount
|
|
252
|
+
if (amount === 0n) continue
|
|
227
253
|
|
|
228
254
|
const entry = tokenMap.get(token) ?? {
|
|
229
255
|
incoming: 0n,
|
|
@@ -232,19 +258,15 @@ export async function buildBalanceDiffs(
|
|
|
232
258
|
recipients: new Set<Address>(),
|
|
233
259
|
token: log.address,
|
|
234
260
|
}
|
|
235
|
-
entry.approved +=
|
|
261
|
+
entry.approved += amount
|
|
236
262
|
entry.recipients.add(log.args.spender)
|
|
237
263
|
tokenMap.set(token, entry)
|
|
238
264
|
}
|
|
239
265
|
|
|
240
266
|
// Collect unique tokens that need decimals.
|
|
241
|
-
const entries = [...tokenMap.values()].filter(
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
? e.outgoing - e.incoming
|
|
245
|
-
: e.incoming - e.outgoing
|
|
246
|
-
return net > 0n || e.approved > 0n
|
|
247
|
-
})
|
|
267
|
+
const entries = [...tokenMap.values()].filter(
|
|
268
|
+
(e) => e.incoming > 0n || e.outgoing > 0n || e.approved > 0n,
|
|
269
|
+
)
|
|
248
270
|
if (entries.length === 0) return {}
|
|
249
271
|
// Omit an unavailable preview rather than returning a partial set of movements.
|
|
250
272
|
if (entries.length > 100) return undefined
|
|
@@ -278,11 +300,8 @@ export async function buildBalanceDiffs(
|
|
|
278
300
|
// Build the diff array for this account.
|
|
279
301
|
const diffs: Capabilities.BalanceDiff[] = []
|
|
280
302
|
for (const entry of entries) {
|
|
281
|
-
const incoming =
|
|
282
|
-
|
|
283
|
-
const outgoing =
|
|
284
|
-
(entry.outgoing > entry.incoming ? entry.outgoing - entry.incoming : 0n) +
|
|
285
|
-
entry.approved
|
|
303
|
+
const { incoming } = entry
|
|
304
|
+
const outgoing = entry.outgoing + entry.approved
|
|
286
305
|
const meta = metadataMap.get(entry.token.toLowerCase())!
|
|
287
306
|
const decimals = meta.decimals
|
|
288
307
|
const metadata = {
|
|
@@ -315,6 +334,8 @@ export async function buildBalanceDiffs(
|
|
|
315
334
|
export declare namespace buildBalanceDiffs {
|
|
316
335
|
type Options = {
|
|
317
336
|
account: Address
|
|
337
|
+
/** Allowances read after the calls, keyed by lowercase `token:spender`. */
|
|
338
|
+
allowances?: ReadonlyMap<string, bigint> | undefined
|
|
318
339
|
store?: Store.Store | undefined
|
|
319
340
|
signal?: AbortSignal | undefined
|
|
320
341
|
logs: Log[]
|
|
@@ -365,3 +386,69 @@ declare namespace computeFee {
|
|
|
365
386
|
| undefined
|
|
366
387
|
}
|
|
367
388
|
}
|
|
389
|
+
|
|
390
|
+
/**
|
|
391
|
+
* Reads, after the calls, the allowance of every spender the account approved during them,
|
|
392
|
+
* so approval exposure is net of what spenders consumed however the approval was made.
|
|
393
|
+
*/
|
|
394
|
+
// biome-ignore lint/correctness/noUnusedVariables: declaration merge
|
|
395
|
+
async function readAllowances(
|
|
396
|
+
client: Client,
|
|
397
|
+
options: readAllowances.Options,
|
|
398
|
+
): Promise<ReadonlyMap<string, bigint> | undefined> {
|
|
399
|
+
const { account, blockNumber, calls, logs } = options
|
|
400
|
+
const accountLower = account.toLowerCase()
|
|
401
|
+
const pairs = new Map<string, { spender: Address; token: Address }>()
|
|
402
|
+
for (const log of parseEventLogs({
|
|
403
|
+
abi: [AbiEvent.fromAbi(Abis.tip20, 'Approval')],
|
|
404
|
+
eventName: 'Approval',
|
|
405
|
+
logs,
|
|
406
|
+
})) {
|
|
407
|
+
if (log.args.owner.toLowerCase() !== accountLower) continue
|
|
408
|
+
pairs.set(
|
|
409
|
+
`${log.address.toLowerCase()}:${log.args.spender.toLowerCase()}`,
|
|
410
|
+
{ spender: log.args.spender, token: log.address },
|
|
411
|
+
)
|
|
412
|
+
}
|
|
413
|
+
// Previews over the token budget are omitted, so their reads are skipped too.
|
|
414
|
+
if (pairs.size === 0 || pairs.size > 100) return undefined
|
|
415
|
+
try {
|
|
416
|
+
const entries = [...pairs.entries()]
|
|
417
|
+
const simulation = await Actions.simulate.simulateCalls(client, {
|
|
418
|
+
account,
|
|
419
|
+
blockNumber,
|
|
420
|
+
calls: [
|
|
421
|
+
...calls,
|
|
422
|
+
...entries.map(([, { spender, token }]) =>
|
|
423
|
+
Actions.token.getAllowance.call(client, { account, spender, token }),
|
|
424
|
+
),
|
|
425
|
+
] as Call[],
|
|
426
|
+
})
|
|
427
|
+
const allowances = new Map<string, bigint>()
|
|
428
|
+
for (const [index, [key]] of entries.entries()) {
|
|
429
|
+
const result = simulation.results[calls.length + index] as
|
|
430
|
+
| { data?: Hex.Hex | undefined; status?: string | undefined }
|
|
431
|
+
| undefined
|
|
432
|
+
if (result?.status !== 'success' || !result.data || result.data === '0x')
|
|
433
|
+
continue
|
|
434
|
+
allowances.set(key, Hex.toBigInt(result.data))
|
|
435
|
+
}
|
|
436
|
+
return allowances
|
|
437
|
+
} catch {
|
|
438
|
+
// Without the reads, exposure falls back to each pair's final approved amount.
|
|
439
|
+
return undefined
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
declare namespace readAllowances {
|
|
444
|
+
type Options = {
|
|
445
|
+
/** Owner whose allowances are read. */
|
|
446
|
+
account: Address
|
|
447
|
+
/** Block the calls were simulated against. */
|
|
448
|
+
blockNumber?: bigint | undefined
|
|
449
|
+
/** Calls preceding the reads. */
|
|
450
|
+
calls: readonly Call[]
|
|
451
|
+
/** Logs the calls emitted. */
|
|
452
|
+
logs: Log[]
|
|
453
|
+
}
|
|
454
|
+
}
|