@axis-markets/client 0.5.0 → 0.8.0

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/src/footprint.js CHANGED
@@ -1,123 +1,469 @@
1
- import {xdr, Address, TransactionBuilder, contract} from '@stellar/stellar-sdk'
2
-
3
- /**
4
- * Upper bound of a serialized `Order` ledger entry in bytes.
5
- * (u64 id/expires, u32 kind, three 32-byte addresses, three i128 amounts = 428 bytes, rounded up to 512).
6
- * @type {number}
7
- */
8
- export const ORDER_ENTRY_SIZE = 512
9
-
10
- /**
11
- * CPU instructions added to the declared budget for every order that was not matched at simulation time.
12
- * @type {number}
13
- */
14
- export const ORDER_INSTRUCTIONS = 2_000_000
15
-
16
- /**
17
- * Resource fee (stroops) added for every order that was not matched at simulation time.
18
- * (write entry ~10k, read entry ~6k, writes ~12k, 2M instructions ~5k, trade/order events ~10k).
19
- * @type {bigint}
20
- */
21
- export const ORDER_RESOURCE_FEE = 100_000n
22
-
23
- /**
24
- * Network-wide per-transaction instructions limit.
25
- * @type {number}
26
- */
27
- const MAX_TX_INSTRUCTIONS = 100_000_000
28
-
29
- /**
30
- * Flatten and deduplicate order ids from several lists, coercing them to bigint.
31
- * @param {...(Array<bigint|number|string>|undefined|null)} idLists - Lists of order ids
32
- * @return {bigint[]} - Unique order ids in the order of first appearance
33
- */
34
- export function collectOrderIds(...idLists) {
35
- const seen = new Set()
36
- const res = []
37
- for (const list of idLists) {
38
- if (!list)
39
- continue
40
- for (const id of list) {
41
- if (id === undefined || id === null)
42
- continue
43
- const value = BigInt(id)
44
- const key = value.toString()
45
- if (seen.has(key))
46
- continue
47
- seen.add(key)
48
- res.push(value)
49
- }
50
- }
51
- return res
52
- }
53
-
54
- /**
55
- * Build persistent contract data ledger key of an order.
56
- * @param {string} contractId - DEX contract address
57
- * @param {bigint|number|string} orderId - Order id
58
- * @return {xdr.LedgerKey}
59
- */
60
- export function orderLedgerKey(contractId, orderId) {
61
- return xdr.LedgerKey.contractData(new xdr.LedgerKeyContractData({
62
- contract: Address.fromString(contractId).toScAddress(),
63
- key: xdr.ScVal.scvU64(new xdr.Uint64(BigInt(orderId))),
64
- durability: xdr.ContractDataDurability.persistent()
65
- }))
66
- }
67
-
68
- /**
69
- * Make sure every supplied order id declared in the read-write footprint of a simulated transaction.
70
- * @param {contract.AssembledTransaction} tx - Simulated transaction
71
- * @param {string} contractId - DEX contract address
72
- * @param {Array<bigint|number|string>} orderIds - Order ids passed to the contract call
73
- * @return {number} - Number of order entries added to the read-write footprint
74
- */
75
- export function ensureOrdersFootprint(tx, contractId, orderIds) {
76
- const simulation = tx.simulation
77
- if (!simulation || simulation.error || simulation.restorePreamble || !tx.built || !orderIds?.length)
78
- return 0
79
- /** @type {SorobanDataBuilder} */
80
- const data = simulation.transactionData
81
- const readOnly = data.getReadOnly()
82
- const readWrite = data.getReadWrite()
83
- const roIndex = new Map(readOnly.map((key, i) => [key.toXDR('base64'), i]))
84
- const rwIndex = new Set(readWrite.map(key => key.toXDR('base64')))
85
- const dropFromReadOnly = new Set()
86
- let added = 0
87
- for (const id of collectOrderIds(orderIds)) {
88
- const key = orderLedgerKey(contractId, id)
89
- const encoded = key.toXDR('base64')
90
- if (rwIndex.has(encoded))
91
- continue
92
- //a key can't be listed in both parts of the footprint
93
- if (roIndex.has(encoded)) {
94
- dropFromReadOnly.add(roIndex.get(encoded))
95
- }
96
- readWrite.push(key)
97
- rwIndex.add(encoded)
98
- added++
99
- }
100
- if (added === 0)
101
- return 0
102
- const newReadOnly = readOnly.filter((_, i) => !dropFromReadOnly.has(i))
103
- data.setFootprint(newReadOnly, readWrite)
104
-
105
- //declare resources for the orders that may get matched at execution time
106
- const resources = data.build().resources()
107
- const instructions = Math.min(resources.instructions() + added * ORDER_INSTRUCTIONS, MAX_TX_INSTRUCTIONS)
108
- data.setResources(instructions, resources.diskReadBytes(), resources.writeBytes() + added * ORDER_ENTRY_SIZE)
109
- const resourceFee = data.build().resourceFee().toBigInt() + BigInt(added) * ORDER_RESOURCE_FEE
110
- data.setResourceFee(resourceFee.toString())
111
-
112
- //drop cached simulation data so the SDK picks up the patched builder when signing
113
- delete tx.simulationTransactionData
114
- //keep the built transaction consistent with the patched footprint and fee
115
- const timeout = tx.options?.timeoutInSeconds ?? 300
116
- tx.built = TransactionBuilder.cloneFrom(tx.built, {
117
- sorobanData: data.build(),
118
- timebounds: undefined
119
- })
120
- .setTimeout(timeout)
121
- .build()
122
- return added
123
- }
1
+ import {xdr, Address, Asset, Keypair, StrKey, TransactionBuilder, nativeToScVal, scValToNative, contract, rpc} from '@stellar/stellar-sdk'
2
+
3
+ /**
4
+ * Upper bound of a serialized `Order` ledger entry in bytes.
5
+ * (positional vector of three addresses, i128 amount and price, optional u64 expires = at most 188-byte value,
6
+ * about 264-byte ledger entry, rounded up to 320).
7
+ * @type {number}
8
+ */
9
+ export const ORDER_ENTRY_SIZE = 320
10
+
11
+ /**
12
+ * CPU instructions added to the declared budget for every order that was not matched at simulation time.
13
+ * @type {number}
14
+ */
15
+ export const ORDER_INSTRUCTIONS = 2_000_000
16
+
17
+ /**
18
+ * Resource fee (stroops) added for every order that was not matched at simulation time.
19
+ * (write entry ~10k, read entry ~6k, writes ~12k, 2M instructions ~5k, trade/order events ~10k).
20
+ * @type {bigint}
21
+ */
22
+ export const ORDER_RESOURCE_FEE = 100_000n
23
+
24
+ /**
25
+ * Upper bound of a maker balance (account, trustline or token balance) or allowance ledger entry in bytes.
26
+ * @type {number}
27
+ */
28
+ export const MAKER_ENTRY_SIZE = 256
29
+
30
+ /**
31
+ * Resource fee (stroops) added for every maker entry declared read-write (write entry ~10k, its bytes charged as written ~6k).
32
+ * @type {bigint}
33
+ */
34
+ export const MAKER_ENTRY_RESOURCE_FEE = 20_000n
35
+
36
+ /**
37
+ * CPU instructions added for every maker whose entries were declared (two token transfers, backing and receive checks).
38
+ * @type {number}
39
+ */
40
+ export const MAKER_INSTRUCTIONS = 3_000_000
41
+
42
+ /**
43
+ * Resource fee (stroops) added for every maker whose entries were declared (instructions ~8k, two transfer events and
44
+ * a `skip` event ~4k, rounded up).
45
+ * @type {bigint}
46
+ */
47
+ export const MAKER_RESOURCE_FEE = 20_000n
48
+
49
+ /**
50
+ * CPU instructions added when the settlement entries of the call were declared: the transfer forwarding what the makers
51
+ * delivered from the DEX contract to the receiver, and the receive checks before it.
52
+ * @type {number}
53
+ */
54
+ export const FORWARD_INSTRUCTIONS = 2_000_000
55
+
56
+ /**
57
+ * Resource fee (stroops) added when the settlement entries of the call were declared (instructions ~5k, the forwarding
58
+ * `transfer` event ~2k, rounded up).
59
+ * @type {bigint}
60
+ */
61
+ export const FORWARD_RESOURCE_FEE = 10_000n
62
+
63
+ /**
64
+ * Ledger entry types read from disk when a transaction is applied: every declared one counts towards the disk read
65
+ * bytes, whether the execution touches it or not.
66
+ * @type {Set<string>}
67
+ */
68
+ const DISK_ENTRY_TYPES = new Set(['account', 'trustline'])
69
+
70
+ /**
71
+ * Network-wide per-transaction instructions limit.
72
+ * @type {number}
73
+ */
74
+ const MAX_TX_INSTRUCTIONS = 400_000_000
75
+
76
+ /**
77
+ * Network-wide per-transaction limits of read-write and total footprint entries.
78
+ */
79
+ const MAX_READ_WRITE_ENTRIES = 200
80
+ const MAX_FOOTPRINT_ENTRIES = 400
81
+
82
+ /**
83
+ * Keys per `getLedgerEntries` request accepted by RPC.
84
+ */
85
+ const LEDGER_ENTRIES_BATCH = 200
86
+
87
+ /**
88
+ * Flatten and deduplicate order ids from several lists, coercing them to bigint.
89
+ * @param {...(Array<bigint|number|string>|undefined|null)} idLists - Lists of order ids
90
+ * @return {bigint[]} - Unique order ids in the order of first appearance
91
+ */
92
+ export function collectOrderIds(...idLists) {
93
+ const seen = new Set()
94
+ const res = []
95
+ for (const list of idLists) {
96
+ if (!list)
97
+ continue
98
+ for (const id of list) {
99
+ if (id === undefined || id === null)
100
+ continue
101
+ const value = BigInt(id)
102
+ const key = value.toString()
103
+ if (seen.has(key))
104
+ continue
105
+ seen.add(key)
106
+ res.push(value)
107
+ }
108
+ }
109
+ return res
110
+ }
111
+
112
+ /**
113
+ * Build persistent contract data ledger key of an order (the key is the raw u128 order id).
114
+ * @param {string} contractId - DEX contract address
115
+ * @param {bigint|number|string} orderId - Order id
116
+ * @return {xdr.LedgerKey}
117
+ */
118
+ export function orderLedgerKey(contractId, orderId) {
119
+ return contractDataKey(contractId, nativeToScVal(BigInt(orderId), {type: 'u128'}), xdr.ContractDataDurability.persistent)
120
+ }
121
+
122
+ /**
123
+ * Build the ledger key of a contract instance entry.
124
+ * @param {string} contractId - Contract address
125
+ * @return {xdr.LedgerKey}
126
+ */
127
+ export function instanceLedgerKey(contractId) {
128
+ return contractDataKey(contractId, xdr.ScVal.scvLedgerKeyContractInstance(), xdr.ContractDataDurability.persistent)
129
+ }
130
+
131
+ /**
132
+ * Build the ledger key holding the balance of `owner` in a Stellar Asset Contract token.
133
+ * @param {string} owner - Account or contract address
134
+ * @param {string} token - Token contract address
135
+ * @param {Asset|null} asset - Classic asset behind the token, `null` for a token that is not a Stellar Asset Contract
136
+ * @return {xdr.LedgerKey|null} - `null` when the balance has no ledger entry of its own (issuer) or the token storage layout is unknown
137
+ */
138
+ export function balanceLedgerKey(owner, token, asset) {
139
+ if (!asset)
140
+ return null
141
+ if (StrKey.isValidContract(owner))
142
+ return contractDataKey(token, xdr.ScVal.scvVec([xdr.ScVal.scvSymbol('Balance'), Address.fromString(owner).toScVal()]), xdr.ContractDataDurability.persistent)
143
+ const accountId = Keypair.fromPublicKey(owner).xdrAccountId()
144
+ if (asset.isNative())
145
+ return xdr.LedgerKey.account(new xdr.LedgerKeyAccount({accountId}))
146
+ //the issuer holds no trustline for its own asset
147
+ if (asset.getIssuer() === owner)
148
+ return null
149
+ return xdr.LedgerKey.trustline(new xdr.LedgerKeyTrustLine({accountId, asset: asset.toTrustLineXDRObject()}))
150
+ }
151
+
152
+ /**
153
+ * Build the ledger key of the allowance `owner` granted to `spender` in a Stellar Asset Contract token.
154
+ * @param {string} owner - Account or contract address granting the allowance
155
+ * @param {string} token - Token contract address
156
+ * @param {string} spender - Spender address (the DEX contract)
157
+ * @return {xdr.LedgerKey}
158
+ */
159
+ export function allowanceLedgerKey(owner, token, spender) {
160
+ const key = xdr.ScVal.scvVec([
161
+ xdr.ScVal.scvSymbol('Allowance'),
162
+ xdr.ScVal.scvMap([
163
+ new xdr.ScMapEntry({key: xdr.ScVal.scvSymbol('from'), val: Address.fromString(owner).toScVal()}),
164
+ new xdr.ScMapEntry({key: xdr.ScVal.scvSymbol('spender'), val: Address.fromString(spender).toScVal()})
165
+ ])
166
+ ])
167
+ return contractDataKey(token, key, xdr.ContractDataDurability.temporary)
168
+ }
169
+
170
+ /**
171
+ * Decode a stored order entry value: a positional vector `[owner, selling, buying, amount, price, expires?]`.
172
+ * @param {xdr.ScVal} val - Contract data value of the order entry
173
+ * @return {{owner: string, selling: string, buying: string}}
174
+ */
175
+ export function decodeStoredOrder(val) {
176
+ const [owner, selling, buying] = scValToNative(val)
177
+ return {owner, selling, buying}
178
+ }
179
+
180
+ /**
181
+ * Resolve the classic asset behind a token from its contract instance entry.
182
+ * @param {xdr.ScVal} val - Contract data value of the token instance entry
183
+ * @return {Asset|null} - `null` for a token that is not a Stellar Asset Contract
184
+ */
185
+ export function decodeSacAsset(val) {
186
+ if (val.type !== 'scvContractInstance' || val.instance.executable.type !== 'contractExecutableStellarAsset')
187
+ return null
188
+ const entry = (val.instance.storage ?? []).find(({key}) => scValToNative(key)?.[0] === 'AssetInfo')
189
+ if (!entry)
190
+ return null
191
+ const [type, info] = scValToNative(entry.val)
192
+ if (type === 'Native')
193
+ return Asset.native()
194
+ //alphanum codes are padded with zero bytes
195
+ const code = info.asset_code.replace(/\0+$/, '')
196
+ return new Asset(code, StrKey.encodeEd25519PublicKey(info.issuer))
197
+ }
198
+
199
+ /**
200
+ * Make sure every supplied order id declared in the read-write footprint of a simulated transaction.
201
+ * @param {contract.AssembledTransaction} tx - Simulated transaction
202
+ * @param {string} contractId - DEX contract address
203
+ * @param {Array<bigint|number|string>} orderIds - Order ids passed to the contract call
204
+ * @return {number} - Number of order entries added to the read-write footprint
205
+ */
206
+ export function ensureOrdersFootprint(tx, contractId, orderIds) {
207
+ if (!isPatchable(tx) || !orderIds?.length)
208
+ return 0
209
+ const data = tx.simulation.transactionData
210
+ const added = declareReadWrite(data, collectOrderIds(orderIds).map(id => orderLedgerKey(contractId, id))).length
211
+ if (added === 0)
212
+ return 0
213
+ applyResources(tx, data, {
214
+ instructions: added * ORDER_INSTRUCTIONS,
215
+ writeBytes: added * ORDER_ENTRY_SIZE,
216
+ fee: BigInt(added) * ORDER_RESOURCE_FEE
217
+ })
218
+ return added
219
+ }
220
+
221
+ /**
222
+ * Complete the footprint of a simulated trading transaction, so it still applies when the book moves between simulation
223
+ * and execution (an order repriced back into range, a maker's backing restored, an earlier order shrunk). Every listed
224
+ * order entry is declared read-write, then the entries the settlement writes for the call itself: the DEX contract's own
225
+ * balance of every asset passing through it (makers deliver to the contract, which forwards to the receiver) and the
226
+ * receiver's balance of the bought asset. Then, for every order's maker, the balance of the asset the maker sells, the
227
+ * allowance on it granted to the DEX contract, and the balance of the asset the maker receives. Tokens that are not
228
+ * Stellar Asset Contracts keep what the simulation recorded (their storage layout is unknown). Entries are added in that
229
+ * order while the footprint limits allow.
230
+ * @param {contract.AssembledTransaction} tx - Simulated transaction
231
+ * @param {string} contractId - DEX contract address
232
+ * @param {Array<bigint|number|string>} orderIds - Order ids passed to the contract call
233
+ * @param {FootprintOptions} options
234
+ * @return {Promise<{orders: number, settlementEntries: number, makerEntries: number}>} - Number of order, settlement and
235
+ * maker entries added to the read-write footprint
236
+ */
237
+ export async function completeFootprint(tx, contractId, orderIds, {server, tokens = [], assetCache = new Map(), passThrough = [], receiver, bought, takerOrder}) {
238
+ if (!isPatchable(tx) || !orderIds?.length)
239
+ return {orders: 0, settlementEntries: 0, makerEntries: 0}
240
+ const ids = collectOrderIds(orderIds)
241
+ const orderKeys = ids.map(id => orderLedgerKey(contractId, id))
242
+ //one request for the orders and the known tokens, another one only for tokens first seen in the orders
243
+ const knownTokens = unresolved([...tokens, ...passThrough, ...(bought ? [bought] : [])], assetCache)
244
+ const entries = await loadEntries(server, [...orderKeys, ...knownTokens.map(instanceLedgerKey)])
245
+ cacheAssets(entries, knownTokens, assetCache)
246
+ const orders = []
247
+ for (let i = 0; i < ids.length; i++) {
248
+ const entry = entries.get(orderKeys[i].toXDR('base64'))
249
+ if (entry) {
250
+ orders.push({id: ids[i], ...decodeStoredOrder(entry.contractData.val)})
251
+ }
252
+ }
253
+ //a crossfill buys what the taker order buys: it passes through the contract, which pays the owner and the receiver
254
+ const passing = [...passThrough]
255
+ if (takerOrder !== undefined && takerOrder !== null) {
256
+ const taker = orders.find(order => order.id === BigInt(takerOrder))
257
+ if (taker) {
258
+ passing.push(taker.buying)
259
+ bought ??= taker.buying
260
+ }
261
+ }
262
+ const newTokens = unresolved(orders.flatMap(({selling, buying}) => [selling, buying]), assetCache)
263
+ if (newTokens.length) {
264
+ cacheAssets(await loadEntries(server, newTokens.map(instanceLedgerKey)), newTokens, assetCache)
265
+ }
266
+ //entries the settlement of the call writes whichever makers fill
267
+ const settlementKeys = [
268
+ ...[...new Set(passing)].map(token => balanceLedgerKey(contractId, token, assetCache.get(token) ?? null)),
269
+ receiver && bought ? balanceLedgerKey(receiver, bought, assetCache.get(bought) ?? null) : null
270
+ ].filter(Boolean)
271
+ const settlementSet = new Set(settlementKeys.map(key => key.toXDR('base64')))
272
+ //entries the settlement writes for each maker, tagged with the maker
273
+ const makerOf = new Map()
274
+ const makerKeys = []
275
+ for (const {owner, selling, buying} of orders) {
276
+ const sold = assetCache.get(selling)
277
+ const keys = [
278
+ balanceLedgerKey(owner, selling, sold),
279
+ sold ? allowanceLedgerKey(owner, selling, contractId) : null,
280
+ balanceLedgerKey(owner, buying, assetCache.get(buying))
281
+ ]
282
+ for (const key of keys) {
283
+ if (!key)
284
+ continue
285
+ const encoded = key.toXDR('base64')
286
+ if (settlementSet.has(encoded))
287
+ continue //declared with the settlement entries
288
+ makerOf.set(encoded, owner)
289
+ makerKeys.push(key)
290
+ }
291
+ }
292
+ const data = tx.simulation.transactionData
293
+ //entries promoted from the read-only part are already counted as disk reads by the simulation
294
+ const readOnly = new Set(data.getReadOnly().map(key => key.toXDR('base64')))
295
+ const added = declareReadWrite(data, [...orderKeys, ...settlementKeys, ...makerKeys])
296
+ if (!added.length)
297
+ return {orders: 0, settlementEntries: 0, makerEntries: 0}
298
+ const makers = new Set()
299
+ let makerEntries = 0
300
+ let settlementEntries = 0
301
+ let diskEntries = 0
302
+ for (const key of added) {
303
+ const encoded = key.toXDR('base64')
304
+ if (settlementSet.has(encoded)) {
305
+ settlementEntries++
306
+ } else if (makerOf.has(encoded)) {
307
+ makerEntries++
308
+ makers.add(makerOf.get(encoded))
309
+ } else
310
+ continue
311
+ if (DISK_ENTRY_TYPES.has(key.type) && !readOnly.has(encoded)) {
312
+ diskEntries++
313
+ }
314
+ }
315
+ const orderEntries = added.length - makerEntries - settlementEntries
316
+ //the forwarding transfer runs only when something settles, which the simulation did not see
317
+ const forward = settlementEntries > 0 ? 1 : 0
318
+ applyResources(tx, data, {
319
+ instructions: orderEntries * ORDER_INSTRUCTIONS + makers.size * MAKER_INSTRUCTIONS + forward * FORWARD_INSTRUCTIONS,
320
+ diskReadBytes: diskEntries * MAKER_ENTRY_SIZE,
321
+ writeBytes: orderEntries * ORDER_ENTRY_SIZE + (makerEntries + settlementEntries) * MAKER_ENTRY_SIZE,
322
+ fee: BigInt(orderEntries) * ORDER_RESOURCE_FEE + BigInt(makerEntries + settlementEntries) * MAKER_ENTRY_RESOURCE_FEE +
323
+ BigInt(makers.size) * MAKER_RESOURCE_FEE + BigInt(forward) * FORWARD_RESOURCE_FEE
324
+ })
325
+ return {orders: orderEntries, settlementEntries, makerEntries}
326
+ }
327
+
328
+ /**
329
+ * @param {string} contractId
330
+ * @param {xdr.ScVal} key
331
+ * @param {xdr.ContractDataDurability} durability
332
+ * @return {xdr.LedgerKey}
333
+ * @private
334
+ */
335
+ function contractDataKey(contractId, key, durability) {
336
+ return xdr.LedgerKey.contractData(new xdr.LedgerKeyContractData({
337
+ contract: Address.fromString(contractId).toScAddress(),
338
+ key,
339
+ durability
340
+ }))
341
+ }
342
+
343
+ /**
344
+ * Whether the simulation succeeded and can be patched
345
+ * @param {contract.AssembledTransaction} tx
346
+ * @return {boolean}
347
+ * @private
348
+ */
349
+ function isPatchable(tx) {
350
+ const simulation = tx.simulation
351
+ return !!simulation && !simulation.error && !simulation.restorePreamble && !!tx.built
352
+ }
353
+
354
+ /**
355
+ * Fetch ledger entries, keyed by the base64 XDR of their ledger keys
356
+ * @param {rpc.Server} server
357
+ * @param {xdr.LedgerKey[]} keys
358
+ * @return {Promise<Map<string, xdr.LedgerEntryData>>}
359
+ * @private
360
+ */
361
+ async function loadEntries(server, keys) {
362
+ const res = new Map()
363
+ for (let i = 0; i < keys.length; i += LEDGER_ENTRIES_BATCH) {
364
+ const {entries} = await server.getLedgerEntries(...keys.slice(i, i + LEDGER_ENTRIES_BATCH))
365
+ for (const entry of entries) {
366
+ res.set(entry.key.toXDR('base64'), entry.val)
367
+ }
368
+ }
369
+ return res
370
+ }
371
+
372
+ /**
373
+ * Tokens from the list not resolved yet, deduplicated
374
+ * @param {string[]} tokens
375
+ * @param {Map<string, Asset|null>} assetCache
376
+ * @return {string[]}
377
+ * @private
378
+ */
379
+ function unresolved(tokens, assetCache) {
380
+ return [...new Set(tokens)].filter(token => !assetCache.has(token))
381
+ }
382
+
383
+ /**
384
+ * Store the classic asset of every token from the loaded instance entries (`null` when unknown)
385
+ * @param {Map<string, xdr.LedgerEntryData>} entries
386
+ * @param {string[]} tokens
387
+ * @param {Map<string, Asset|null>} assetCache
388
+ * @private
389
+ */
390
+ function cacheAssets(entries, tokens, assetCache) {
391
+ for (const token of tokens) {
392
+ const entry = entries.get(instanceLedgerKey(token).toXDR('base64'))
393
+ assetCache.set(token, entry ? decodeSacAsset(entry.contractData.val) : null)
394
+ }
395
+ }
396
+
397
+ /**
398
+ * Add keys to the read-write part of a simulated footprint, dropping them from the read-only part, while the
399
+ * footprint limits allow
400
+ * @param {SorobanDataBuilder} data - Simulation data to patch
401
+ * @param {xdr.LedgerKey[]} keys - Keys to declare, in priority order
402
+ * @return {xdr.LedgerKey[]} - Keys actually added
403
+ * @private
404
+ */
405
+ function declareReadWrite(data, keys) {
406
+ const readOnly = data.getReadOnly()
407
+ const readWrite = data.getReadWrite()
408
+ const roIndex = new Map(readOnly.map((key, i) => [key.toXDR('base64'), i]))
409
+ const rwIndex = new Set(readWrite.map(key => key.toXDR('base64')))
410
+ const dropFromReadOnly = new Set()
411
+ const added = []
412
+ for (const key of keys) {
413
+ const encoded = key.toXDR('base64')
414
+ if (rwIndex.has(encoded))
415
+ continue
416
+ //a key promoted from the read-only part does not grow the footprint
417
+ const promoted = roIndex.has(encoded)
418
+ const total = readOnly.length - dropFromReadOnly.size + readWrite.length
419
+ if (readWrite.length >= MAX_READ_WRITE_ENTRIES || (!promoted && total >= MAX_FOOTPRINT_ENTRIES))
420
+ continue
421
+ //a key can't be listed in both parts of the footprint
422
+ if (promoted) {
423
+ dropFromReadOnly.add(roIndex.get(encoded))
424
+ }
425
+ readWrite.push(key)
426
+ rwIndex.add(encoded)
427
+ added.push(key)
428
+ }
429
+ if (added.length) {
430
+ data.setFootprint(readOnly.filter((_, i) => !dropFromReadOnly.has(i)), readWrite)
431
+ }
432
+ return added
433
+ }
434
+
435
+ /**
436
+ * Declare the resources of the added entries and rebuild the transaction from the patched simulation data
437
+ * @param {contract.AssembledTransaction} tx - Simulated transaction
438
+ * @param {SorobanDataBuilder} data - Patched simulation data
439
+ * @param {{instructions: number, diskReadBytes?: number, writeBytes: number, fee: bigint}} extra - Resources and fee to add
440
+ * @private
441
+ */
442
+ function applyResources(tx, data, {instructions, diskReadBytes = 0, writeBytes, fee}) {
443
+ const resources = data.build().resources
444
+ data.setResources(Math.min(resources.instructions + instructions, MAX_TX_INSTRUCTIONS), resources.diskReadBytes + diskReadBytes, resources.writeBytes + writeBytes)
445
+ data.setResourceFee((data.build().resourceFee + fee).toString())
446
+
447
+ //drop cached simulation data so the SDK picks up the patched builder when signing
448
+ delete tx.simulationTransactionData
449
+ //keep the built transaction consistent with the patched footprint and fee
450
+ const timeout = tx.options?.timeoutInSeconds ?? 300
451
+ tx.built = TransactionBuilder.cloneFrom(tx.built, {
452
+ sorobanData: data.build(),
453
+ timebounds: undefined
454
+ })
455
+ .setTimeout(timeout)
456
+ .build()
457
+ }
458
+
459
+ /**
460
+ * @typedef {{}} FootprintOptions
461
+ * @property {rpc.Server} server - RPC server used to load the listed orders and the token instances
462
+ * @property {string[]} [tokens] - Tokens the call trades, resolved together with the orders
463
+ * @property {Map<string, Asset|null>} [assetCache] - Classic assets of resolved tokens (`null` for other tokens), reused between calls
464
+ * @property {string[]} [passThrough] - Tokens the call moves through the DEX contract's own balance: the bought asset of a
465
+ * trade, every hop asset of a swap
466
+ * @property {string} [receiver] - Account the bought asset is forwarded to (the trader, or the crossfill caller paid the surplus)
467
+ * @property {string} [bought] - Token the receiver gets (the taker order's `buying` by default for a crossfill)
468
+ * @property {bigint|number|string} [takerOrder] - Taker order of a crossfill: the asset it buys passes through the contract
469
+ */