@axis-markets/client 0.5.0 → 0.7.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,11 +1,12 @@
1
- import {xdr, Address, TransactionBuilder, contract} from '@stellar/stellar-sdk'
1
+ import {xdr, Address, Asset, Keypair, StrKey, TransactionBuilder, nativeToScVal, scValToNative, contract, rpc} from '@stellar/stellar-sdk'
2
2
 
3
3
  /**
4
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).
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).
6
7
  * @type {number}
7
8
  */
8
- export const ORDER_ENTRY_SIZE = 512
9
+ export const ORDER_ENTRY_SIZE = 320
9
10
 
10
11
  /**
11
12
  * CPU instructions added to the declared budget for every order that was not matched at simulation time.
@@ -20,11 +21,54 @@ export const ORDER_INSTRUCTIONS = 2_000_000
20
21
  */
21
22
  export const ORDER_RESOURCE_FEE = 100_000n
22
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
+
23
56
  /**
24
57
  * Network-wide per-transaction instructions limit.
25
58
  * @type {number}
26
59
  */
27
- const MAX_TX_INSTRUCTIONS = 100_000_000
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
28
72
 
29
73
  /**
30
74
  * Flatten and deduplicate order ids from several lists, coercing them to bigint.
@@ -52,17 +96,90 @@ export function collectOrderIds(...idLists) {
52
96
  }
53
97
 
54
98
  /**
55
- * Build persistent contract data ledger key of an order.
99
+ * Build persistent contract data ledger key of an order (the key is the raw u128 order id).
56
100
  * @param {string} contractId - DEX contract address
57
101
  * @param {bigint|number|string} orderId - Order id
58
102
  * @return {xdr.LedgerKey}
59
103
  */
60
104
  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
- }))
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))
66
183
  }
67
184
 
68
185
  /**
@@ -73,41 +190,214 @@ export function orderLedgerKey(contractId, orderId) {
73
190
  * @return {number} - Number of order entries added to the read-write footprint
74
191
  */
75
192
  export function ensureOrdersFootprint(tx, contractId, orderIds) {
76
- const simulation = tx.simulation
77
- if (!simulation || simulation.error || simulation.restorePreamble || !tx.built || !orderIds?.length)
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)
78
198
  return 0
79
- /** @type {SorobanDataBuilder} */
80
- const data = simulation.transactionData
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) {
81
361
  const readOnly = data.getReadOnly()
82
362
  const readWrite = data.getReadWrite()
83
363
  const roIndex = new Map(readOnly.map((key, i) => [key.toXDR('base64'), i]))
84
364
  const rwIndex = new Set(readWrite.map(key => key.toXDR('base64')))
85
365
  const dropFromReadOnly = new Set()
86
- let added = 0
87
- for (const id of collectOrderIds(orderIds)) {
88
- const key = orderLedgerKey(contractId, id)
366
+ const added = []
367
+ for (const key of keys) {
89
368
  const encoded = key.toXDR('base64')
90
369
  if (rwIndex.has(encoded))
91
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
92
376
  //a key can't be listed in both parts of the footprint
93
- if (roIndex.has(encoded)) {
377
+ if (promoted) {
94
378
  dropFromReadOnly.add(roIndex.get(encoded))
95
379
  }
96
380
  readWrite.push(key)
97
381
  rwIndex.add(encoded)
98
- added++
382
+ added.push(key)
99
383
  }
100
- if (added === 0)
101
- return 0
102
- const newReadOnly = readOnly.filter((_, i) => !dropFromReadOnly.has(i))
103
- data.setFootprint(newReadOnly, readWrite)
384
+ if (added.length) {
385
+ data.setFootprint(readOnly.filter((_, i) => !dropFromReadOnly.has(i)), readWrite)
386
+ }
387
+ return added
388
+ }
104
389
 
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())
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())
111
401
 
112
402
  //drop cached simulation data so the SDK picks up the patched builder when signing
113
403
  delete tx.simulationTransactionData
@@ -119,5 +409,11 @@ export function ensureOrdersFootprint(tx, contractId, orderIds) {
119
409
  })
120
410
  .setTimeout(timeout)
121
411
  .build()
122
- return added
123
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
+ */