@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/lib/footprint.cjs CHANGED
@@ -1,2 +1,2 @@
1
- !function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e(require("@stellar/stellar-sdk")):"function"==typeof define&&define.amd?define(["@stellar/stellar-sdk"],e):"object"==typeof exports?exports.axisFootprint=e(require("@stellar/stellar-sdk")):t.axisFootprint=e(t["@stellar/stellar-sdk"])}(this,t=>(()=>{"use strict";var e={346(e){e.exports=t}},r={};function o(t){var n=r[t];if(void 0!==n)return n.exports;var s=r[t]={exports:{}};return e[t](s,s.exports,o),s.exports}o.d=(t,e)=>{for(var r in e)o.o(e,r)&&!o.o(t,r)&&Object.defineProperty(t,r,{enumerable:!0,get:e[r]})},o.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);var n={};o.d(n,{default:()=>l});var s=o(346);const a=2e6,i=100000n;function d(...t){const e=new Set,r=[];for(const o of t)if(o)for(const t of o){if(null==t)continue;const o=BigInt(t),n=o.toString();e.has(n)||(e.add(n),r.push(o))}return r}function c(t,e){return s.xdr.LedgerKey.contractData(new s.xdr.LedgerKeyContractData({contract:s.Address.fromString(t).toScAddress(),key:s.xdr.ScVal.scvU64(new s.xdr.Uint64(BigInt(e))),durability:s.xdr.ContractDataDurability.persistent()}))}const l={collectOrderIds:d,ensureOrdersFootprint:function(t,e,r){const o=t.simulation;if(!o||o.error||o.restorePreamble||!t.built||!r?.length)return 0;const n=o.transactionData,l=n.getReadOnly(),u=n.getReadWrite(),f=new Map(l.map((t,e)=>[t.toXDR("base64"),e])),p=new Set(u.map(t=>t.toXDR("base64"))),b=new Set;let R=0;for(const t of d(r)){const r=c(e,t),o=r.toXDR("base64");p.has(o)||(f.has(o)&&b.add(f.get(o)),u.push(r),p.add(o),R++)}if(0===R)return 0;const x=l.filter((t,e)=>!b.has(e));n.setFootprint(x,u);const y=n.build().resources(),g=Math.min(y.instructions()+R*a,1e8);n.setResources(g,y.diskReadBytes(),y.writeBytes()+512*R);const m=n.build().resourceFee().toBigInt()+BigInt(R)*i;n.setResourceFee(m.toString()),delete t.simulationTransactionData;const D=t.options?.timeoutInSeconds??300;return t.built=s.TransactionBuilder.cloneFrom(t.built,{sorobanData:n.build(),timebounds:void 0}).setTimeout(D).build(),R},orderLedgerKey:c,ORDER_ENTRY_SIZE:512,ORDER_INSTRUCTIONS:a,ORDER_RESOURCE_FEE:i};return n.default})());
1
+ !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("@stellar/stellar-sdk")):"function"==typeof define&&define.amd?define(["@stellar/stellar-sdk"],t):"object"==typeof exports?exports.axisFootprint=t(require("@stellar/stellar-sdk")):e.axisFootprint=t(e["@stellar/stellar-sdk"])}(this,e=>(()=>{"use strict";var t={346(t){t.exports=e}},n={};function r(e){var s=n[e];if(void 0!==s)return s.exports;var o=n[e]={exports:{}};return t[e](o,o.exports,r),o.exports}r.d=(e,t)=>{for(var n in t)r.o(t,n)&&!r.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);var s={};r.d(s,{default:()=>w});var o=r(346);const a=2e6,i=100000n,c=3e6,l=2e6,u=new Set(["account","trustline"]);function d(...e){const t=new Set,n=[];for(const r of e)if(r)for(const e of r){if(null==e)continue;const r=BigInt(e),s=r.toString();t.has(s)||(t.add(s),n.push(r))}return n}function f(e,t){return R(e,(0,o.nativeToScVal)(BigInt(t),{type:"u128"}),o.xdr.ContractDataDurability.persistent)}function g(e){return R(e,o.xdr.ScVal.scvLedgerKeyContractInstance(),o.xdr.ContractDataDurability.persistent)}function y(e,t,n){if(!n)return null;if(o.StrKey.isValidContract(e))return R(t,o.xdr.ScVal.scvVec([o.xdr.ScVal.scvSymbol("Balance"),o.Address.fromString(e).toScVal()]),o.xdr.ContractDataDurability.persistent);const r=o.Keypair.fromPublicKey(e).xdrAccountId();return n.isNative()?o.xdr.LedgerKey.account(new o.xdr.LedgerKeyAccount({accountId:r})):n.getIssuer()===e?null:o.xdr.LedgerKey.trustline(new o.xdr.LedgerKeyTrustLine({accountId:r,asset:n.toTrustLineXDRObject()}))}function p(e,t,n){return R(t,o.xdr.ScVal.scvVec([o.xdr.ScVal.scvSymbol("Allowance"),o.xdr.ScVal.scvMap([new o.xdr.ScMapEntry({key:o.xdr.ScVal.scvSymbol("from"),val:o.Address.fromString(e).toScVal()}),new o.xdr.ScMapEntry({key:o.xdr.ScVal.scvSymbol("spender"),val:o.Address.fromString(n).toScVal()})])]),o.xdr.ContractDataDurability.temporary)}function S(e){const[t,n,r]=(0,o.scValToNative)(e);return{owner:t,selling:n,buying:r}}function b(e){if("scvContractInstance"!==e.type||"contractExecutableStellarAsset"!==e.instance.executable.type)return null;const t=(e.instance.storage??[]).find(({key:e})=>"AssetInfo"===(0,o.scValToNative)(e)?.[0]);if(!t)return null;const[n,r]=(0,o.scValToNative)(t.val);if("Native"===n)return o.Asset.native();const s=r.asset_code.replace(/\0+$/,"");return new o.Asset(s,o.StrKey.encodeEd25519PublicKey(r.issuer))}function R(e,t,n){return o.xdr.LedgerKey.contractData(new o.xdr.LedgerKeyContractData({contract:o.Address.fromString(e).toScAddress(),key:t,durability:n}))}function m(e){const t=e.simulation;return!(!t||t.error||t.restorePreamble||!e.built)}async function E(e,t){const n=new Map;for(let r=0;r<t.length;r+=200){const{entries:s}=await e.getLedgerEntries(...t.slice(r,r+200));for(const e of s)n.set(e.key.toXDR("base64"),e.val)}return n}function h(e,t){return[...new Set(e)].filter(e=>!t.has(e))}function x(e,t,n){for(const r of t){const t=e.get(g(r).toXDR("base64"));n.set(r,t?b(t.contractData.val):null)}}function v(e,t){const n=e.getReadOnly(),r=e.getReadWrite(),s=new Map(n.map((e,t)=>[e.toXDR("base64"),t])),o=new Set(r.map(e=>e.toXDR("base64"))),a=new Set,i=[];for(const e of t){const t=e.toXDR("base64");if(o.has(t))continue;const c=s.has(t),l=n.length-a.size+r.length;r.length>=200||!c&&l>=400||(c&&a.add(s.get(t)),r.push(e),o.add(t),i.push(e))}return i.length&&e.setFootprint(n.filter((e,t)=>!a.has(t)),r),i}function D(e,t,{instructions:n,diskReadBytes:r=0,writeBytes:s,fee:a}){const i=t.build().resources;t.setResources(Math.min(i.instructions+n,4e8),i.diskReadBytes+r,i.writeBytes+s),t.setResourceFee((t.build().resourceFee+a).toString()),delete e.simulationTransactionData;const c=e.options?.timeoutInSeconds??300;e.built=o.TransactionBuilder.cloneFrom(e.built,{sorobanData:t.build(),timebounds:void 0}).setTimeout(c).build()}const w={allowanceLedgerKey:p,balanceLedgerKey:y,collectOrderIds:d,completeFootprint:async function(e,t,n,{server:r,tokens:s=[],assetCache:o=new Map,passThrough:b=[],receiver:R,bought:w,takerOrder:I}){if(!m(e)||!n?.length)return{orders:0,settlementEntries:0,makerEntries:0};const O=d(n),K=O.map(e=>f(t,e)),A=h([...s,...b,...w?[w]:[]],o),T=await E(r,[...K,...A.map(g)]);x(T,A,o);const B=[];for(let e=0;e<O.length;e++){const t=T.get(K[e].toXDR("base64"));t&&B.push({id:O[e],...S(t.contractData.val)})}const V=[...b];if(null!=I){const e=B.find(e=>e.id===BigInt(I));e&&(V.push(e.buying),w??=e.buying)}const k=h(B.flatMap(({selling:e,buying:t})=>[e,t]),o);k.length&&x(await E(r,k.map(g)),k,o);const _=[...[...new Set(V)].map(e=>y(t,e,o.get(e)??null)),R&&w?y(R,w,o.get(w)??null):null].filter(Boolean),C=new Set(_.map(e=>e.toXDR("base64"))),F=new Map,L=[];for(const{owner:e,selling:n,buying:r}of B){const s=o.get(n),a=[y(e,n,s),s?p(e,n,t):null,y(e,r,o.get(r))];for(const t of a){if(!t)continue;const n=t.toXDR("base64");C.has(n)||(F.set(n,e),L.push(t))}}const N=e.simulation.transactionData,M=new Set(N.getReadOnly().map(e=>e.toXDR("base64"))),X=v(N,[...K,..._,...L]);if(!X.length)return{orders:0,settlementEntries:0,makerEntries:0};const U=new Set;let j=0,P=0,z=0;for(const e of X){const t=e.toXDR("base64");if(C.has(t))P++;else{if(!F.has(t))continue;j++,U.add(F.get(t))}u.has(e.type)&&!M.has(t)&&z++}const W=X.length-j-P,Y=P>0?1:0;return D(e,N,{instructions:W*a+U.size*c+Y*l,diskReadBytes:256*z,writeBytes:320*W+256*(j+P),fee:BigInt(W)*i+20000n*BigInt(j+P)+20000n*BigInt(U.size)+10000n*BigInt(Y)}),{orders:W,settlementEntries:P,makerEntries:j}},decodeSacAsset:b,decodeStoredOrder:S,ensureOrdersFootprint:function(e,t,n){if(!m(e)||!n?.length)return 0;const r=e.simulation.transactionData,s=v(r,d(n).map(e=>f(t,e))).length;return 0===s?0:(D(e,r,{instructions:s*a,writeBytes:320*s,fee:BigInt(s)*i}),s)},FORWARD_INSTRUCTIONS:l,FORWARD_RESOURCE_FEE:10000n,instanceLedgerKey:g,orderLedgerKey:f,MAKER_ENTRY_RESOURCE_FEE:20000n,MAKER_ENTRY_SIZE:256,MAKER_INSTRUCTIONS:c,MAKER_RESOURCE_FEE:20000n,ORDER_ENTRY_SIZE:320,ORDER_INSTRUCTIONS:a,ORDER_RESOURCE_FEE:i};return s.default})());
2
2
  //# sourceMappingURL=footprint.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"footprint.cjs","mappings":"CAAA,SAAAA,EAAAC,GACA,iBAAAC,SAAA,iBAAAC,OACAA,OAAAD,QAAAD,EAAAG,QAAA,yBACA,mBAAAC,QAAAA,OAAAC,IACAD,OAAA,yBAAAJ,GACA,iBAAAC,QACAA,QAAA,cAAAD,EAAAG,QAAA,yBAEAJ,EAAA,cAAAC,EAAAD,EAAA,wBACC,CATD,CASCO,KAAAC,oCCTDL,EAAAD,QAAAM,ICCAC,EAAA,GAGA,SAAAC,EAAAC,GAEA,IAAAC,EAAAH,EAAAE,GACA,QAAAE,IAAAD,EACA,OAAAA,EAAAV,QAGA,IAAAC,EAAAM,EAAAE,GAAA,CA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IAAIC,IAAIL,EAASM,IAAI,CAAC7D,EAAK8D,IAAM,CAAC9D,EAAI+D,MAAM,UAAWD,KACjEE,EAAU,IAAIhD,IAAIyC,EAAUI,IAAI7D,GAAOA,EAAI+D,MAAM,YACjDE,EAAmB,IAAIjD,IAC7B,IAAIkD,EAAQ,EACZ,IAAK,MAAM/C,KAAMN,EAAgBkC,GAAW,CACxC,MAAM/C,EAAM0B,EAAeC,EAAYR,GACjCgD,EAAUnE,EAAI+D,MAAM,UACtBC,EAAQzC,IAAI4C,KAGZR,EAAQpC,IAAI4C,IACZF,EAAiBzC,IAAImC,EAAQtD,IAAI8D,IAErCV,EAAUhC,KAAKzB,GACfgE,EAAQxC,IAAI2C,GACZD,IACJ,CACA,GAAc,IAAVA,EACA,OAAO,EACX,MAAME,EAAcb,EAASc,OAAO,CAACC,EAAGR,KAAOG,EAAiB1C,IAAIuC,IACpET,EAAKkB,aAAaH,EAAaX,GAG/B,MAAMe,EAAYnB,EAAKoB,QAAQD,YACzBE,EAAeC,KAAKC,IAAIJ,EAAUE,eAAiBR,EAAQvD,EAhFzC,KAiFxB0C,EAAKwB,aAAaH,EAAcF,EAAUM,gBAAiBN,EAAUO,aApGzC,IAoGwDb,GACpF,MAAMc,EAAc3B,EAAKoB,QAAQO,cAAcC,WAAa5D,OAAO6C,GAAStD,EAC5EyC,EAAK6B,eAAeF,EAAY1D,mBAGzBwB,EAAGqC,0BAEV,MAAMC,EAAUtC,EAAGuC,SAASC,kBAAoB,IAOhD,OANAxC,EAAGK,MAAQtB,EAAA0D,mBAAmBC,UAAU1C,EAAGK,MAAO,CAC9CsC,YAAapC,EAAKoB,QAClBiB,gBAAY9F,IAEX+F,WAAWP,GACXX,QACEP,CACX,EC9GIxC,eAAcA,EACdkE,iBDN4B,ICO5BjF,mBAAkBA,EAClBC,mBAAkBA","sources":["webpack://@axis-markets/client/webpack/universalModuleDefinition","webpack://@axis-markets/client/external umd \"@stellar/stellar-sdk\"","webpack://@axis-markets/client/webpack/bootstrap","webpack://@axis-markets/client/webpack/runtime/define property getters","webpack://@axis-markets/client/webpack/runtime/hasOwnProperty shorthand","webpack://@axis-markets/client/./src/footprint.js","webpack://@axis-markets/client/./src/footprint-cjs.js"],"sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory(require(\"@stellar/stellar-sdk\"));\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([\"@stellar/stellar-sdk\"], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"axisFootprint\"] = factory(require(\"@stellar/stellar-sdk\"));\n\telse\n\t\troot[\"axisFootprint\"] = factory(root[\"@stellar/stellar-sdk\"]);\n})(this, (__WEBPACK_EXTERNAL_MODULE__346__) => {\nreturn ","module.exports = __WEBPACK_EXTERNAL_MODULE__346__;","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\t// no module.id needed\n\t\t// no module.loaded needed\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId](module, module.exports, __webpack_require__);\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","import {xdr, Address, TransactionBuilder, contract} from '@stellar/stellar-sdk'\n\n/**\n * Upper bound of a serialized `Order` ledger entry in bytes.\n * (u64 id/expires, u32 kind, three 32-byte addresses, three i128 amounts = 428 bytes, rounded up to 512).\n * @type {number}\n */\nexport const ORDER_ENTRY_SIZE = 512\n\n/**\n * CPU instructions added to the declared budget for every order that was not matched at simulation time.\n * @type {number}\n */\nexport const ORDER_INSTRUCTIONS = 2_000_000\n\n/**\n * Resource fee (stroops) added for every order that was not matched at simulation time.\n * (write entry ~10k, read entry ~6k, writes ~12k, 2M instructions ~5k, trade/order events ~10k).\n * @type {bigint}\n */\nexport const ORDER_RESOURCE_FEE = 100_000n\n\n/**\n * Network-wide per-transaction instructions limit.\n * @type {number}\n */\nconst MAX_TX_INSTRUCTIONS = 100_000_000\n\n/**\n * Flatten and deduplicate order ids from several lists, coercing them to bigint.\n * @param {...(Array<bigint|number|string>|undefined|null)} idLists - Lists of order ids\n * @return {bigint[]} - Unique order ids in the order of first appearance\n */\nexport function collectOrderIds(...idLists) {\n const seen = new Set()\n const res = []\n for (const list of idLists) {\n if (!list)\n continue\n for (const id of list) {\n if (id === undefined || id === null)\n continue\n const value = BigInt(id)\n const key = value.toString()\n if (seen.has(key))\n continue\n seen.add(key)\n res.push(value)\n }\n }\n return res\n}\n\n/**\n * Build persistent contract data ledger key of an order.\n * @param {string} contractId - DEX contract address\n * @param {bigint|number|string} orderId - Order id\n * @return {xdr.LedgerKey}\n */\nexport function orderLedgerKey(contractId, orderId) {\n return xdr.LedgerKey.contractData(new xdr.LedgerKeyContractData({\n contract: Address.fromString(contractId).toScAddress(),\n key: xdr.ScVal.scvU64(new xdr.Uint64(BigInt(orderId))),\n durability: xdr.ContractDataDurability.persistent()\n }))\n}\n\n/**\n * Make sure every supplied order id declared in the read-write footprint of a simulated transaction.\n * @param {contract.AssembledTransaction} tx - Simulated transaction\n * @param {string} contractId - DEX contract address\n * @param {Array<bigint|number|string>} orderIds - Order ids passed to the contract call\n * @return {number} - Number of order entries added to the read-write footprint\n */\nexport function ensureOrdersFootprint(tx, contractId, orderIds) {\n const simulation = tx.simulation\n if (!simulation || simulation.error || simulation.restorePreamble || !tx.built || !orderIds?.length)\n return 0\n /** @type {SorobanDataBuilder} */\n const data = simulation.transactionData\n const readOnly = data.getReadOnly()\n const readWrite = data.getReadWrite()\n const roIndex = new Map(readOnly.map((key, i) => [key.toXDR('base64'), i]))\n const rwIndex = new Set(readWrite.map(key => key.toXDR('base64')))\n const dropFromReadOnly = new Set()\n let added = 0\n for (const id of collectOrderIds(orderIds)) {\n const key = orderLedgerKey(contractId, id)\n const encoded = key.toXDR('base64')\n if (rwIndex.has(encoded))\n continue\n //a key can't be listed in both parts of the footprint\n if (roIndex.has(encoded)) {\n dropFromReadOnly.add(roIndex.get(encoded))\n }\n readWrite.push(key)\n rwIndex.add(encoded)\n added++\n }\n if (added === 0)\n return 0\n const newReadOnly = readOnly.filter((_, i) => !dropFromReadOnly.has(i))\n data.setFootprint(newReadOnly, readWrite)\n\n //declare resources for the orders that may get matched at execution time\n const resources = data.build().resources()\n const instructions = Math.min(resources.instructions() + added * ORDER_INSTRUCTIONS, MAX_TX_INSTRUCTIONS)\n data.setResources(instructions, resources.diskReadBytes(), resources.writeBytes() + added * ORDER_ENTRY_SIZE)\n const resourceFee = data.build().resourceFee().toBigInt() + BigInt(added) * ORDER_RESOURCE_FEE\n data.setResourceFee(resourceFee.toString())\n\n //drop cached simulation data so the SDK picks up the patched builder when signing\n delete tx.simulationTransactionData\n //keep the built transaction consistent with the patched footprint and fee\n const timeout = tx.options?.timeoutInSeconds ?? 300\n tx.built = TransactionBuilder.cloneFrom(tx.built, {\n sorobanData: data.build(),\n timebounds: undefined\n })\n .setTimeout(timeout)\n .build()\n return added\n}\n","import {\n collectOrderIds,\n ensureOrdersFootprint,\n orderLedgerKey,\n ORDER_ENTRY_SIZE,\n ORDER_INSTRUCTIONS,\n ORDER_RESOURCE_FEE\n} from './footprint.js'\n\nconst axisFootprint = {\n collectOrderIds,\n ensureOrdersFootprint,\n orderLedgerKey,\n ORDER_ENTRY_SIZE,\n ORDER_INSTRUCTIONS,\n ORDER_RESOURCE_FEE\n}\n\nexport default axisFootprint\n"],"names":["root","factory","exports","module","require","define","amd","this","__WEBPACK_EXTERNAL_MODULE__346__","__webpack_module_cache__","__webpack_require__","moduleId","cachedModule","undefined","__webpack_modules__","d","definition","key","o","Object","defineProperty","enumerable","get","obj","prop","prototype","hasOwnProperty","call","ORDER_INSTRUCTIONS","ORDER_RESOURCE_FEE","collectOrderIds","idLists","seen","Set","res","list","id","value","BigInt","toString","has","add","push","orderLedgerKey","contractId","orderId","stellar_sdk_","xdr","LedgerKey","contractData","LedgerKeyContractData","contract","Address","fromString","toScAddress","ScVal","scvU64","Uint64","durability","ContractDataDurability","persistent","footprint_cjs","ensureOrdersFootprint","tx","orderIds","simulation","error","restorePreamble","built","length","data","transactionData","readOnly","getReadOnly","readWrite","getReadWrite","roIndex","Map","map","i","toXDR","rwIndex","dropFromReadOnly","added","encoded","newReadOnly","filter","_","setFootprint","resources","build","instructions","Math","min","setResources","diskReadBytes","writeBytes","resourceFee","toBigInt","setResourceFee","simulationTransactionData","timeout","options","timeoutInSeconds","TransactionBuilder","cloneFrom","sorobanData","timebounds","setTimeout","ORDER_ENTRY_SIZE"],"sourceRoot":""}
