@axis-markets/client 0.4.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/README.md +372 -66
- package/lib/axis-client.cjs +1 -1
- package/lib/axis-client.cjs.map +1 -1
- package/lib/footprint.cjs +2 -0
- package/lib/footprint.cjs.map +1 -0
- package/package.json +10 -3
- package/src/allowance.js +46 -0
- package/src/api-client.js +95 -12
- package/src/api-dates.js +17 -0
- package/src/asset-pair.js +104 -0
- package/src/axis-account.js +970 -0
- package/src/axis-market.js +197 -0
- package/src/axis.js +408 -0
- package/src/constants.js +15 -0
- package/src/contract-client.js +47 -20
- package/src/emitter.js +71 -0
- package/src/errors.js +62 -29
- package/src/footprint.d.ts +102 -0
- package/src/footprint.js +419 -0
- package/src/index.d.ts +1446 -521
- package/src/index.js +522 -246
- package/src/order-id.js +47 -0
- package/src/stream-client.js +327 -0
- package/src/token-balance.js +81 -0
|
@@ -0,0 +1,2 @@
|
|
|
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 o=n[e];if(void 0!==o)return o.exports;var s=n[e]={exports:{}};return t[e](s,s.exports,r),s.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 o={};r.d(o,{default:()=>D});var s=r(346);const a=2e6,c=100000n,i=3e6,l=new Set(["account","trustline"]);function u(...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),o=r.toString();t.has(o)||(t.add(o),n.push(r))}return n}function d(e,t){return b(e,(0,s.nativeToScVal)(BigInt(t),{type:"u128"}),s.xdr.ContractDataDurability.persistent)}function f(e){return b(e,s.xdr.ScVal.scvLedgerKeyContractInstance(),s.xdr.ContractDataDurability.persistent)}function y(e,t,n){if(!n)return null;if(s.StrKey.isValidContract(e))return b(t,s.xdr.ScVal.scvVec([s.xdr.ScVal.scvSymbol("Balance"),s.Address.fromString(e).toScVal()]),s.xdr.ContractDataDurability.persistent);const r=s.Keypair.fromPublicKey(e).xdrAccountId();return n.isNative()?s.xdr.LedgerKey.account(new s.xdr.LedgerKeyAccount({accountId:r})):n.getIssuer()===e?null:s.xdr.LedgerKey.trustline(new s.xdr.LedgerKeyTrustLine({accountId:r,asset:n.toTrustLineXDRObject()}))}function p(e,t,n){return b(t,s.xdr.ScVal.scvVec([s.xdr.ScVal.scvSymbol("Allowance"),s.xdr.ScVal.scvMap([new s.xdr.ScMapEntry({key:s.xdr.ScVal.scvSymbol("from"),val:s.Address.fromString(e).toScVal()}),new s.xdr.ScMapEntry({key:s.xdr.ScVal.scvSymbol("spender"),val:s.Address.fromString(n).toScVal()})])]),s.xdr.ContractDataDurability.temporary)}function g(e){const[t,n,r]=(0,s.scValToNative)(e);return{owner:t,selling:n,buying:r}}function S(e){if("scvContractInstance"!==e.type||"contractExecutableStellarAsset"!==e.instance.executable.type)return null;const t=(e.instance.storage??[]).find(({key:e})=>"AssetInfo"===(0,s.scValToNative)(e)?.[0]);if(!t)return null;const[n,r]=(0,s.scValToNative)(t.val);if("Native"===n)return s.Asset.native();const o=r.asset_code.replace(/\0+$/,"");return new s.Asset(o,s.StrKey.encodeEd25519PublicKey(r.issuer))}function b(e,t,n){return s.xdr.LedgerKey.contractData(new s.xdr.LedgerKeyContractData({contract:s.Address.fromString(e).toScAddress(),key:t,durability:n}))}function R(e){const t=e.simulation;return!(!t||t.error||t.restorePreamble||!e.built)}async function m(e,t){const n=new Map;for(let r=0;r<t.length;r+=200){const{entries:o}=await e.getLedgerEntries(...t.slice(r,r+200));for(const e of o)n.set(e.key.toXDR("base64"),e.val)}return n}function x(e,t){return[...new Set(e)].filter(e=>!t.has(e))}function v(e,t,n){for(const r of t){const t=e.get(f(r).toXDR("base64"));n.set(r,t?S(t.contractData.val):null)}}function E(e,t){const n=e.getReadOnly(),r=e.getReadWrite(),o=new Map(n.map((e,t)=>[e.toXDR("base64"),t])),s=new Set(r.map(e=>e.toXDR("base64"))),a=new Set,c=[];for(const e of t){const t=e.toXDR("base64");if(s.has(t))continue;const i=o.has(t),l=n.length-a.size+r.length;r.length>=200||!i&&l>=400||(i&&a.add(o.get(t)),r.push(e),s.add(t),c.push(e))}return c.length&&e.setFootprint(n.filter((e,t)=>!a.has(t)),r),c}function w(e,t,{instructions:n,diskReadBytes:r=0,writeBytes:o,fee:a}){const c=t.build().resources;t.setResources(Math.min(c.instructions+n,4e8),c.diskReadBytes+r,c.writeBytes+o),t.setResourceFee((t.build().resourceFee+a).toString()),delete e.simulationTransactionData;const i=e.options?.timeoutInSeconds??300;e.built=s.TransactionBuilder.cloneFrom(e.built,{sorobanData:t.build(),timebounds:void 0}).setTimeout(i).build()}const D={allowanceLedgerKey:p,balanceLedgerKey:y,collectOrderIds:u,completeFootprint:async function(e,t,n,{server:r,tokens:o=[],assetCache:s=new Map}){if(!R(e)||!n?.length)return{orders:0,makerEntries:0};const S=u(n).map(e=>d(t,e)),b=x(o,s),D=await m(r,[...S,...b.map(f)]);v(D,b,s);const h=S.map(e=>D.get(e.toXDR("base64"))).filter(Boolean).map(e=>g(e.contractData.val)),I=x(h.flatMap(({selling:e,buying:t})=>[e,t]),s);I.length&&v(await m(r,I.map(f)),I,s);const K=new Map,V=[];for(const{owner:e,selling:n,buying:r}of h){const o=s.get(n),a=[y(e,n,o),o?p(e,n,t):null,y(e,r,s.get(r))];for(const t of a)t&&(K.set(t.toXDR("base64"),e),V.push(t))}const A=e.simulation.transactionData,O=new Set(A.getReadOnly().map(e=>e.toXDR("base64"))),k=E(A,[...S,...V]);if(!k.length)return{orders:0,makerEntries:0};const B=new Set;let T=0,C=0;for(const e of k){const t=e.toXDR("base64"),n=K.get(t);void 0!==n&&(T++,B.add(n),l.has(e.type)&&!O.has(t)&&C++)}const L=k.length-T;return w(e,A,{instructions:L*a+B.size*i,diskReadBytes:256*C,writeBytes:320*L+256*T,fee:BigInt(L)*c+20000n*BigInt(T)+20000n*BigInt(B.size)}),{orders:L,makerEntries:T}},decodeSacAsset:S,decodeStoredOrder:g,ensureOrdersFootprint:function(e,t,n){if(!R(e)||!n?.length)return 0;const r=e.simulation.transactionData,o=E(r,u(n).map(e=>d(t,e))).length;return 0===o?0:(w(e,r,{instructions:o*a,writeBytes:320*o,fee:BigInt(o)*c}),o)},instanceLedgerKey:f,orderLedgerKey:d,MAKER_ENTRY_RESOURCE_FEE:20000n,MAKER_ENTRY_SIZE:256,MAKER_INSTRUCTIONS:i,MAKER_RESOURCE_FEE:20000n,ORDER_ENTRY_SIZE:320,ORDER_INSTRUCTIONS:a,ORDER_RESOURCE_FEE:c};return o.default})());
|
|
2
|
+
//# sourceMappingURL=footprint.cjs.map
|
|
@@ -0,0 +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,CAGAT,QAAA,IAOA,OAHAY,EAAAH,GAAAR,EAAAA,EAAAD,QAAAQ,GAGAP,EAAAD,OACA,CCrBAQ,EAAAK,EAAA,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K,KAAO8H,EAAO,CACrB,MAAMC,EAAU/H,EAAI8G,MAAM,UACpB4D,EAAQN,EAAQ/J,IAAI0H,QACZnI,IAAV8K,IAEJZ,IACAU,EAAO9I,IAAIgJ,GACP5J,EAAiBW,IAAIzB,EAAIkC,QAAUoF,EAAS7F,IAAIsG,IAChD0C,IAER,CACA,MAAME,EAAe7C,EAAMrB,OAASqD,EAOpC,OANAzB,EAAevC,EAAIuB,EAAM,CACrBiB,aAAcqC,EAAehK,EAAqB6J,EAAOtC,KAAOrH,EAChE0H,cAxPwB,IAwPTkC,EACfjC,WA5QwB,IA4QZmC,EAzPY,IAyPsBb,EAC9CrB,IAAKlH,OAAOoJ,GAAgB/J,EApPI,OAoPiBW,OAAOuI,GAvO9B,OAuOyEvI,OAAOiJ,EAAOtC,QAE9G,CAAC2B,OAAQc,EAAcb,eAClC,EChQIpF,eAAcA,EACdJ,kBAAiBA,EACjBsG,sBDqKG,SAA+B9E,EAAIjE,EAAY+H,GAClD,IAAK/D,EAAYC,KAAQ8D,GAAUnD,OAC/B,OAAO,EACX,MAAMY,EAAOvB,EAAGC,WAAWwE,gBACrBzC,EAAQV,EAAiBC,EAAMrG,EAAgB4I,GAAUjC,IAAItG,GAAMO,EAAeC,EAAYR,KAAMoF,OAC1G,OAAc,IAAVqB,EACO,GACXO,EAAevC,EAAIuB,EAAM,CACrBiB,aAAcR,EAAQnH,EACtB6H,WAhMwB,IAgMZV,EACZW,IAAKlH,OAAOuG,GAASlH,IAElBkH,EACX,ECjLIxF,kBAAiBA,EACjBV,eAAcA,EACdiJ,yBDIoC,OCHpCC,iBDH4B,ICI5BjK,mBAAkBA,EAClBkK,mBDc8B,OCb9BC,iBDzB4B,IC0B5BrK,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'\n\n/**\n * Upper bound of a serialized `Order` ledger entry in bytes.\n * (positional vector of three addresses, i128 amount and price, optional u64 expires = at most 188-byte value,\n * about 264-byte ledger entry, rounded up to 320).\n * @type {number}\n */\nexport const ORDER_ENTRY_SIZE = 320\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 * Upper bound of a maker balance (account, trustline or token balance) or allowance ledger entry in bytes.\n * @type {number}\n */\nexport const MAKER_ENTRY_SIZE = 256\n\n/**\n * Resource fee (stroops) added for every maker entry declared read-write (write entry ~10k, its bytes charged as written ~6k).\n * @type {bigint}\n */\nexport const MAKER_ENTRY_RESOURCE_FEE = 20_000n\n\n/**\n * CPU instructions added for every maker whose entries were declared (two token transfers, backing and receive checks).\n * @type {number}\n */\nexport const MAKER_INSTRUCTIONS = 3_000_000\n\n/**\n * Resource fee (stroops) added for every maker whose entries were declared (instructions ~8k, two transfer events and\n * a `skip` event ~4k, rounded up).\n * @type {bigint}\n */\nexport const MAKER_RESOURCE_FEE = 20_000n\n\n/**\n * Ledger entry types read from disk when a transaction is applied: every declared one counts towards the disk read\n * bytes, whether the execution touches it or not.\n * @type {Set<string>}\n */\nconst DISK_ENTRY_TYPES = new Set(['account', 'trustline'])\n\n/**\n * Network-wide per-transaction instructions limit.\n * @type {number}\n */\nconst MAX_TX_INSTRUCTIONS = 400_000_000\n\n/**\n * Network-wide per-transaction limits of read-write and total footprint entries.\n */\nconst MAX_READ_WRITE_ENTRIES = 200\nconst MAX_FOOTPRINT_ENTRIES = 400\n\n/**\n * Keys per `getLedgerEntries` request accepted by RPC.\n */\nconst LEDGER_ENTRIES_BATCH = 200\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 (the key is the raw u128 order id).\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 contractDataKey(contractId, nativeToScVal(BigInt(orderId), {type: 'u128'}), xdr.ContractDataDurability.persistent)\n}\n\n/**\n * Build the ledger key of a contract instance entry.\n * @param {string} contractId - Contract address\n * @return {xdr.LedgerKey}\n */\nexport function instanceLedgerKey(contractId) {\n return contractDataKey(contractId, xdr.ScVal.scvLedgerKeyContractInstance(), xdr.ContractDataDurability.persistent)\n}\n\n/**\n * Build the ledger key holding the balance of `owner` in a Stellar Asset Contract token.\n * @param {string} owner - Account or contract address\n * @param {string} token - Token contract address\n * @param {Asset|null} asset - Classic asset behind the token, `null` for a token that is not a Stellar Asset Contract\n * @return {xdr.LedgerKey|null} - `null` when the balance has no ledger entry of its own (issuer) or the token storage layout is unknown\n */\nexport function balanceLedgerKey(owner, token, asset) {\n if (!asset)\n return null\n if (StrKey.isValidContract(owner))\n return contractDataKey(token, xdr.ScVal.scvVec([xdr.ScVal.scvSymbol('Balance'), Address.fromString(owner).toScVal()]), xdr.ContractDataDurability.persistent)\n const accountId = Keypair.fromPublicKey(owner).xdrAccountId()\n if (asset.isNative())\n return xdr.LedgerKey.account(new xdr.LedgerKeyAccount({accountId}))\n //the issuer holds no trustline for its own asset\n if (asset.getIssuer() === owner)\n return null\n return xdr.LedgerKey.trustline(new xdr.LedgerKeyTrustLine({accountId, asset: asset.toTrustLineXDRObject()}))\n}\n\n/**\n * Build the ledger key of the allowance `owner` granted to `spender` in a Stellar Asset Contract token.\n * @param {string} owner - Account or contract address granting the allowance\n * @param {string} token - Token contract address\n * @param {string} spender - Spender address (the DEX contract)\n * @return {xdr.LedgerKey}\n */\nexport function allowanceLedgerKey(owner, token, spender) {\n const key = xdr.ScVal.scvVec([\n xdr.ScVal.scvSymbol('Allowance'),\n xdr.ScVal.scvMap([\n new xdr.ScMapEntry({key: xdr.ScVal.scvSymbol('from'), val: Address.fromString(owner).toScVal()}),\n new xdr.ScMapEntry({key: xdr.ScVal.scvSymbol('spender'), val: Address.fromString(spender).toScVal()})\n ])\n ])\n return contractDataKey(token, key, xdr.ContractDataDurability.temporary)\n}\n\n/**\n * Decode a stored order entry value: a positional vector `[owner, selling, buying, amount, price, expires?]`.\n * @param {xdr.ScVal} val - Contract data value of the order entry\n * @return {{owner: string, selling: string, buying: string}}\n */\nexport function decodeStoredOrder(val) {\n const [owner, selling, buying] = scValToNative(val)\n return {owner, selling, buying}\n}\n\n/**\n * Resolve the classic asset behind a token from its contract instance entry.\n * @param {xdr.ScVal} val - Contract data value of the token instance entry\n * @return {Asset|null} - `null` for a token that is not a Stellar Asset Contract\n */\nexport function decodeSacAsset(val) {\n if (val.type !== 'scvContractInstance' || val.instance.executable.type !== 'contractExecutableStellarAsset')\n return null\n const entry = (val.instance.storage ?? []).find(({key}) => scValToNative(key)?.[0] === 'AssetInfo')\n if (!entry)\n return null\n const [type, info] = scValToNative(entry.val)\n if (type === 'Native')\n return Asset.native()\n //alphanum codes are padded with zero bytes\n const code = info.asset_code.replace(/\\0+$/, '')\n return new Asset(code, StrKey.encodeEd25519PublicKey(info.issuer))\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 if (!isPatchable(tx) || !orderIds?.length)\n return 0\n const data = tx.simulation.transactionData\n const added = declareReadWrite(data, collectOrderIds(orderIds).map(id => orderLedgerKey(contractId, id))).length\n if (added === 0)\n return 0\n applyResources(tx, data, {\n instructions: added * ORDER_INSTRUCTIONS,\n writeBytes: added * ORDER_ENTRY_SIZE,\n fee: BigInt(added) * ORDER_RESOURCE_FEE\n })\n return added\n}\n\n/**\n * Complete the footprint of a simulated trading transaction, so it still applies when the book moves between simulation\n * and execution (an order repriced back into range, a maker's backing restored, an earlier order shrunk). Every listed\n * order entry is declared read-write, and so is every entry the settlement may write for the order's maker: the balance\n * of the asset the maker sells, the allowance on it granted to the DEX contract, and the balance of the asset the maker\n * receives. Makers of tokens that are not Stellar Asset Contracts keep what the simulation recorded (their storage layout\n * is unknown). Entries are added in list order, orders first, while the footprint limits allow.\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 * @param {FootprintOptions} options\n * @return {Promise<{orders: number, makerEntries: number}>} - Number of order and maker entries added to the read-write footprint\n */\nexport async function completeFootprint(tx, contractId, orderIds, {server, tokens = [], assetCache = new Map()}) {\n if (!isPatchable(tx) || !orderIds?.length)\n return {orders: 0, makerEntries: 0}\n const orderKeys = collectOrderIds(orderIds).map(id => orderLedgerKey(contractId, id))\n //one request for the orders and the known tokens, another one only for tokens first seen in the orders\n const knownTokens = unresolved(tokens, assetCache)\n const entries = await loadEntries(server, [...orderKeys, ...knownTokens.map(instanceLedgerKey)])\n cacheAssets(entries, knownTokens, assetCache)\n const orders = orderKeys\n .map(key => entries.get(key.toXDR('base64')))\n .filter(Boolean)\n .map(entry => decodeStoredOrder(entry.contractData.val))\n const newTokens = unresolved(orders.flatMap(({selling, buying}) => [selling, buying]), assetCache)\n if (newTokens.length) {\n cacheAssets(await loadEntries(server, newTokens.map(instanceLedgerKey)), newTokens, assetCache)\n }\n //entries the settlement writes for each maker, tagged with the maker\n const makerOf = new Map()\n const makerKeys = []\n for (const {owner, selling, buying} of orders) {\n const sold = assetCache.get(selling)\n const keys = [\n balanceLedgerKey(owner, selling, sold),\n sold ? allowanceLedgerKey(owner, selling, contractId) : null,\n balanceLedgerKey(owner, buying, assetCache.get(buying))\n ]\n for (const key of keys) {\n if (!key)\n continue\n makerOf.set(key.toXDR('base64'), owner)\n makerKeys.push(key)\n }\n }\n const data = tx.simulation.transactionData\n //entries promoted from the read-only part are already counted as disk reads by the simulation\n const readOnly = new Set(data.getReadOnly().map(key => key.toXDR('base64')))\n const added = declareReadWrite(data, [...orderKeys, ...makerKeys])\n if (!added.length)\n return {orders: 0, makerEntries: 0}\n const makers = new Set()\n let makerEntries = 0\n let diskEntries = 0\n for (const key of added) {\n const encoded = key.toXDR('base64')\n const maker = makerOf.get(encoded)\n if (maker === undefined)\n continue\n makerEntries++\n makers.add(maker)\n if (DISK_ENTRY_TYPES.has(key.type) && !readOnly.has(encoded)) {\n diskEntries++\n }\n }\n const orderEntries = added.length - makerEntries\n applyResources(tx, data, {\n instructions: orderEntries * ORDER_INSTRUCTIONS + makers.size * MAKER_INSTRUCTIONS,\n diskReadBytes: diskEntries * MAKER_ENTRY_SIZE,\n writeBytes: orderEntries * ORDER_ENTRY_SIZE + makerEntries * MAKER_ENTRY_SIZE,\n fee: BigInt(orderEntries) * ORDER_RESOURCE_FEE + BigInt(makerEntries) * MAKER_ENTRY_RESOURCE_FEE + BigInt(makers.size) * MAKER_RESOURCE_FEE\n })\n return {orders: orderEntries, makerEntries}\n}\n\n/**\n * @param {string} contractId\n * @param {xdr.ScVal} key\n * @param {xdr.ContractDataDurability} durability\n * @return {xdr.LedgerKey}\n * @private\n */\nfunction contractDataKey(contractId, key, durability) {\n return xdr.LedgerKey.contractData(new xdr.LedgerKeyContractData({\n contract: Address.fromString(contractId).toScAddress(),\n key,\n durability\n }))\n}\n\n/**\n * Whether the simulation succeeded and can be patched\n * @param {contract.AssembledTransaction} tx\n * @return {boolean}\n * @private\n */\nfunction isPatchable(tx) {\n const simulation = tx.simulation\n return !!simulation && !simulation.error && !simulation.restorePreamble && !!tx.built\n}\n\n/**\n * Fetch ledger entries, keyed by the base64 XDR of their ledger keys\n * @param {rpc.Server} server\n * @param {xdr.LedgerKey[]} keys\n * @return {Promise<Map<string, xdr.LedgerEntryData>>}\n * @private\n */\nasync function loadEntries(server, keys) {\n const res = new Map()\n for (let i = 0; i < keys.length; i += LEDGER_ENTRIES_BATCH) {\n const {entries} = await server.getLedgerEntries(...keys.slice(i, i + LEDGER_ENTRIES_BATCH))\n for (const entry of entries) {\n res.set(entry.key.toXDR('base64'), entry.val)\n }\n }\n return res\n}\n\n/**\n * Tokens from the list not resolved yet, deduplicated\n * @param {string[]} tokens\n * @param {Map<string, Asset|null>} assetCache\n * @return {string[]}\n * @private\n */\nfunction unresolved(tokens, assetCache) {\n return [...new Set(tokens)].filter(token => !assetCache.has(token))\n}\n\n/**\n * Store the classic asset of every token from the loaded instance entries (`null` when unknown)\n * @param {Map<string, xdr.LedgerEntryData>} entries\n * @param {string[]} tokens\n * @param {Map<string, Asset|null>} assetCache\n * @private\n */\nfunction cacheAssets(entries, tokens, assetCache) {\n for (const token of tokens) {\n const entry = entries.get(instanceLedgerKey(token).toXDR('base64'))\n assetCache.set(token, entry ? decodeSacAsset(entry.contractData.val) : null)\n }\n}\n\n/**\n * Add keys to the read-write part of a simulated footprint, dropping them from the read-only part, while the\n * footprint limits allow\n * @param {SorobanDataBuilder} data - Simulation data to patch\n * @param {xdr.LedgerKey[]} keys - Keys to declare, in priority order\n * @return {xdr.LedgerKey[]} - Keys actually added\n * @private\n */\nfunction declareReadWrite(data, keys) {\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 const added = []\n for (const key of keys) {\n const encoded = key.toXDR('base64')\n if (rwIndex.has(encoded))\n continue\n //a key promoted from the read-only part does not grow the footprint\n const promoted = roIndex.has(encoded)\n const total = readOnly.length - dropFromReadOnly.size + readWrite.length\n if (readWrite.length >= MAX_READ_WRITE_ENTRIES || (!promoted && total >= MAX_FOOTPRINT_ENTRIES))\n continue\n //a key can't be listed in both parts of the footprint\n if (promoted) {\n dropFromReadOnly.add(roIndex.get(encoded))\n }\n readWrite.push(key)\n rwIndex.add(encoded)\n added.push(key)\n }\n if (added.length) {\n data.setFootprint(readOnly.filter((_, i) => !dropFromReadOnly.has(i)), readWrite)\n }\n return added\n}\n\n/**\n * Declare the resources of the added entries and rebuild the transaction from the patched simulation data\n * @param {contract.AssembledTransaction} tx - Simulated transaction\n * @param {SorobanDataBuilder} data - Patched simulation data\n * @param {{instructions: number, diskReadBytes?: number, writeBytes: number, fee: bigint}} extra - Resources and fee to add\n * @private\n */\nfunction applyResources(tx, data, {instructions, diskReadBytes = 0, writeBytes, fee}) {\n const resources = data.build().resources\n data.setResources(Math.min(resources.instructions + instructions, MAX_TX_INSTRUCTIONS), resources.diskReadBytes + diskReadBytes, resources.writeBytes + writeBytes)\n data.setResourceFee((data.build().resourceFee + fee).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}\n\n/**\n * @typedef {{}} FootprintOptions\n * @property {rpc.Server} server - RPC server used to load the listed orders and the token instances\n * @property {string[]} [tokens] - Tokens the call trades, resolved together with the orders\n * @property {Map<string, Asset|null>} [assetCache] - Classic assets of resolved tokens (`null` for other tokens), reused between calls\n */\n","import {\n allowanceLedgerKey,\n balanceLedgerKey,\n collectOrderIds,\n completeFootprint,\n decodeSacAsset,\n decodeStoredOrder,\n ensureOrdersFootprint,\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 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","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","orders","makerEntries","orderKeys","knownTokens","Boolean","newTokens","flatMap","makerOf","makerKeys","sold","transactionData","makers","diskEntries","maker","orderEntries","ensureOrdersFootprint","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.
|
|
3
|
+
"version": "0.7.0",
|
|
4
4
|
"description": "AXIS contract and API client",
|
|
5
5
|
"author": "team@stellar.expert",
|
|
6
6
|
"license": "MIT",
|
|
@@ -14,6 +14,11 @@
|
|
|
14
14
|
"import": "./src/index.js",
|
|
15
15
|
"require": "./lib/axis-client.cjs"
|
|
16
16
|
},
|
|
17
|
+
"./footprint": {
|
|
18
|
+
"types": "./src/footprint.d.ts",
|
|
19
|
+
"import": "./src/footprint.js",
|
|
20
|
+
"require": "./lib/footprint.cjs"
|
|
21
|
+
},
|
|
17
22
|
"./package.json": "./package.json"
|
|
18
23
|
},
|
|
19
24
|
"homepage": "https://axis.markets",
|
|
@@ -23,10 +28,11 @@
|
|
|
23
28
|
},
|
|
24
29
|
"bugs": "https://github.com/axis-markets/js-client/issues",
|
|
25
30
|
"scripts": {
|
|
31
|
+
"test": "node --experimental-vm-modules node_modules/jest/bin/jest.js",
|
|
26
32
|
"prepare": "webpack --mode=production --config webpack.config.cjs"
|
|
27
33
|
},
|
|
28
34
|
"peerDependencies": {
|
|
29
|
-
"@stellar/stellar-sdk": ">=
|
|
35
|
+
"@stellar/stellar-sdk": ">=17"
|
|
30
36
|
},
|
|
31
37
|
"engines": {
|
|
32
38
|
"node": ">=22"
|
|
@@ -43,6 +49,7 @@
|
|
|
43
49
|
"files": [
|
|
44
50
|
"src/",
|
|
45
51
|
"lib/",
|
|
46
|
-
"!src/cjs.js"
|
|
52
|
+
"!src/cjs.js",
|
|
53
|
+
"!src/footprint-cjs.js"
|
|
47
54
|
]
|
|
48
55
|
}
|
package/src/allowance.js
ADDED
|
@@ -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
|
+
*/
|
package/src/api-client.js
CHANGED
|
@@ -73,12 +73,13 @@ export class AxisApiClient {
|
|
|
73
73
|
}
|
|
74
74
|
|
|
75
75
|
/**
|
|
76
|
-
* Order book depth aggregated into price
|
|
76
|
+
* Order book depth around the mid price, aggregated into price levels on multiples of `step` (bids rounded down,
|
|
77
|
+
* asks up, so a level price crosses every order in it)
|
|
77
78
|
* @param {DepthParams} params - Depth request parameters
|
|
78
79
|
* @return {Promise<OrderbookDepth>} - Aggregated bids and asks
|
|
79
80
|
*/
|
|
80
|
-
async getDepth({market, depth}) {
|
|
81
|
-
return this.request('/depth', {market, depth})
|
|
81
|
+
async getDepth({market, depth, step, limit}) {
|
|
82
|
+
return this.request('/depth', {market, depth, step, limit})
|
|
82
83
|
}
|
|
83
84
|
|
|
84
85
|
/**
|
|
@@ -107,6 +108,14 @@ export class AxisApiClient {
|
|
|
107
108
|
return this.request('/markets', {cursor, limit})
|
|
108
109
|
}
|
|
109
110
|
|
|
111
|
+
/**
|
|
112
|
+
* Contract state tracked by the indexer: frozen switch, configuration and active markets
|
|
113
|
+
* @return {Promise<ContractInfo>} - Contract state
|
|
114
|
+
*/
|
|
115
|
+
async getContract() {
|
|
116
|
+
return this.request('/contract')
|
|
117
|
+
}
|
|
118
|
+
|
|
110
119
|
/**
|
|
111
120
|
* Retrieve active orders, filterable by owner or asset
|
|
112
121
|
* @param {OrdersParams} [params] - Filter parameters
|
|
@@ -116,10 +125,20 @@ export class AxisApiClient {
|
|
|
116
125
|
return this.request('/order', {owner, asset, cursor, limit})
|
|
117
126
|
}
|
|
118
127
|
|
|
128
|
+
/**
|
|
129
|
+
* Account state tracked by the indexer: every live order of the trader (not paginated) and their backing in each
|
|
130
|
+
* asset they trade
|
|
131
|
+
* @param {string} address - Trader address
|
|
132
|
+
* @return {Promise<ApiAccount>}
|
|
133
|
+
*/
|
|
134
|
+
async getAccount(address) {
|
|
135
|
+
return this.request(`/account/${encodeURIComponent(address)}`)
|
|
136
|
+
}
|
|
137
|
+
|
|
119
138
|
/**
|
|
120
139
|
* Retrieve a single order by ID
|
|
121
140
|
* @param {bigint|string|number} id - Order ID
|
|
122
|
-
* @return {Promise<ApiOrder
|
|
141
|
+
* @return {Promise<ApiOrder>} - Order (throws AxisApiError with status 404 if not found)
|
|
123
142
|
*/
|
|
124
143
|
async getOrder(id) {
|
|
125
144
|
return this.request(`/order/${encodeURIComponent(id.toString())}`)
|
|
@@ -215,18 +234,26 @@ export class AxisApiClient {
|
|
|
215
234
|
* @property {string} selling - Selling asset contract id at this hop
|
|
216
235
|
* @property {string} buying - Buying asset contract id at this hop
|
|
217
236
|
* @property {string[]} orders - Maker order IDs matched at this hop
|
|
237
|
+
* @property {string} [worstPrice] - Highest price among the matched orders (maker `buying` per `selling`, 18 decimals):
|
|
238
|
+
* a trade limit at this price crosses every listed order
|
|
218
239
|
*/
|
|
219
240
|
|
|
220
241
|
/**
|
|
221
242
|
* @typedef {{}} DepthParams
|
|
222
243
|
* @property {string} market - Market identifier `BASE/QUOTE`
|
|
223
244
|
* @property {number} [depth] - Percentage band (±) around the center price (0 < depth ≤ 100, default 20)
|
|
245
|
+
* @property {string} [step] - Price step of the levels, a decimal such as `"0.0005"` (5 significant digits of the mid
|
|
246
|
+
* price by default)
|
|
247
|
+
* @property {number} [limit] - Price levels per side (default 100, max 500)
|
|
224
248
|
*/
|
|
225
249
|
|
|
226
250
|
/**
|
|
227
251
|
* @typedef {{}} OrderbookDepth
|
|
228
252
|
* @property {number} ledger - Ledger sequence
|
|
229
253
|
* @property {number} timestamp - UNIX timestamp (seconds)
|
|
254
|
+
* @property {string|null} step - Price step of the levels (null for an empty book)
|
|
255
|
+
* @property {string|null} bestBid - Exact best bid price, before the rounding to levels
|
|
256
|
+
* @property {string|null} bestAsk - Exact best ask price, before the rounding to levels
|
|
230
257
|
* @property {Array<[string, string]>} bids - `[price, quantity]` pairs sorted descending by price
|
|
231
258
|
* @property {Array<[string, string]>} asks - `[price, quantity]` pairs sorted ascending by price
|
|
232
259
|
*/
|
|
@@ -280,10 +307,33 @@ export class AxisApiClient {
|
|
|
280
307
|
* @property {string[]} orderTypes - Supported order types
|
|
281
308
|
*/
|
|
282
309
|
|
|
310
|
+
/**
|
|
311
|
+
* @typedef {{}} ContractInfo - Contract state tracked by the indexer
|
|
312
|
+
* @property {boolean} frozen - Whether trading is blocked by the safety admin
|
|
313
|
+
* @property {ContractInfoConfig} [config] - Contract configuration
|
|
314
|
+
* @property {ContractInfoMarket[]} markets - Markets opened by `subsidize`
|
|
315
|
+
*/
|
|
316
|
+
|
|
317
|
+
/**
|
|
318
|
+
* @typedef {{}} ContractInfoConfig
|
|
319
|
+
* @property {string} safetyAdmin - Safety admin address
|
|
320
|
+
* @property {string} oracle - Price oracle contract address
|
|
321
|
+
* @property {string} marketListingFee - Fee token amount burned to open a market
|
|
322
|
+
* @property {string} minTradeSize - Minimum trade value in USD with 7 decimals (0 = disabled)
|
|
323
|
+
*/
|
|
324
|
+
|
|
325
|
+
/**
|
|
326
|
+
* @typedef {{}} ContractInfoMarket
|
|
327
|
+
* @property {string} a - First market asset
|
|
328
|
+
* @property {string} b - Second market asset
|
|
329
|
+
* @property {string} created - Creation timestamp (UTC)
|
|
330
|
+
* @property {string} refreshed - Last oracle check timestamp (UTC)
|
|
331
|
+
*/
|
|
332
|
+
|
|
283
333
|
/**
|
|
284
334
|
* @typedef {{}} OrdersParams
|
|
285
335
|
* @property {string} [owner] - Filter by order owner address
|
|
286
|
-
* @property {string|string[]} [asset] - Filter by asset(s) -
|
|
336
|
+
* @property {string|string[]} [asset] - Filter by asset(s) - every listed asset must be one of the order assets (two assets select a pair)
|
|
287
337
|
* @property {string|bigint} [cursor] - Pagination cursor (order id)
|
|
288
338
|
* @property {number|string} [limit] - Max orders to return
|
|
289
339
|
*/
|
|
@@ -306,26 +356,58 @@ export class AxisApiClient {
|
|
|
306
356
|
|
|
307
357
|
/**
|
|
308
358
|
* @typedef {{}} ApiOrder - Serialized order returned by the API
|
|
309
|
-
* @property {string} id - Order ID
|
|
310
|
-
* @property {
|
|
311
|
-
* @property {string} kind - Order kind (`LIMIT`)
|
|
359
|
+
* @property {string} id - Order ID (decimal u128)
|
|
360
|
+
* @property {'ACTIVE'|'FILLED'|'CANCELED'|'EXPIRED'} status - Order status: `ACTIVE`, `FILLED`, `CANCELED` (removed by the owner) or `EXPIRED` (archived once past `expires`)
|
|
312
361
|
* @property {string} buying - Buying asset contract id
|
|
313
362
|
* @property {string} selling - Selling asset contract id
|
|
314
363
|
* @property {string} price - Order price
|
|
315
364
|
* @property {string} rprice - Rational price representation
|
|
316
|
-
* @property {string} quote -
|
|
317
|
-
* @property {string} amount - Amount left to sell
|
|
365
|
+
* @property {string} quote - Selling amount at creation
|
|
366
|
+
* @property {string} amount - Amount left to sell
|
|
367
|
+
* @property {string} [backed] - Amount the maker can actually deliver, when the indexer tracks backing
|
|
368
|
+
* @property {ApiOrderBacking} [backing] - Maker backing details, when the indexer tracks backing
|
|
318
369
|
* @property {string} owner - Maker address
|
|
319
370
|
* @property {string} [expires] - Expiration timestamp (UTC)
|
|
320
|
-
* @property {string} [iceberg] - Iceberg amount
|
|
321
|
-
* @property {string} [stop] - Stop price
|
|
322
371
|
* @property {string} [created] - Creation timestamp (UTC)
|
|
323
372
|
* @property {string} [updated] - Last update timestamp (UTC)
|
|
324
373
|
* @property {string} [cursor] - Pagination cursor
|
|
325
374
|
*/
|
|
326
375
|
|
|
376
|
+
/**
|
|
377
|
+
* @typedef {{}} ApiOrderBacking - Maker backing in the order's selling asset
|
|
378
|
+
* @property {string} balance - Token balance
|
|
379
|
+
* @property {string} allowance - Allowance granted to the AXIS contract
|
|
380
|
+
* @property {number} liveUntil - Ledger sequence the allowance lives until
|
|
381
|
+
* @property {boolean} authorized - Whether the maker can send and receive the token
|
|
382
|
+
* @property {string} [updated] - Last load timestamp (UTC)
|
|
383
|
+
* @property {boolean} [pending] - A reload confirming the latest event is still due: the values may predate it
|
|
384
|
+
*/
|
|
385
|
+
|
|
386
|
+
/**
|
|
387
|
+
* @typedef {{}} ApiBacking - Tracked backing of an account in a token
|
|
388
|
+
* @property {string} owner - Account address
|
|
389
|
+
* @property {string} asset - Token contract id
|
|
390
|
+
* @property {string} balance - Token balance
|
|
391
|
+
* @property {string} allowance - Allowance granted to the AXIS contract
|
|
392
|
+
* @property {number} liveUntil - Ledger sequence the allowance lives until
|
|
393
|
+
* @property {boolean} authorized - Whether the account can send and receive the token
|
|
394
|
+
* @property {string} budget - Effective budget, min(balance, allowance), 0 when unauthorized or expired
|
|
395
|
+
* @property {string} [updated] - Last load timestamp (UTC)
|
|
396
|
+
* @property {string} [skipped] - Last `skip` event of an order selling the token (UTC)
|
|
397
|
+
* @property {boolean} [pending] - A reload confirming the latest event is still due
|
|
398
|
+
*/
|
|
399
|
+
|
|
400
|
+
/**
|
|
401
|
+
* @typedef {{}} ApiAccount - Account state: every live order and the backing per traded asset
|
|
402
|
+
* @property {string} address - Trader address
|
|
403
|
+
* @property {number} ledger - Last processed ledger
|
|
404
|
+
* @property {ApiOrder[]} orders - Live orders, oldest first
|
|
405
|
+
* @property {Object<string, ApiBacking>} backing - Backing by token contract id
|
|
406
|
+
*/
|
|
407
|
+
|
|
327
408
|
/**
|
|
328
409
|
* @typedef {{}} ApiTrade - Serialized trade returned by the API
|
|
410
|
+
* @property {'trade'} type - Record type
|
|
329
411
|
* @property {string} id - Trade ID
|
|
330
412
|
* @property {string} order - Matched order ID
|
|
331
413
|
* @property {string} taker - Taker account address
|
|
@@ -334,6 +416,7 @@ export class AxisApiClient {
|
|
|
334
416
|
* @property {string} boughtAsset - Bought asset contract id
|
|
335
417
|
* @property {string} sold - Sold tokens amount
|
|
336
418
|
* @property {string} bought - Bought tokens amount
|
|
419
|
+
* @property {string} [left] - Order amount left after the fill
|
|
337
420
|
* @property {string} price - Approximate trade price
|
|
338
421
|
* @property {string} [cursor] - Pagination cursor
|
|
339
422
|
* @property {string} timestamp - Trade timestamp (UTC)
|
package/src/api-dates.js
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Parse an Aggregator API timestamp (`YYYY-MM-DD HH:mm:ss` UTC)
|
|
3
|
+
* @param {string|number|undefined} value
|
|
4
|
+
* @return {number} - UNIX milliseconds, 0 when missing or invalid
|
|
5
|
+
*/
|
|
6
|
+
export function parseApiDate(value) {
|
|
7
|
+
if (value === undefined || value === null || value === '')
|
|
8
|
+
return 0
|
|
9
|
+
if (typeof value === 'number')
|
|
10
|
+
return value
|
|
11
|
+
let text = String(value).trim().replace(' ', 'T')
|
|
12
|
+
if (!/[zZ]|[+-]\d\d:?\d\d$/.test(text)) {
|
|
13
|
+
text += 'Z'
|
|
14
|
+
}
|
|
15
|
+
const ms = Date.parse(text)
|
|
16
|
+
return Number.isFinite(ms) ? ms : 0
|
|
17
|
+
}
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import {Address} from '@stellar/stellar-sdk'
|
|
2
|
+
|
|
3
|
+
/** Price scale of the contract (18 decimals) */
|
|
4
|
+
export const PRICE_SCALE = 10n ** 18n
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Serialized `ScAddress` by address string
|
|
8
|
+
* @type {Map<string, Uint8Array>}
|
|
9
|
+
*/
|
|
10
|
+
const keyCache = new Map()
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* @param {string} address
|
|
14
|
+
* @return {Uint8Array}
|
|
15
|
+
*/
|
|
16
|
+
function getAddressKey(address) {
|
|
17
|
+
let key = keyCache.get(address)
|
|
18
|
+
if (!key) {
|
|
19
|
+
key = Address.fromString(address).toScAddress().toXDR()
|
|
20
|
+
if (keyCache.size >= 10_000) { //will never happen in real life
|
|
21
|
+
keyCache.clear()
|
|
22
|
+
}
|
|
23
|
+
keyCache.set(address, key)
|
|
24
|
+
}
|
|
25
|
+
return key
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Compare two assets in the contract canonical order
|
|
30
|
+
* @param {string} a - Token contract address
|
|
31
|
+
* @param {string} b - Token contract address
|
|
32
|
+
* @return {number} - Negative if `a` first, positive if `b` first, 0 if equal
|
|
33
|
+
*/
|
|
34
|
+
export function compareAssets(a, b) {
|
|
35
|
+
if (a === b)
|
|
36
|
+
return 0
|
|
37
|
+
const key1 = getAddressKey(a)
|
|
38
|
+
const key2 = getAddressKey(b)
|
|
39
|
+
const length = Math.min(key1.length, key2.length)
|
|
40
|
+
for (let i = 0; i < length; i++) {
|
|
41
|
+
if (key1[i] !== key2[i])
|
|
42
|
+
return key1[i] - key2[i]
|
|
43
|
+
}
|
|
44
|
+
return key1.length - key2.length
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Reorder an asset pair the way the contract stores markets
|
|
49
|
+
* @param {string} x - Token contract address
|
|
50
|
+
* @param {string} y - Token contract address
|
|
51
|
+
* @return {[string, string]} - `[a, b]`: `a` is the base, `b` the quote of the canonical market symbol
|
|
52
|
+
*/
|
|
53
|
+
export function canonicalPair(x, y) {
|
|
54
|
+
return compareAssets(x, y) <= 0 ? [x, y] : [y, x]
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Canonical market key `a/b`
|
|
59
|
+
* @param {string} a - Token contract address
|
|
60
|
+
* @param {string} b - Token contract address
|
|
61
|
+
* @return {string}
|
|
62
|
+
*/
|
|
63
|
+
export function pairKey(a, b) {
|
|
64
|
+
const [a1, a2] = canonicalPair(a, b)
|
|
65
|
+
return a1 + '/' + a2
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Calculate inverted price, rounded down: `floor(10^36 / price)`
|
|
70
|
+
* @param {bigint} price - Price in the contract scale
|
|
71
|
+
* @return {bigint}
|
|
72
|
+
*/
|
|
73
|
+
export function invertPrice(price) {
|
|
74
|
+
if (price <= 0n)
|
|
75
|
+
return 0n
|
|
76
|
+
return PRICE_SCALE * PRICE_SCALE / price
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* 24h ticker entry of the market seen in the inverted orientation (`b/a`)
|
|
81
|
+
* @param {TickerEntry} entry - Standard ticker entry
|
|
82
|
+
* @return {TickerEntry}
|
|
83
|
+
*/
|
|
84
|
+
export function invertTicker(entry) {
|
|
85
|
+
const [a, b] = entry.symbol.split('/')
|
|
86
|
+
const inv = value => {
|
|
87
|
+
const n = Number(value)
|
|
88
|
+
return n > 0 ? String(1 / n) : '0'
|
|
89
|
+
}
|
|
90
|
+
const open = Number(entry.openPrice)
|
|
91
|
+
const last = Number(entry.lastPrice)
|
|
92
|
+
return {
|
|
93
|
+
...entry,
|
|
94
|
+
symbol: b + '/' + a,
|
|
95
|
+
openPrice: inv(entry.openPrice),
|
|
96
|
+
highPrice: inv(entry.lowPrice),
|
|
97
|
+
lowPrice: inv(entry.highPrice),
|
|
98
|
+
lastPrice: inv(entry.lastPrice),
|
|
99
|
+
volume: entry.quoteVolume,
|
|
100
|
+
quoteVolume: entry.volume,
|
|
101
|
+
change: open > 0 && last > 0 ? Math.round((open / last - 1) * 100_000) / 1000 : 0,
|
|
102
|
+
avgPrice: inv(entry.avgPrice)
|
|
103
|
+
}
|
|
104
|
+
}
|