viem 2.57.12 → 2.57.14
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 +34 -0
- package/_cjs/actions/public/fillTransaction.js +6 -3
- package/_cjs/actions/public/fillTransaction.js.map +1 -1
- package/_cjs/actions/public/watchContractEvent.js +58 -29
- package/_cjs/actions/public/watchContractEvent.js.map +1 -1
- package/_cjs/actions/public/watchEvent.js +58 -29
- package/_cjs/actions/public/watchEvent.js.map +1 -1
- package/_cjs/chains/definitions/molibra.js +21 -0
- package/_cjs/chains/definitions/molibra.js.map +1 -0
- package/_cjs/chains/index.js +9 -7
- package/_cjs/chains/index.js.map +1 -1
- package/_cjs/errors/version.js +1 -1
- package/_cjs/tempo/Account.js +4 -4
- package/_cjs/tempo/Account.js.map +1 -1
- package/_cjs/tempo/Formatters.js +17 -3
- 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.map +1 -1
- package/_cjs/tempo/accounts/Config.js +21 -8
- package/_cjs/tempo/accounts/Config.js.map +1 -1
- package/_cjs/tempo/chainConfig.js +17 -5
- package/_cjs/tempo/chainConfig.js.map +1 -1
- package/_cjs/tempo/internal/relay/accounts.js +41 -4
- package/_cjs/tempo/internal/relay/accounts.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 +4 -1
- 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/_esm/actions/public/fillTransaction.js +8 -3
- package/_esm/actions/public/fillTransaction.js.map +1 -1
- package/_esm/actions/public/watchContractEvent.js +73 -36
- package/_esm/actions/public/watchContractEvent.js.map +1 -1
- package/_esm/actions/public/watchEvent.js +73 -36
- package/_esm/actions/public/watchEvent.js.map +1 -1
- package/_esm/chains/definitions/molibra.js +18 -0
- package/_esm/chains/definitions/molibra.js.map +1 -0
- package/_esm/chains/index.js +1 -0
- package/_esm/chains/index.js.map +1 -1
- package/_esm/errors/version.js +1 -1
- package/_esm/tempo/Account.js +4 -4
- package/_esm/tempo/Account.js.map +1 -1
- package/_esm/tempo/Formatters.js +17 -4
- 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.map +1 -1
- package/_esm/tempo/accounts/Config.js +27 -12
- package/_esm/tempo/accounts/Config.js.map +1 -1
- package/_esm/tempo/chainConfig.js +22 -5
- package/_esm/tempo/chainConfig.js.map +1 -1
- package/_esm/tempo/internal/relay/accounts.js +43 -4
- package/_esm/tempo/internal/relay/accounts.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 +4 -1
- 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/_types/actions/getContract.d.ts +1 -1
- package/_types/actions/public/fillTransaction.d.ts.map +1 -1
- package/_types/actions/public/watchContractEvent.d.ts +1 -1
- package/_types/actions/public/watchContractEvent.d.ts.map +1 -1
- package/_types/actions/public/watchEvent.d.ts +1 -1
- package/_types/actions/public/watchEvent.d.ts.map +1 -1
- package/_types/chains/definitions/molibra.d.ts +52 -0
- package/_types/chains/definitions/molibra.d.ts.map +1 -0
- package/_types/chains/definitions/tempo.d.ts +14 -6
- package/_types/chains/definitions/tempo.d.ts.map +1 -1
- package/_types/chains/definitions/tempoDevnet.d.ts +14 -6
- package/_types/chains/definitions/tempoDevnet.d.ts.map +1 -1
- package/_types/chains/definitions/tempoLocalnet.d.ts +14 -6
- package/_types/chains/definitions/tempoLocalnet.d.ts.map +1 -1
- package/_types/chains/definitions/tempoModerato.d.ts +14 -6
- package/_types/chains/definitions/tempoModerato.d.ts.map +1 -1
- package/_types/chains/index.d.ts +1 -0
- package/_types/chains/index.d.ts.map +1 -1
- package/_types/clients/decorators/public.d.ts +2 -2
- package/_types/errors/version.d.ts +1 -1
- package/_types/tempo/Account.d.ts +15 -1
- 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/Formatters.d.ts +3 -0
- package/_types/tempo/Formatters.d.ts.map +1 -1
- package/_types/tempo/Relay.d.ts +46 -0
- package/_types/tempo/Relay.d.ts.map +1 -1
- package/_types/tempo/Transaction.d.ts +7 -2
- package/_types/tempo/Transaction.d.ts.map +1 -1
- package/_types/tempo/accounts/Config.d.ts +24 -2
- package/_types/tempo/accounts/Config.d.ts.map +1 -1
- package/_types/tempo/actions/accessKey.d.ts +2 -2
- package/_types/tempo/chainConfig.d.ts +8 -3
- package/_types/tempo/chainConfig.d.ts.map +1 -1
- package/_types/tempo/internal/relay/accounts.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/actions/getContract.ts +1 -1
- package/actions/public/fillTransaction.ts +12 -3
- package/actions/public/watchContractEvent.ts +82 -39
- package/actions/public/watchEvent.ts +82 -39
- package/chains/definitions/molibra.ts +18 -0
- package/chains/index.ts +1 -0
- package/clients/decorators/public.ts +2 -2
- package/errors/version.ts +1 -1
- package/package.json +1 -1
- package/tempo/Account.ts +19 -9
- package/tempo/Capabilities.ts +34 -2
- package/tempo/Formatters.ts +24 -12
- package/tempo/Relay.ts +57 -0
- package/tempo/Transaction.ts +10 -2
- package/tempo/accounts/Config.ts +39 -16
- package/tempo/actions/accessKey.ts +2 -2
- package/tempo/chainConfig.ts +26 -5
- package/tempo/internal/relay/accounts.ts +44 -6
- package/tempo/internal/relay/autoSwap.ts +263 -0
- package/tempo/internal/relay/error.ts +7 -2
- package/tempo/internal/relay/feePayer.ts +6 -1
- package/tempo/internal/relay/feeToken.ts +21 -3
- package/tempo/internal/relay/simulate.ts +106 -19
|
@@ -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, {
|
|
@@ -817,7 +817,12 @@ function isBaseFeeRejection(error: unknown) {
|
|
|
817
817
|
const { cause, code, message } = current as Record<string, unknown>
|
|
818
818
|
// Reth reports pool admission failures as invalid input (-32000). `transaction underpriced`
|
|
819
819
|
// reflects a node-configurable floor, so another node could still admit the envelope.
|
|
820
|
-
if (
|
|
820
|
+
if (
|
|
821
|
+
code === -32000 &&
|
|
822
|
+
typeof message === 'string' &&
|
|
823
|
+
(message === 'gas price is less than basefee' ||
|
|
824
|
+
message.startsWith('fee cap less than base fee'))
|
|
825
|
+
)
|
|
821
826
|
return true
|
|
822
827
|
current = cause
|
|
823
828
|
}
|
|
@@ -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
|
+
}
|