1
+ {"version":3,"file":"footprint.cjs","mappings":"CAAA,SAAAA,EAAAC,GACA,iBAAAC,SAAA,iBAAAC,OACAA,OAAAD,QAAAD,EAAAG,QAAA,yBACA,mBAAAC,QAAAA,OAAAC,IACAD,OAAA,yBAAAJ,GACA,iBAAAC,QACAA,QAAA,cAAAD,EAAAG,QAAA,yBAEAJ,EAAA,cAAAC,EAAAD,EAAA,wBACC,CATD,CASCO,KAAAC,oCCTDL,EAAAD,QAAAM,ICCAC,EAAA,GAGA,SAAAC,EAAAC,GAEA,IAAAC,EAAAH,EAAAE,GACA,QAAAE,IAAAD,EACA,OAAAA,EAAAV,QAGA,IAAAC,EAAAM,EAAAE,GAAA,CAGAT,QAAA,IAOA,OAHAY,EAAAH,GAAAR,EAAAA,EAAAD,QAAAQ,GAGAP,EAAAD,OACA,CCrBAQ,EAAAK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uB,EAAM,CACrBiB,aAAc+C,EAAe3K,EAAqByK,EAAOjD,KAAOtH,EAAqB0K,EAAUzK,EAC/F0H,cApSwB,IAoST6C,EACf5C,WAxTwB,IAwTZ6C,EArSY,KAqSuBlB,EAAeD,GAC9DzB,IAAKlH,OAAO8J,GAAgB1K,EAhSI,OAgSiBY,OAAO4I,EAAeD,GAnR7C,OAoRtB3I,OAAO4J,EAAOjD,MAtQU,OAsQmB3G,OAAO+J,KAEnD,CAACrB,OAAQoB,EAAcnB,oBAAmBC,eACrD,EC3SIzF,eAAcA,EACdJ,kBAAiBA,EACjBiH,sBDiLG,SAA+BzF,EAAIjE,EAAY+H,GAClD,IAAK/D,EAAYC,KAAQ8D,GAAUnD,OAC/B,OAAO,EACX,MAAMY,EAAOvB,EAAGC,WAAWmF,gBACrBpD,EAAQV,EAAiBC,EAAMrG,EAAgB4I,GAAUjC,IAAItG,GAAMO,EAAeC,EAAYR,KAAMoF,OAC1G,OAAc,IAAVqB,EACO,GACXO,EAAevC,EAAIuB,EAAM,CACrBiB,aAAcR,EAAQpH,EACtB8H,WA9MwB,IA8MZV,EACZW,IAAKlH,OAAOuG,GAASnH,IAElBmH,EACX,EC7LIjH,qBAAoBA,EACpB2K,qBD8BgC,OC7BhClJ,kBAAiBA,EACjBV,eAAcA,EACd6J,yBDAoC,OCCpCC,iBDP4B,ICQ5B9K,mBAAkBA,EAClB+K,mBDU8B,OCT9BC,iBD7B4B,IC8B5BlL,mBAAkBA,EAClBC,mBAAkBA","sources":["webpack://@axis-markets/client/webpack/universalModuleDefinition","webpack://@axis-markets/client/external umd \"@stellar/stellar-sdk\"","webpack://@axis-markets/client/webpack/bootstrap","webpack://@axis-markets/client/webpack/runtime/define property getters","webpack://@axis-markets/client/webpack/runtime/hasOwnProperty shorthand","webpack://@axis-markets/client/./src/footprint.js","webpack://@axis-markets/client/./src/footprint-cjs.js"],"sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory(require(\"@stellar/stellar-sdk\"));\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([\"@stellar/stellar-sdk\"], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"axisFootprint\"] = factory(require(\"@stellar/stellar-sdk\"));\n\telse\n\t\troot[\"axisFootprint\"] = factory(root[\"@stellar/stellar-sdk\"]);\n})(this, (__WEBPACK_EXTERNAL_MODULE__346__) => {\nreturn ","module.exports = __WEBPACK_EXTERNAL_MODULE__346__;","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\t// no module.id needed\n\t\t// no module.loaded needed\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId](module, module.exports, __webpack_require__);\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","import {xdr, Address, Asset, Keypair, StrKey, TransactionBuilder, nativeToScVal, scValToNative, contract, rpc} from '@stellar/stellar-sdk'\r\n\r\n/**\r\n * Upper bound of a serialized `Order` ledger entry in bytes.\r\n * (positional vector of three addresses, i128 amount and price, optional u64 expires = at most 188-byte value,\r\n * about 264-byte ledger entry, rounded up to 320).\r\n * @type {number}\r\n */\r\nexport const ORDER_ENTRY_SIZE = 320\r\n\r\n/**\r\n * CPU instructions added to the declared budget for every order that was not matched at simulation time.\r\n * @type {number}\r\n */\r\nexport const ORDER_INSTRUCTIONS = 2_000_000\r\n\r\n/**\r\n * Resource fee (stroops) added for every order that was not matched at simulation time.\r\n * (write entry ~10k, read entry ~6k, writes ~12k, 2M instructions ~5k, trade/order events ~10k).\r\n * @type {bigint}\r\n */\r\nexport const ORDER_RESOURCE_FEE = 100_000n\r\n\r\n/**\r\n * Upper bound of a maker balance (account, trustline or token balance) or allowance ledger entry in bytes.\r\n * @type {number}\r\n */\r\nexport const MAKER_ENTRY_SIZE = 256\r\n\r\n/**\r\n * Resource fee (stroops) added for every maker entry declared read-write (write entry ~10k, its bytes charged as written ~6k).\r\n * @type {bigint}\r\n */\r\nexport const MAKER_ENTRY_RESOURCE_FEE = 20_000n\r\n\r\n/**\r\n * CPU instructions added for every maker whose entries were declared (two token transfers, backing and receive checks).\r\n * @type {number}\r\n */\r\nexport const MAKER_INSTRUCTIONS = 3_000_000\r\n\r\n/**\r\n * Resource fee (stroops) added for every maker whose entries were declared (instructions ~8k, two transfer events and\r\n * a `skip` event ~4k, rounded up).\r\n * @type {bigint}\r\n */\r\nexport const MAKER_RESOURCE_FEE = 20_000n\r\n\r\n/**\r\n * CPU instructions added when the settlement entries of the call were declared: the transfer forwarding what the makers\r\n * delivered from the DEX contract to the receiver, and the receive checks before it.\r\n * @type {number}\r\n */\r\nexport const FORWARD_INSTRUCTIONS = 2_000_000\r\n\r\n/**\r\n * Resource fee (stroops) added when the settlement entries of the call were declared (instructions ~5k, the forwarding\r\n * `transfer` event ~2k, rounded up).\r\n * @type {bigint}\r\n */\r\nexport const FORWARD_RESOURCE_FEE = 10_000n\r\n\r\n/**\r\n * Ledger entry types read from disk when a transaction is applied: every declared one counts towards the disk read\r\n * bytes, whether the execution touches it or not.\r\n * @type {Set<string>}\r\n */\r\nconst DISK_ENTRY_TYPES = new Set(['account', 'trustline'])\r\n\r\n/**\r\n * Network-wide per-transaction instructions limit.\r\n * @type {number}\r\n */\r\nconst MAX_TX_INSTRUCTIONS = 400_000_000\r\n\r\n/**\r\n * Network-wide per-transaction limits of read-write and total footprint entries.\r\n */\r\nconst MAX_READ_WRITE_ENTRIES = 200\r\nconst MAX_FOOTPRINT_ENTRIES = 400\r\n\r\n/**\r\n * Keys per `getLedgerEntries` request accepted by RPC.\r\n */\r\nconst LEDGER_ENTRIES_BATCH = 200\r\n\r\n/**\r\n * Flatten and deduplicate order ids from several lists, coercing them to bigint.\r\n * @param {...(Array<bigint|number|string>|undefined|null)} idLists - Lists of order ids\r\n * @return {bigint[]} - Unique order ids in the order of first appearance\r\n */\r\nexport function collectOrderIds(...idLists) {\r\n const seen = new Set()\r\n const res = []\r\n for (const list of idLists) {\r\n if (!list)\r\n continue\r\n for (const id of list) {\r\n if (id === undefined || id === null)\r\n continue\r\n const value = BigInt(id)\r\n const key = value.toString()\r\n if (seen.has(key))\r\n continue\r\n seen.add(key)\r\n res.push(value)\r\n }\r\n }\r\n return res\r\n}\r\n\r\n/**\r\n * Build persistent contract data ledger key of an order (the key is the raw u128 order id).\r\n * @param {string} contractId - DEX contract address\r\n * @param {bigint|number|string} orderId - Order id\r\n * @return {xdr.LedgerKey}\r\n */\r\nexport function orderLedgerKey(contractId, orderId) {\r\n return contractDataKey(contractId, nativeToScVal(BigInt(orderId), {type: 'u128'}), xdr.ContractDataDurability.persistent)\r\n}\r\n\r\n/**\r\n * Build the ledger key of a contract instance entry.\r\n * @param {string} contractId - Contract address\r\n * @return {xdr.LedgerKey}\r\n */\r\nexport function instanceLedgerKey(contractId) {\r\n return contractDataKey(contractId, xdr.ScVal.scvLedgerKeyContractInstance(), xdr.ContractDataDurability.persistent)\r\n}\r\n\r\n/**\r\n * Build the ledger key holding the balance of `owner` in a Stellar Asset Contract token.\r\n * @param {string} owner - Account or contract address\r\n * @param {string} token - Token contract address\r\n * @param {Asset|null} asset - Classic asset behind the token, `null` for a token that is not a Stellar Asset Contract\r\n * @return {xdr.LedgerKey|null} - `null` when the balance has no ledger entry of its own (issuer) or the token storage layout is unknown\r\n */\r\nexport function balanceLedgerKey(owner, token, asset) {\r\n if (!asset)\r\n return null\r\n if (StrKey.isValidContract(owner))\r\n return contractDataKey(token, xdr.ScVal.scvVec([xdr.ScVal.scvSymbol('Balance'), Address.fromString(owner).toScVal()]), xdr.ContractDataDurability.persistent)\r\n const accountId = Keypair.fromPublicKey(owner).xdrAccountId()\r\n if (asset.isNative())\r\n return xdr.LedgerKey.account(new xdr.LedgerKeyAccount({accountId}))\r\n //the issuer holds no trustline for its own asset\r\n if (asset.getIssuer() === owner)\r\n return null\r\n return xdr.LedgerKey.trustline(new xdr.LedgerKeyTrustLine({accountId, asset: asset.toTrustLineXDRObject()}))\r\n}\r\n\r\n/**\r\n * Build the ledger key of the allowance `owner` granted to `spender` in a Stellar Asset Contract token.\r\n * @param {string} owner - Account or contract address granting the allowance\r\n * @param {string} token - Token contract address\r\n * @param {string} spender - Spender address (the DEX contract)\r\n * @return {xdr.LedgerKey}\r\n */\r\nexport function allowanceLedgerKey(owner, token, spender) {\r\n const key = xdr.ScVal.scvVec([\r\n xdr.ScVal.scvSymbol('Allowance'),\r\n xdr.ScVal.scvMap([\r\n new xdr.ScMapEntry({key: xdr.ScVal.scvSymbol('from'), val: Address.fromString(owner).toScVal()}),\r\n new xdr.ScMapEntry({key: xdr.ScVal.scvSymbol('spender'), val: Address.fromString(spender).toScVal()})\r\n ])\r\n ])\r\n return contractDataKey(token, key, xdr.ContractDataDurability.temporary)\r\n}\r\n\r\n/**\r\n * Decode a stored order entry value: a positional vector `[owner, selling, buying, amount, price, expires?]`.\r\n * @param {xdr.ScVal} val - Contract data value of the order entry\r\n * @return {{owner: string, selling: string, buying: string}}\r\n */\r\nexport function decodeStoredOrder(val) {\r\n const [owner, selling, buying] = scValToNative(val)\r\n return {owner, selling, buying}\r\n}\r\n\r\n/**\r\n * Resolve the classic asset behind a token from its contract instance entry.\r\n * @param {xdr.ScVal} val - Contract data value of the token instance entry\r\n * @return {Asset|null} - `null` for a token that is not a Stellar Asset Contract\r\n */\r\nexport function decodeSacAsset(val) {\r\n if (val.type !== 'scvContractInstance' || val.instance.executable.type !== 'contractExecutableStellarAsset')\r\n return null\r\n const entry = (val.instance.storage ?? []).find(({key}) => scValToNative(key)?.[0] === 'AssetInfo')\r\n if (!entry)\r\n return null\r\n const [type, info] = scValToNative(entry.val)\r\n if (type === 'Native')\r\n return Asset.native()\r\n //alphanum codes are padded with zero bytes\r\n const code = info.asset_code.replace(/\\0+$/, '')\r\n return new Asset(code, StrKey.encodeEd25519PublicKey(info.issuer))\r\n}\r\n\r\n/**\r\n * Make sure every supplied order id declared in the read-write footprint of a simulated transaction.\r\n * @param {contract.AssembledTransaction} tx - Simulated transaction\r\n * @param {string} contractId - DEX contract address\r\n * @param {Array<bigint|number|string>} orderIds - Order ids passed to the contract call\r\n * @return {number} - Number of order entries added to the read-write footprint\r\n */\r\nexport function ensureOrdersFootprint(tx, contractId, orderIds) {\r\n if (!isPatchable(tx) || !orderIds?.length)\r\n return 0\r\n const data = tx.simulation.transactionData\r\n const added = declareReadWrite(data, collectOrderIds(orderIds).map(id => orderLedgerKey(contractId, id))).length\r\n if (added === 0)\r\n return 0\r\n applyResources(tx, data, {\r\n instructions: added * ORDER_INSTRUCTIONS,\r\n writeBytes: added * ORDER_ENTRY_SIZE,\r\n fee: BigInt(added) * ORDER_RESOURCE_FEE\r\n })\r\n return added\r\n}\r\n\r\n/**\r\n * Complete the footprint of a simulated trading transaction, so it still applies when the book moves between simulation\r\n * and execution (an order repriced back into range, a maker's backing restored, an earlier order shrunk). Every listed\r\n * order entry is declared read-write, then the entries the settlement writes for the call itself: the DEX contract's own\r\n * balance of every asset passing through it (makers deliver to the contract, which forwards to the receiver) and the\r\n * receiver's balance of the bought asset. Then, for every order's maker, the balance of the asset the maker sells, the\r\n * allowance on it granted to the DEX contract, and the balance of the asset the maker receives. Tokens that are not\r\n * Stellar Asset Contracts keep what the simulation recorded (their storage layout is unknown). Entries are added in that\r\n * order while the footprint limits allow.\r\n * @param {contract.AssembledTransaction} tx - Simulated transaction\r\n * @param {string} contractId - DEX contract address\r\n * @param {Array<bigint|number|string>} orderIds - Order ids passed to the contract call\r\n * @param {FootprintOptions} options\r\n * @return {Promise<{orders: number, settlementEntries: number, makerEntries: number}>} - Number of order, settlement and\r\n * maker entries added to the read-write footprint\r\n */\r\nexport async function completeFootprint(tx, contractId, orderIds, {server, tokens = [], assetCache = new Map(), passThrough = [], receiver, bought, takerOrder}) {\r\n if (!isPatchable(tx) || !orderIds?.length)\r\n return {orders: 0, settlementEntries: 0, makerEntries: 0}\r\n const ids = collectOrderIds(orderIds)\r\n const orderKeys = ids.map(id => orderLedgerKey(contractId, id))\r\n //one request for the orders and the known tokens, another one only for tokens first seen in the orders\r\n const knownTokens = unresolved([...tokens, ...passThrough, ...(bought ? [bought] : [])], assetCache)\r\n const entries = await loadEntries(server, [...orderKeys, ...knownTokens.map(instanceLedgerKey)])\r\n cacheAssets(entries, knownTokens, assetCache)\r\n const orders = []\r\n for (let i = 0; i < ids.length; i++) {\r\n const entry = entries.get(orderKeys[i].toXDR('base64'))\r\n if (entry) {\r\n orders.push({id: ids[i], ...decodeStoredOrder(entry.contractData.val)})\r\n }\r\n }\r\n //a crossfill buys what the taker order buys: it passes through the contract, which pays the owner and the receiver\r\n const passing = [...passThrough]\r\n if (takerOrder !== undefined && takerOrder !== null) {\r\n const taker = orders.find(order => order.id === BigInt(takerOrder))\r\n if (taker) {\r\n passing.push(taker.buying)\r\n bought ??= taker.buying\r\n }\r\n }\r\n const newTokens = unresolved(orders.flatMap(({selling, buying}) => [selling, buying]), assetCache)\r\n if (newTokens.length) {\r\n cacheAssets(await loadEntries(server, newTokens.map(instanceLedgerKey)), newTokens, assetCache)\r\n }\r\n //entries the settlement of the call writes whichever makers fill\r\n const settlementKeys = [\r\n ...[...new Set(passing)].map(token => balanceLedgerKey(contractId, token, assetCache.get(token) ?? null)),\r\n receiver && bought ? balanceLedgerKey(receiver, bought, assetCache.get(bought) ?? null) : null\r\n ].filter(Boolean)\r\n const settlementSet = new Set(settlementKeys.map(key => key.toXDR('base64')))\r\n //entries the settlement writes for each maker, tagged with the maker\r\n const makerOf = new Map()\r\n const makerKeys = []\r\n for (const {owner, selling, buying} of orders) {\r\n const sold = assetCache.get(selling)\r\n const keys = [\r\n balanceLedgerKey(owner, selling, sold),\r\n sold ? allowanceLedgerKey(owner, selling, contractId) : null,\r\n balanceLedgerKey(owner, buying, assetCache.get(buying))\r\n ]\r\n for (const key of keys) {\r\n if (!key)\r\n continue\r\n const encoded = key.toXDR('base64')\r\n if (settlementSet.has(encoded))\r\n continue //declared with the settlement entries\r\n makerOf.set(encoded, owner)\r\n makerKeys.push(key)\r\n }\r\n }\r\n const data = tx.simulation.transactionData\r\n //entries promoted from the read-only part are already counted as disk reads by the simulation\r\n const readOnly = new Set(data.getReadOnly().map(key => key.toXDR('base64')))\r\n const added = declareReadWrite(data, [...orderKeys, ...settlementKeys, ...makerKeys])\r\n if (!added.length)\r\n return {orders: 0, settlementEntries: 0, makerEntries: 0}\r\n const makers = new Set()\r\n let makerEntries = 0\r\n let settlementEntries = 0\r\n let diskEntries = 0\r\n for (const key of added) {\r\n const encoded = key.toXDR('base64')\r\n if (settlementSet.has(encoded)) {\r\n settlementEntries++\r\n } else if (makerOf.has(encoded)) {\r\n makerEntries++\r\n makers.add(makerOf.get(encoded))\r\n } else\r\n continue\r\n if (DISK_ENTRY_TYPES.has(key.type) && !readOnly.has(encoded)) {\r\n diskEntries++\r\n }\r\n }\r\n const orderEntries = added.length - makerEntries - settlementEntries\r\n //the forwarding transfer runs only when something settles, which the simulation did not see\r\n const forward = settlementEntries > 0 ? 1 : 0\r\n applyResources(tx, data, {\r\n instructions: orderEntries * ORDER_INSTRUCTIONS + makers.size * MAKER_INSTRUCTIONS + forward * FORWARD_INSTRUCTIONS,\r\n diskReadBytes: diskEntries * MAKER_ENTRY_SIZE,\r\n writeBytes: orderEntries * ORDER_ENTRY_SIZE + (makerEntries + settlementEntries) * MAKER_ENTRY_SIZE,\r\n fee: BigInt(orderEntries) * ORDER_RESOURCE_FEE + BigInt(makerEntries + settlementEntries) * MAKER_ENTRY_RESOURCE_FEE +\r\n BigInt(makers.size) * MAKER_RESOURCE_FEE + BigInt(forward) * FORWARD_RESOURCE_FEE\r\n })\r\n return {orders: orderEntries, settlementEntries, makerEntries}\r\n}\r\n\r\n/**\r\n * @param {string} contractId\r\n * @param {xdr.ScVal} key\r\n * @param {xdr.ContractDataDurability} durability\r\n * @return {xdr.LedgerKey}\r\n * @private\r\n */\r\nfunction contractDataKey(contractId, key, durability) {\r\n return xdr.LedgerKey.contractData(new xdr.LedgerKeyContractData({\r\n contract: Address.fromString(contractId).toScAddress(),\r\n key,\r\n durability\r\n }))\r\n}\r\n\r\n/**\r\n * Whether the simulation succeeded and can be patched\r\n * @param {contract.AssembledTransaction} tx\r\n * @return {boolean}\r\n * @private\r\n */\r\nfunction isPatchable(tx) {\r\n const simulation = tx.simulation\r\n return !!simulation && !simulation.error && !simulation.restorePreamble && !!tx.built\r\n}\r\n\r\n/**\r\n * Fetch ledger entries, keyed by the base64 XDR of their ledger keys\r\n * @param {rpc.Server} server\r\n * @param {xdr.LedgerKey[]} keys\r\n * @return {Promise<Map<string, xdr.LedgerEntryData>>}\r\n * @private\r\n */\r\nasync function loadEntries(server, keys) {\r\n const res = new Map()\r\n for (let i = 0; i < keys.length; i += LEDGER_ENTRIES_BATCH) {\r\n const {entries} = await server.getLedgerEntries(...keys.slice(i, i + LEDGER_ENTRIES_BATCH))\r\n for (const entry of entries) {\r\n res.set(entry.key.toXDR('base64'), entry.val)\r\n }\r\n }\r\n return res\r\n}\r\n\r\n/**\r\n * Tokens from the list not resolved yet, deduplicated\r\n * @param {string[]} tokens\r\n * @param {Map<string, Asset|null>} assetCache\r\n * @return {string[]}\r\n * @private\r\n */\r\nfunction unresolved(tokens, assetCache) {\r\n return [...new Set(tokens)].filter(token => !assetCache.has(token))\r\n}\r\n\r\n/**\r\n * Store the classic asset of every token from the loaded instance entries (`null` when unknown)\r\n * @param {Map<string, xdr.LedgerEntryData>} entries\r\n * @param {string[]} tokens\r\n * @param {Map<string, Asset|null>} assetCache\r\n * @private\r\n */\r\nfunction cacheAssets(entries, tokens, assetCache) {\r\n for (const token of tokens) {\r\n const entry = entries.get(instanceLedgerKey(token).toXDR('base64'))\r\n assetCache.set(token, entry ? decodeSacAsset(entry.contractData.val) : null)\r\n }\r\n}\r\n\r\n/**\r\n * Add keys to the read-write part of a simulated footprint, dropping them from the read-only part, while the\r\n * footprint limits allow\r\n * @param {SorobanDataBuilder} data - Simulation data to patch\r\n * @param {xdr.LedgerKey[]} keys - Keys to declare, in priority order\r\n * @return {xdr.LedgerKey[]} - Keys actually added\r\n * @private\r\n */\r\nfunction declareReadWrite(data, keys) {\r\n const readOnly = data.getReadOnly()\r\n const readWrite = data.getReadWrite()\r\n const roIndex = new Map(readOnly.map((key, i) => [key.toXDR('base64'), i]))\r\n const rwIndex = new Set(readWrite.map(key => key.toXDR('base64')))\r\n const dropFromReadOnly = new Set()\r\n const added = []\r\n for (const key of keys) {\r\n const encoded = key.toXDR('base64')\r\n if (rwIndex.has(encoded))\r\n continue\r\n //a key promoted from the read-only part does not grow the footprint\r\n const promoted = roIndex.has(encoded)\r\n const total = readOnly.length - dropFromReadOnly.size + readWrite.length\r\n if (readWrite.length >= MAX_READ_WRITE_ENTRIES || (!promoted && total >= MAX_FOOTPRINT_ENTRIES))\r\n continue\r\n //a key can't be listed in both parts of the footprint\r\n if (promoted) {\r\n dropFromReadOnly.add(roIndex.get(encoded))\r\n }\r\n readWrite.push(key)\r\n rwIndex.add(encoded)\r\n added.push(key)\r\n }\r\n if (added.length) {\r\n data.setFootprint(readOnly.filter((_, i) => !dropFromReadOnly.has(i)), readWrite)\r\n }\r\n return added\r\n}\r\n\r\n/**\r\n * Declare the resources of the added entries and rebuild the transaction from the patched simulation data\r\n * @param {contract.AssembledTransaction} tx - Simulated transaction\r\n * @param {SorobanDataBuilder} data - Patched simulation data\r\n * @param {{instructions: number, diskReadBytes?: number, writeBytes: number, fee: bigint}} extra - Resources and fee to add\r\n * @private\r\n */\r\nfunction applyResources(tx, data, {instructions, diskReadBytes = 0, writeBytes, fee}) {\r\n const resources = data.build().resources\r\n data.setResources(Math.min(resources.instructions + instructions, MAX_TX_INSTRUCTIONS), resources.diskReadBytes + diskReadBytes, resources.writeBytes + writeBytes)\r\n data.setResourceFee((data.build().resourceFee + fee).toString())\r\n\r\n //drop cached simulation data so the SDK picks up the patched builder when signing\r\n delete tx.simulationTransactionData\r\n //keep the built transaction consistent with the patched footprint and fee\r\n const timeout = tx.options?.timeoutInSeconds ?? 300\r\n tx.built = TransactionBuilder.cloneFrom(tx.built, {\r\n sorobanData: data.build(),\r\n timebounds: undefined\r\n })\r\n .setTimeout(timeout)\r\n .build()\r\n}\r\n\r\n/**\r\n * @typedef {{}} FootprintOptions\r\n * @property {rpc.Server} server - RPC server used to load the listed orders and the token instances\r\n * @property {string[]} [tokens] - Tokens the call trades, resolved together with the orders\r\n * @property {Map<string, Asset|null>} [assetCache] - Classic assets of resolved tokens (`null` for other tokens), reused between calls\r\n * @property {string[]} [passThrough] - Tokens the call moves through the DEX contract's own balance: the bought asset of a\r\n * trade, every hop asset of a swap\r\n * @property {string} [receiver] - Account the bought asset is forwarded to (the trader, or the crossfill caller paid the surplus)\r\n * @property {string} [bought] - Token the receiver gets (the taker order's `buying` by default for a crossfill)\r\n * @property {bigint|number|string} [takerOrder] - Taker order of a crossfill: the asset it buys passes through the contract\r\n */\r\n","import {\n allowanceLedgerKey,\n balanceLedgerKey,\n collectOrderIds,\n completeFootprint,\n decodeSacAsset,\n decodeStoredOrder,\n ensureOrdersFootprint,\n FORWARD_INSTRUCTIONS,\n FORWARD_RESOURCE_FEE,\n instanceLedgerKey,\n orderLedgerKey,\n MAKER_ENTRY_RESOURCE_FEE,\n MAKER_ENTRY_SIZE,\n MAKER_INSTRUCTIONS,\n MAKER_RESOURCE_FEE,\n ORDER_ENTRY_SIZE,\n ORDER_INSTRUCTIONS,\n ORDER_RESOURCE_FEE\n} from './footprint.js'\n\nconst axisFootprint = {\n allowanceLedgerKey,\n balanceLedgerKey,\n collectOrderIds,\n completeFootprint,\n decodeSacAsset,\n decodeStoredOrder,\n ensureOrdersFootprint,\n FORWARD_INSTRUCTIONS,\n FORWARD_RESOURCE_FEE,\n instanceLedgerKey,\n orderLedgerKey,\n MAKER_ENTRY_RESOURCE_FEE,\n MAKER_ENTRY_SIZE,\n MAKER_INSTRUCTIONS,\n MAKER_RESOURCE_FEE,\n ORDER_ENTRY_SIZE,\n ORDER_INSTRUCTIONS,\n ORDER_RESOURCE_FEE\n}\n\nexport default axisFootprint\n"],"names":["root","factory","exports","module","require","define","amd","this","__WEBPACK_EXTERNAL_MODULE__346__","__webpack_module_cache__","__webpack_require__","moduleId","cachedModule","undefined","__webpack_modules__","d","definition","key","o","Object","defineProperty","enumerable","get","obj","prop","prototype","hasOwnProperty","call","ORDER_INSTRUCTIONS","ORDER_RESOURCE_FEE","MAKER_INSTRUCTIONS","FORWARD_INSTRUCTIONS","DISK_ENTRY_TYPES","Set","collectOrderIds","idLists","seen","res","list","id","value","BigInt","toString","has","add","push","orderLedgerKey","contractId","orderId","contractDataKey","stellar_sdk_","nativeToScVal","type","xdr","ContractDataDurability","persistent","instanceLedgerKey","ScVal","scvLedgerKeyContractInstance","balanceLedgerKey","owner","token","asset","StrKey","isValidContract","scvVec","scvSymbol","Address","fromString","toScVal","accountId","Keypair","fromPublicKey","xdrAccountId","isNative","LedgerKey","account","LedgerKeyAccount","getIssuer","trustline","LedgerKeyTrustLine","toTrustLineXDRObject","allowanceLedgerKey","spender","scvMap","ScMapEntry","val","temporary","decodeStoredOrder","selling","buying","scValToNative","decodeSacAsset","instance","executable","entry","storage","find","info","Asset","native","code","asset_code","replace","encodeEd25519PublicKey","issuer","durability","contractData","LedgerKeyContractData","contract","toScAddress","isPatchable","tx","simulation","error","restorePreamble","built","async","loadEntries","server","keys","Map","i","length","entries","getLedgerEntries","slice","set","toXDR","unresolved","tokens","assetCache","filter","cacheAssets","declareReadWrite","data","readOnly","getReadOnly","readWrite","getReadWrite","roIndex","map","rwIndex","dropFromReadOnly","added","encoded","promoted","total","size","setFootprint","_","applyResources","instructions","diskReadBytes","writeBytes","fee","resources","build","setResources","Math","min","setResourceFee","resourceFee","simulationTransactionData","timeout","options","timeoutInSeconds","TransactionBuilder","cloneFrom","sorobanData","timebounds","setTimeout","footprint_cjs","completeFootprint","orderIds","passThrough","receiver","bought","takerOrder","orders","settlementEntries","makerEntries","ids","orderKeys","knownTokens","passing","taker","order","newTokens","flatMap","settlementKeys","Boolean","settlementSet","makerOf","makerKeys","sold","transactionData","makers","diskEntries","orderEntries","forward","ensureOrdersFootprint","FORWARD_RESOURCE_FEE","MAKER_ENTRY_RESOURCE_FEE","MAKER_ENTRY_SIZE","MAKER_RESOURCE_FEE","ORDER_ENTRY_SIZE"],"sourceRoot":""}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@axis-markets/client",
3
- "version": "0.5.0",
3
+ "version": "0.8.0",
4
4
  "description": "AXIS contract and API client",
