@axis-markets/client 0.7.0 → 0.8.1

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