5
5
  "author": "team@stellar.expert",
6
6
  "license": "MIT",
@@ -32,7 +32,7 @@
32
32
  "prepare": "webpack --mode=production --config webpack.config.cjs"
33
33
  },
34
34
  "peerDependencies": {
35
- "@stellar/stellar-sdk": ">=16"
35
+ "@stellar/stellar-sdk": ">=17"
36
36
  },
37
37
  "engines": {
38
38
  "node": ">=22"
@@ -0,0 +1,46 @@
1
+ import {PRICE_SCALE} from './asset-pair.js'
2
+
3
+ /**
4
+ * Allowance lifetime granted with a trade, in ledgers: ~30 days at 5s per ledger (the maximum entry TTL ~180 days)
5
+ */
6
+ export const APPROVAL_TTL_LEDGERS = 518_400
7
+
8
+ /**
9
+ * An allowance expiring within this number of ledgers is renewed with the next trade (~1 day)
10
+ */
11
+ export const APPROVAL_RENEW_LEDGERS = 17_280
12
+
13
+ /**
14
+ * Decide whether a call needs an in-call approval and adjust it. The approval amount is absolute and one allowance backs
15
+ * every order selling the token across all markets, so it has to cover this call plus every order selling the same asset
16
+ * @param {ApprovalPlanParams} params
17
+ * @return {{amount: bigint, liveUntil: number}|undefined} - Approval to pass with the call, undefined when the current allowance already covers it
18
+ */
19
+ export function planApproval({required, committed, allowance, liveUntil, ledger}) {
20
+ const target = required + committed
21
+ const expiring = liveUntil > 0 && liveUntil < ledger + APPROVAL_RENEW_LEDGERS
22
+ if (allowance >= target && !expiring)
23
+ return undefined //TODO: reduce outstanding allowances if the backed amount is reduced (expired or cancelled)
24
+ return {amount: target, liveUntil: ledger + APPROVAL_TTL_LEDGERS}
25
+ }
26
+
27
+ /**
28
+ * Max amount of `selling` tokens a buy trade may cost: `ceil(amount × price / 10^18)`
29
+ * @param {bigint} amount - Amount of `buying` tokens to acquire
30
+ * @param {bigint} price - Limit price (`selling` per 1 `buying`, with AXIS standard price decimals)
31
+ * @return {bigint}
32
+ */
33
+ export function maxQuoteSpend(amount, price) {
34
+ if (amount <= 0n || price <= 0n)
35
+ return 0n
36
+ return (amount * price + PRICE_SCALE - 1n) / PRICE_SCALE
37
+ }
38
+
39
+ /**
40
+ * @typedef {{}} ApprovalPlanParams
41
+ * @property {bigint} required - Max amount of the selling asset the call may spend
42
+ * @property {bigint} committed - Remaining amount of orders in the book selling the asset
43
+ * @property {bigint} allowance - Current allowance (0 once expired)
44
+ * @property {number} ledger - Current ledger sequence
45
+ * @property {number} [liveUntil] - Ledger the current allowance lives until (0 or omitted when unknown)
46
+ */