@oceanprotocol/lib 5.1.3 → 6.0.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/CHANGELOG.md +18 -4
- package/dist/lib.cjs +1 -1
- package/dist/lib.cjs.map +1 -1
- package/dist/lib.modern.js +1 -1
- package/dist/lib.modern.js.map +1 -1
- package/dist/lib.module.mjs +1 -1
- package/dist/lib.module.mjs.map +1 -1
- package/dist/lib.umd.js +1 -1
- package/dist/lib.umd.js.map +1 -1
- package/dist/types/@types/Compute.d.ts +5 -0
- package/dist/types/@types/Provider.d.ts +39 -0
- package/dist/types/services/Aquarius.d.ts +1 -0
- package/dist/types/services/Provider.d.ts +8 -18
- package/dist/types/utils/eciesencrypt.d.ts +8 -0
- package/package.json +3 -2
package/dist/lib.modern.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import t from"@oceanprotocol/contracts/addresses/address.json";import e from"fs";import{ethers as a,formatUnits as i,parseUnits as r,EventLog as n,toUtf8Bytes as s,keccak256 as o,hexlify as c,toUtf8String as l,getAddress as d,parseEther as u,getBytes as h,toBeHex as g}from"ethers";import*as w from"@oasisprotocol/sapphire-paratime";import p from"bignumber.js";import m from"decimal.js";import f from"@oceanprotocol/contracts/artifacts/contracts/pools/dispenser/Dispenser.sol/Dispenser.json";import y from"@oceanprotocol/contracts/artifacts/contracts/pools/fixedRate/FixedRateExchange.sol/FixedRateExchange.json";import v from"@oceanprotocol/contracts/artifacts/contracts/pools/FactoryRouter.sol/FactoryRouter.json";import k from"@oceanprotocol/contracts/artifacts/contracts/templates/ERC20Template.sol/ERC20Template.json";import T from"@oceanprotocol/contracts/artifacts/contracts/templates/ERC20TemplateEnterprise.sol/ERC20TemplateEnterprise.json";import b from"@oceanprotocol/contracts/artifacts/contracts/templates/ERC721Template.sol/ERC721Template.json";import S from"@oceanprotocol/contracts/artifacts/contracts/ERC721Factory.sol/ERC721Factory.json";import E from"@oceanprotocol/contracts/artifacts/contracts/interfaces/IERC20Template.sol/IERC20Template.json";import A from"@oceanprotocol/contracts/artifacts/contracts/templates/ERC20Template4.sol/ERC20Template4.json";import F from"@oceanprotocol/contracts/artifacts/contracts/accesslists/AccessList.sol/AccessList.json";import C from"@oceanprotocol/contracts/artifacts/contracts/accesslists/AccessListFactory.sol/AccessListFactory.json";import x from"@oceanprotocol/contracts/artifacts/contracts/escrow/Escrow.sol/Escrow.json";import D from"@oceanprotocol/contracts/artifacts/contracts/communityFee/EnterpriseFeeCollector.sol/EnterpriseFeeCollector.json";import M from"cross-fetch";import{DDOManager as O}from"@oceanprotocol/ddo-js";import N from"jsonwebtoken";import P from"crypto-js/sha256.js";import{createHash as R}from"crypto";var U,I,L;!function(t){t.URL="url",t.IPFS="ipfs",t.ARWEAVE="arweave"}(U||(U={})),function(t){t.AES="AES",t.ECIES="ECIES"}(I||(I={}));class j{constructor(){this.nodeUri=void 0,this.providerAddress=void 0,this.oceanNodeUri=void 0,this.web3Provider=void 0,this.oceanTokenAddress=void 0,this.nftFactoryAddress=void 0,this.routerFactoryAddress=void 0,this.datatokensABI=void 0,this.fixedRateExchangeAddress=void 0,this.fixedRateExchangeAddressABI=void 0,this.dispenserAddress=void 0,this.dispenserABI=void 0,this.opfCommunityFeeCollector=void 0,this.EnterpriseFeeCollector=void 0,this.sideStakingAddress=void 0,this.startBlock=void 0,this.verbose=void 0,this.authMessage=void 0,this.authTokenExpiration=void 0,this.parityUri=void 0,this.threshold=void 0,this.chainId=void 0,this.network=void 0,this.explorerUri=void 0,this.oceanTokenSymbol=void 0,this.transactionBlockTimeout=void 0,this.transactionConfirmationBlocks=void 0,this.transactionPollingTimeout=void 0,this.gasFeeMultiplier=void 0,this.sdk=void 0,this.accessListFactory=void 0,this.escrow=void 0}}function G(){return G=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var a=arguments[e];for(var i in a)({}).hasOwnProperty.call(a,i)&&(t[i]=a[i])}return t},G.apply(null,arguments)}!function(t){t[t.None=-1]="None",t[t.Error=0]="Error",t[t.Warn=1]="Warn",t[t.Log=2]="Log",t[t.Verbose=3]="Verbose"}(L||(L={}));class ${constructor(t){this.logLevel=void 0,this.logLevel=t,this.logLevel=t||L.Error}setLevel(t){this.logLevel=t}bypass(...t){this.dispatch("log",-Infinity,...t)}debug(...t){this.dispatch("debug",L.Verbose,...t)}log(...t){this.dispatch("log",L.Log,...t)}warn(...t){this.dispatch("warn",L.Warn,...t)}error(...t){this.dispatch("error",L.Error,...t)}dispatch(t,e,...a){this.logLevel>=e&&console[t](...a)}}const _=new $,z={chainId:null,network:"unknown",nodeUri:"http://127.0.0.1:8545",oceanNodeUri:"http://127.0.0.1:8001",explorerUri:null,oceanTokenAddress:null,oceanTokenSymbol:"OCEAN",fixedRateExchangeAddress:null,dispenserAddress:null,startBlock:0,transactionBlockTimeout:50,transactionConfirmationBlocks:1,transactionPollingTimeout:750,gasFeeMultiplier:1},B=[G({},z),G({},z,{chainId:8996,network:"development",oceanNodeUri:"http://127.0.0.1:8001",sdk:"evm"}),G({},z,{chainId:11155111,network:"sepolia",nodeUri:"https://sepolia.infura.io/v3",explorerUri:"https://sepolia.etherscan.io",gasFeeMultiplier:1.1,sdk:"evm"}),G({},z,{chainId:1,network:"mainnet",nodeUri:"https://mainnet.infura.io/v3",explorerUri:"https://etherscan.io",startBlock:11105459,transactionBlockTimeout:150,transactionConfirmationBlocks:5,transactionPollingTimeout:1750,gasFeeMultiplier:1.05,sdk:"evm"}),G({},z,{chainId:8453,network:"base",nodeUri:"https://mainnet.base.org",explorerUri:"https://etherscan.io",startBlock:30562198,transactionBlockTimeout:150,transactionConfirmationBlocks:5,transactionPollingTimeout:1750,gasFeeMultiplier:1.05,sdk:"evm"}),G({},z,{chainId:137,network:"polygon",nodeUri:"https://polygon-mainnet.infura.io/v3",explorerUri:"https://polygonscan.com",oceanTokenSymbol:"mOCEAN",gasFeeMultiplier:1.6,sdk:"evm"}),G({},z,{chainId:2021e3,network:"gaiaxtestnet",nodeUri:"https://rpc.gaiaxtestnet.oceanprotocol.com",explorerUri:"https://blockscout.gaiaxtestnet.oceanprotocol.com",sdk:"evm"}),G({},z,{chainId:80001,network:"mumbai",nodeUri:"https://polygon-mumbai.infura.io/v3",explorerUri:"https://mumbai.polygonscan.com",gasFeeMultiplier:1.1,sdk:"evm"}),G({},z,{chainId:56,network:"bsc",nodeUri:"https://bsc-dataseed.binance.org",explorerUri:"https://bscscan.com/",gasFeeMultiplier:1.05,sdk:"evm"}),G({},z,{chainId:246,network:"energyweb",nodeUri:"https://rpc.energyweb.org",explorerUri:"https://explorer.energyweb.org",gasFeeMultiplier:1.05,sdk:"evm"}),G({},z,{chainId:1285,network:"moonriver",nodeUri:"https://moonriver.api.onfinality.io/public",explorerUri:"https://moonriver.moonscan.io/",gasFeeMultiplier:1.05,sdk:"evm"}),G({},z,{chainId:100,network:"gen-x-testnet",nodeUri:"https://rpc.genx.minimal-gaia-x.eu",explorerUri:"https://explorer.genx.minimal-gaia-x.eu/",gasFeeMultiplier:1,sdk:"evm"}),G({},z,{chainId:10,network:"optimism",nodeUri:"https://mainnet.optimism.io",explorerUri:"https://optimistic.etherscan.io/",gasFeeMultiplier:1.1,sdk:"evm"}),G({},z,{chainId:11155420,network:"optimism_sepolia",nodeUri:"https://sepolia.optimism.io",explorerUri:"https://sepolia-optimism.etherscan.io/",gasFeeMultiplier:1.1,sdk:"evm"}),G({},z,{chainId:23294,network:"oasis_sapphire",nodeUri:"https://sapphire.oasis.io",explorerUri:"https://explorer.oasis.io/mainnet/sapphire/",gasFeeMultiplier:1,sdk:"oasis"}),G({},z,{chainId:23295,network:"oasis_sapphire_testnet",nodeUri:"https://testnet.sapphire.oasis.dev",explorerUri:"https://explorer.oasis.io/testnet/sapphire/",gasFeeMultiplier:1,sdk:"oasis"}),G({},z,{chainId:32456,network:"pontus-x-devnet",nodeUri:"https://rpc.dev.pontus-x.eu",explorerUri:"https://explorer.dev.pontus-x.eu/testnet/pontusx",sdk:"evm"})],q=[23294,23295];class J{getAddressesFromEnv(e,a){let i;const r=()=>process.env.NODE_URL?{oceanNodeUri:process.env.NODE_URL}:{};if(a&&a[e]){const{FixedPrice:t,Dispenser:n,ERC721Factory:s,OPFCommunityFeeCollector:o,Ocean:c,chainId:l,startBlock:d,Router:u,AccessListFactory:h,Escrow:g,EnterpriseFeeCollector:w}=a[e];i=G({nftFactoryAddress:s,opfCommunityFeeCollector:o,fixedRateExchangeAddress:t,dispenserAddress:n,oceanTokenAddress:c,routerFactoryAddress:u,chainId:l,startBlock:d,accessListFactory:h,escrow:g,EnterpriseFeeCollector:w},r())}else if(t[e]){const{FixedPrice:a,Dispenser:n,OPFCommunityFeeCollector:s,ERC721Factory:o,Ocean:c,chainId:l,startBlock:d,Router:u,AccessListFactory:h,Escrow:g,EnterpriseFeeCollector:w}=t[e];i=G({nftFactoryAddress:o,opfCommunityFeeCollector:s,fixedRateExchangeAddress:a,dispenserAddress:n,oceanTokenAddress:c,routerFactoryAddress:u,chainId:l,startBlock:d,accessListFactory:h,escrow:g,EnterpriseFeeCollector:w},r())}return i}getConfig(t,a){const i="string"==typeof t?"network":"chainId";let r,n=B.find(e=>e[i]===t);if(!n)return _.error(`No config found for given network '${t}'`),null;try{r=process.env.ADDRESS_FILE?JSON.parse(e.readFileSync(process.env.ADDRESS_FILE,"utf8")):null}catch(t){console.log(t),r=null}let s=this.getAddressesFromEnv(n.network,r);return!s&&q.includes(n.chainId)&&(s=this.getAddressesFromEnv(n.network.replace("sapph","saph"),r)),"sdk"in n&&null!==n.sdk||(n.sdk=q.includes(n.chainId)?"oasis":"evm"),s&&"accessListFactory"in s&&(n.accessListFactory=s.accessListFactory),n=G({},n,s),G({},n,{nodeUri:a?`${n.nodeUri}/${a}`:n.nodeUri})}}const W=[{constant:!0,inputs:[],name:"name",outputs:[{name:"",type:"string"}],payable:!1,stateMutability:"view",type:"function"},{constant:!1,inputs:[{name:"_spender",type:"address"},{name:"_value",type:"uint256"}],name:"approve",outputs:[{name:"",type:"bool"}],payable:!1,stateMutability:"nonpayable",type:"function"},{constant:!0,inputs:[],name:"totalSupply",outputs:[{name:"",type:"uint256"}],payable:!1,stateMutability:"view",type:"function"},{constant:!1,inputs:[{name:"_from",type:"address"},{name:"_to",type:"address"},{name:"_value",type:"uint256"}],name:"transferFrom",outputs:[{name:"",type:"bool"}],payable:!1,stateMutability:"nonpayable",type:"function"},{constant:!0,inputs:[],name:"decimals",outputs:[{name:"",type:"uint8"}],payable:!1,stateMutability:"view",type:"function"},{constant:!0,inputs:[{name:"_owner",type:"address"}],name:"balanceOf",outputs:[{name:"balance",type:"uint256"}],payable:!1,stateMutability:"view",type:"function"},{constant:!0,inputs:[],name:"symbol",outputs:[{name:"",type:"string"}],payable:!1,stateMutability:"view",type:"function"},{constant:!1,inputs:[{name:"_to",type:"address"},{name:"_value",type:"uint256"}],name:"transfer",outputs:[{name:"",type:"bool"}],payable:!1,stateMutability:"nonpayable",type:"function"},{constant:!0,inputs:[{name:"_owner",type:"address"},{name:"_spender",type:"address"}],name:"allowance",outputs:[{name:"",type:"uint256"}],payable:!1,stateMutability:"view",type:"function"},{payable:!0,stateMutability:"payable",type:"fallback"},{anonymous:!1,inputs:[{indexed:!0,name:"owner",type:"address"},{indexed:!0,name:"spender",type:"address"},{indexed:!1,name:"value",type:"uint256"}],name:"Approval",type:"event"},{anonymous:!1,inputs:[{indexed:!0,name:"from",type:"address"},{indexed:!0,name:"to",type:"address"},{indexed:!1,name:"value",type:"uint256"}],name:"Transfer",type:"event"}],V=3e10,H=4e9,Z=1e10,X=11155111;function K(t,e){return t}async function Q(t,e){const a=(await t.provider.getFeeData()).gasPrice,i=BigInt(a.toString());return e?(i*BigInt(e)).toString(10):i.toString()}async function Y(t,e){return new a.Contract(e,W,t).decimals()}async function tt(t,e,a,r){let n=r||await Y(t,e);return"0"===n&&(n=18),i(a,n).toString()}async function et(t,e,a,i){let n=i||await Y(t,e);return"0"===n&&(n=18),r(a,n).toString()}function at(t,e){if(t&&t.logs)return t.logs.filter(t=>t instanceof n&&t.eventName===e)[0]}async function it(t,e,a,i,...r){const{chainId:n}=await e.provider.getNetwork(),s=await e.provider.getFeeData();let o={};if(s.maxPriorityFeePerGas){let t=s.maxPriorityFeePerGas.toString(),e=s.maxFeePerGas.toString();a>1&&(t=Math.round(Number(s.maxPriorityFeePerGas)*a).toString(),e=Math.round(Number(s.maxFeePerGas)*a).toString()),o={maxPriorityFeePerGas:(80001===Number(n)||137===Number(n))&&Number(t)<V?V:Number(n)===X&&Number(t)<H?H:q.includes(Number(n))&&Number(t)<Z?Z:Number(t),maxFeePerGas:(80001===Number(n)||137===Number(n))&&Number(e)<V?V:Number(n)===X&&Number(e)<H?H:q.includes(Number(n))&&Number(e)<Z?Z:Number(e)}}else o={gasPrice:s.gasPrice};o.gasLimit=BigInt(new p(t).plus(20000n).toString());try{const t=await i(...r,o);return await t.wait(),t}catch(t){return _.error("Send tx error: ",t),null}}class rt{constructor(t,e,a,i){this.signer=void 0,this.config=void 0,this.abi=void 0,this.signer=t,this.config=a||(new J).getConfig(e),this.abi=i||this.getDefaultAbi()}getSignerAccordingSdk(){return this.config&&"sdk"in this.config&&"oasis"===this.config.sdk?w.wrap(this.signer):this.signer}async amountToUnits(t,e,a){return et(this.signer,t,e,a)}async unitsToAmount(t,e,a){return tt(this.signer,t,e,a)}async getFairGasPrice(){var t;return Q(this.signer,null==(t=this.config)?void 0:t.gasFeeMultiplier)}getContract(t,e){if(!t)throw new Error("Contract address is required but not provided");return K(new a.Contract(t,new a.Interface(JSON.stringify(e||this.abi)),this.signer))}}class nt extends rt{constructor(t,e,a,i,r){super(e,a,i,r),this.address=void 0,this.contract=void 0,this.address=t,this.contract=this.getContract(this.address)}}class st extends nt{getDefaultAbi(){return f.abi}async status(t){const e=await this.contract.status(t);if(!e)throw new Error("Np dispenser found for the given datatoken address");return{active:e.active,owner:e.owner,isMinter:e.isMinter,maxTokens:await this.unitsToAmount(null,e.maxTokens,18),maxBalance:await this.unitsToAmount(null,e.maxBalance,18),balance:await this.unitsToAmount(null,e.balance,18),allowedSwapper:e.allowedSwapper}}async create(t,e,a,i,r,n){var s;const o=await this.contract.create.estimateGas(t,this.amountToUnits(null,a,18),this.amountToUnits(null,i,18),e,r);return n?o:await it(o,this.getSignerAccordingSdk(),null==(s=this.config)?void 0:s.gasFeeMultiplier,this.contract.create,t,this.amountToUnits(null,a,18),this.amountToUnits(null,i,18),e,r)}async activate(t,e,a,i){var r;const n=await this.contract.activate.estimateGas(t,this.amountToUnits(null,e,18),this.amountToUnits(null,a,18));return i?n:await it(n,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,this.contract.activate,t,this.amountToUnits(null,e,18),this.amountToUnits(null,a,18))}async deactivate(t,e){var a;const i=await this.contract.deactivate.estimateGas(t);return e?i:await it(i,this.getSignerAccordingSdk(),null==(a=this.config)?void 0:a.gasFeeMultiplier,this.contract.deactivate,t)}async setAllowedSwapper(t,e,a){var i;const r=await this.contract.setAllowedSwapper.estimateGas(t,e);return a?r:await it(r,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.setAllowedSwapper,t,e)}async dispense(t,e="1",a,i){var r;const n=await this.contract.dispense.estimateGas(t,this.amountToUnits(null,e,18),a);return i?n:await it(n,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,this.contract.dispense,t,this.amountToUnits(null,e,18),a)}async ownerWithdraw(t,e){var a;const i=await this.contract.ownerWithdraw.estimateGas(t);return e?i:await it(i,this.getSignerAccordingSdk(),null==(a=this.config)?void 0:a.gasFeeMultiplier,this.contract.ownerWithdraw,t)}async isDispensable(t,e,a,i="1"){const r=await this.status(t);return!(!r||!1===r.active||new m(await e.balance(t,a)).greaterThanOrEqualTo(r.maxBalance)||new m(String(i)).greaterThan(r.maxTokens)||!new m(r.balance).greaterThanOrEqualTo(i)&&!0!==r.isMinter)}}const ot="0x0000000000000000000000000000000000000000",ct=1e6,lt="115792089237316195423570985008687907853269984665640564039457584007913129639934",dt="Returned error: Method eth_feeHistory not supported.";class ut extends nt{getDefaultAbi(){return y.abi}async generateExchangeId(t,e){return await this.contract.generateExchangeId(t,e)}async buyDatatokens(t,e,a,i=ot,r="0",n){var s;const o=await this.getExchange(t),c=await this.amountToUnits(null,r,18),l=await this.amountToUnits(o.datatoken,e,Number(o.dtDecimals)),d=await this.amountToUnits(o.baseToken,a,Number(o.btDecimals)),u=await this.contract.buyDT.estimateGas(t,l,d,i,c);return n?u:await it(u,this.getSignerAccordingSdk(),null==(s=this.config)?void 0:s.gasFeeMultiplier,this.contract.buyDT,t,l,d,i,c)}async sellDatatokens(t,e,a,i=ot,r="0",n){var s;const o=await this.getExchange(t),c=await this.amountToUnits(null,r,18),l=await this.amountToUnits(o.datatoken,e,Number(o.dtDecimals)),d=await this.amountToUnits(o.baseToken,a,Number(o.btDecimals)),u=await this.contract.sellDT.estimateGas(t,l,d,i,c);return n?u:await it(u,this.getSignerAccordingSdk(),null==(s=this.config)?void 0:s.gasFeeMultiplier,this.contract.sellDT,t,l,d,i,c)}async getNumberOfExchanges(){const t=await this.contract.getNumberOfExchanges();return Number(t)}async setRate(t,e,a){var i;const r=await this.contract.setRate.estimateGas(t,await this.amountToUnits(null,e,18));return a?r:await it(r,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.setRate,t,await this.amountToUnits(null,e,18))}async setAllowedSwapper(t,e,a){var i;const r=await this.contract.setAllowedSwapper.estimateGas(t,e);return a?r:await it(r,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.setAllowedSwapper,t,e)}async activate(t,e){var a;const i=await this.getExchange(t);if(!i)return null;if(!0===i.active)return null;const r=await this.contract.toggleExchangeState.estimateGas(t);return e?r:await it(r,this.getSignerAccordingSdk(),null==(a=this.config)?void 0:a.gasFeeMultiplier,this.contract.toggleExchangeState,t)}async deactivate(t,e){var a;const i=await this.getExchange(t);if(!i)return null;if(!1===i.active)return null;const r=await this.contract.toggleExchangeState.estimateGas(t);return e?r:await it(r,this.getSignerAccordingSdk(),null==(a=this.config)?void 0:a.gasFeeMultiplier,this.contract.toggleExchangeState,t)}async getRate(t){const e=await this.contract.getRate(t);return await this.unitsToAmount(null,e,18)}async getDatatokenSupply(t){const e=await this.contract.getDTSupply(t),a=await this.getExchange(t);return await this.unitsToAmount(a.datatoken,e,Number(a.dtDecimals))}async getBasetokenSupply(t){const e=await this.contract.getBTSupply(t),a=await this.getExchange(t);return await this.unitsToAmount(a.baseToken,e,Number(a.btDecimals))}async getAllowedSwapper(t){return await this.contract.getAllowedSwapper(t)}async calcBaseInGivenDatatokensOut(t,e,a="0"){const i=await this.getExchange(t),r=await this.contract.calcBaseInGivenOutDT(t,await this.amountToUnits(i.datatoken,e,Number(i.dtDecimals)),await this.amountToUnits(null,a,18));return{baseTokenAmount:await this.unitsToAmount(i.baseToken,r.baseTokenAmount,Number(i.btDecimals)),marketFeeAmount:await this.unitsToAmount(i.baseToken,r.publishMarketFeeAmount,Number(i.btDecimals)),oceanFeeAmount:await this.unitsToAmount(i.baseToken,r.oceanFeeAmount,Number(i.btDecimals)),consumeMarketFeeAmount:await this.unitsToAmount(i.baseToken,r.consumeMarketFeeAmount,Number(i.btDecimals))}}async getAmountBasetokensOut(t,e,a="0"){const i=await this.getExchange(t),r=await this.contract.calcBaseOutGivenInDT(t,await this.amountToUnits(i.datatoken,e,Number(i.dtDecimals)),await this.amountToUnits(null,a,18));return await this.unitsToAmount(i.baseToken,r[0],Number(i.btDecimals))}async getExchange(t){const e=await this.contract.getExchange(t);return{active:e.active,datatoken:e.datatoken,baseToken:e.baseToken,withMint:e.withMint,exchangeOwner:e.exchangeOwner,allowedSwapper:e.allowedSwapper,dtDecimals:e.dtDecimals.toString(),btDecimals:e.btDecimals.toString(),dtBalance:await this.unitsToAmount(e.datatoken,e.dtBalance,Number(e.dtDecimals)),btBalance:await this.unitsToAmount(e.baseToken,e.btBalance,Number(e.btDecimals)),dtSupply:await this.unitsToAmount(e.datatoken,e.dtSupply,Number(e.dtDecimals)),btSupply:await this.unitsToAmount(e.baseToken,e.btSupply,Number(e.btDecimals)),fixedRate:await this.unitsToAmount(null,e.fixedRate,18),exchangeId:t}}async getFeesInfo(t){const e=await this.contract.getFeesInfo(t),a=await this.getExchange(t);return{opcFee:await this.unitsToAmount(null,e.opcFee.toString(),18),marketFee:await this.unitsToAmount(null,e.marketFee.toString(),18),marketFeeCollector:e.marketFeeCollector,marketFeeAvailable:await this.unitsToAmount(a.baseToken,e.marketFeeAvailable,Number(a.btDecimals)),oceanFeeAvailable:await this.unitsToAmount(a.baseToken,e.oceanFeeAvailable,Number(a.btDecimals)),exchangeId:t}}async getExchanges(){return await this.contract.getExchanges()}async isActive(t){return await this.contract.isActive(t)}async activateMint(t,e){var a;const i=await this.getExchange(t);if(!i)return null;if(!0===i.withMint)return null;const r=await this.contract.toggleMintState.estimateGas(t,!0);return e?r:await it(r,this.getSignerAccordingSdk(),null==(a=this.config)?void 0:a.gasFeeMultiplier,this.contract.toggleMintState,t,!0)}async deactivateMint(t,e){var a;const i=await this.getExchange(t);if(!i)return null;if(!1===i.withMint)return null;const r=await this.contract.toggleMintState.estimateGas(t,!1);return e?r:await it(r,this.getSignerAccordingSdk(),null==(a=this.config)?void 0:a.gasFeeMultiplier,this.contract.toggleMintState,t,!1)}async collectBasetokens(t,e,a){var i;if(!await this.getExchange(t))return null;const r=await this.contract.getExchange(t),n=await this.amountToUnits(r.baseToken,e,Number(r.btDecimals)),s=await this.contract.collectBT.estimateGas(t,n);return a?s:await it(s,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.collectBT,t,n)}async collectDatatokens(t,e,a){var i;if(!await this.getExchange(t))return null;const r=await this.contract.getExchange(t),n=await this.amountToUnits(r.datatoken,e,Number(r.dtDecimals)),s=await this.contract.collectDT.estimateGas(t,n);return a?s:await it(s,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.collectDT,t,n)}async collectMarketFee(t,e){var a;if(!await this.getExchange(t))return null;const i=await this.contract.collectMarketFee.estimateGas(t);return e?i:await it(i,this.getSignerAccordingSdk(),null==(a=this.config)?void 0:a.gasFeeMultiplier,this.contract.collectMarketFee,t)}async collectOceanFee(t,e){var a;if(!await this.getExchange(t))return null;const i=await this.contract.collectOceanFee.estimateGas(t);return e?i:await it(i,this.getSignerAccordingSdk(),null==(a=this.config)?void 0:a.gasFeeMultiplier,this.contract.collectOceanFee,t)}async getOPCCollector(){return await this.contract.opcCollector()}async getRouter(){return await this.contract.router()}async getExchangeOwner(t){return(await this.getExchange(t)).exchangeOwner}async updateMarketFee(t,e,a){var i;const r=await this.contract.updateMarketFee.estimateGas(t,await this.amountToUnits(null,e,18));return a?r:await it(r,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.updateMarketFee,t,await this.amountToUnits(null,e,18))}async updateMarketFeeCollector(t,e,a){var i;const r=await this.contract.updateMarketFeeCollector.estimateGas(t,e);return a?r:await it(r,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.updateMarketFeeCollector,t,e)}}class ht extends nt{getDefaultAbi(){return v.abi}async buyDatatokenBatch(t,e){var a;const i=await this.contract.buyDTBatch.estimateGas(t);return e?i:await it(i,this.getSignerAccordingSdk(),null==(a=this.config)?void 0:a.gasFeeMultiplier,this.contract.buyDTBatch,t)}async isApprovedToken(t){return await this.contract.isApprovedToken(t)}async isFixedPrice(t){return await this.contract.isFixedRateContract(t)}async getOwner(){return await this.contract.routerOwner()}async getNFTFactory(){return await this.contract.factory()}async addApprovedToken(t,e,a){var i;if(await this.getOwner()!==t)throw new Error("Caller is not Router Owner");const r=await this.contract.addApprovedToken.estimateGas(e);return a?r:await it(r,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.addApprovedToken,e)}async removeApprovedToken(t,e,a){var i;if(await this.getOwner()!==t)throw new Error("Caller is not Router Owner");const r=await this.contract.removeApprovedToken.estimateGas(e);return a?r:await it(r,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.removeApprovedToken,e)}async addFixedRateContract(t,e,a){var i;if(await this.getOwner()!==t)throw new Error("Caller is not Router Owner");const r=await this.contract.addFixedRateContract.estimateGas(e);return a?r:await it(r,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.addFixedRateContract,e)}async removeFixedRateContract(t,e,a){var i;if(await this.getOwner()!==t)throw new Error("Caller is not Router Owner");const r=await this.contract.removeFixedRateContract.estimateGas(e);return a?r:await it(r,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.removeFixedRateContract,e)}async addDispenserContract(t,e,a){var i;if(await this.getOwner()!==t)throw new Error("Caller is not Router Owner");const r=await this.contract.addDispenserContract.estimateGas(e);return a?r:await it(r,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.addDispenserContract,e)}async removeDispenserContract(t,e,a){var i;if(await this.getOwner()!==t)throw new Error("Caller is not Router Owner");const r=await this.contract.removeDispenserContract.estimateGas(e);return a?r:await it(r,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.removeDispenserContract,e)}async getOPCFee(t){const e=await this.contract.getOPCFee(t);return Number(e)}async getCurrentOPCFee(){const t=await this.contract.swapOceanFee();return Number(t)}async updateOPCFee(t,e,a,i,r,n){var s;if(await this.getOwner()!==t)throw new Error("Caller is not Router Owner");const o=await this.contract.updateOPCFee.estimateGas(e,a,i,r);return n?o:await it(o,this.getSignerAccordingSdk(),null==(s=this.config)?void 0:s.gasFeeMultiplier,this.contract.updateOPCFee,e,a,i,r)}}var gt={nouns:["Crab","Fish","Seal","Octopus","Shark","Seahorse","Walrus","Starfish","Whale","Orca","Penguin","Jellyfish","Squid","Lobster","Pelican","Shrimp","Oyster","Clam","Seagull","Dolphin","Shell","Cormorant","Otter","Anemone","Turtle","Coral","Ray","Barracuda","Krill","Anchovy","Angelfish","Barnacle","Clownfish","Cod","Cuttlefish","Eel","Fugu","Herring","Haddock","Ling","Mackerel","Manatee","Narwhal","Nautilus","Plankton","Porpoise","Prawn","Pufferfish","Swordfish","Tuna"],adjectives:["adamant","adroit","amatory","ambitious","amused","animistic","antic","arcadian","artistic","astonishing","astounding","baleful","bellicose","bilious","blissful","boorish","brave","breathtaking","brilliant","calamitous","caustic","cerulean","clever","charming","comely","competent","concomitant","confident","contumacious","corpulent","crapulous","creative","dazzling","dedicated","defamatory","delighted","delightful","determined","didactic","dilatory","dowdy","efficacious","effulgent","egregious","empowered","endemic","enthusiastic","equanimous","exceptional","execrable","fabulous","fantastic","fastidious","feckless","fecund","friable","fulsome","garrulous","generous","gentle","guileless","gustatory","heuristic","histrionic","hubristic","incendiary","incredible","insidious","insolent","inspired","intransigent","inveterate","invidious","invigorated","irksome","jejune","juicy","jocular","joyful","judicious","kind","lachrymose","limpid","loquacious","lovely","luminous","mannered","marvelous","mendacious","meretricious","minatory","mordant","motivated","munificent","nefarious","noxious","obtuse","optimistic","parsimonious","pendulous","pernicious","pervasive","petulant","passionate","phenomenal","platitudinous","pleasant","powerful","precipitate","propitious","puckish","querulous","quiescent","rebarbative","recalcitant","redolent","rhadamanthine","risible","ruminative","sagacious","salubrious","sartorial","sclerotic","serpentine","smart","spasmodic","strident","stunning","stupendous","taciturn","tactful","tasty","tenacious","tremendous","tremulous","trenchant","turbulent","turgid","ubiquitous","uxorious","verdant","vibrant","voluble","voracious","wheedling","withering","wonderful","zealous"]};function wt(t){const e=t||gt,a=Math.floor(Math.random()*e.adjectives.length),i=Math.floor(Math.random()*e.nouns.length),r=Math.floor(100*Math.random()),n=e.adjectives[a].replace(/^\w/,t=>t.toUpperCase()),s=e.nouns[i].replace(/^\w/,t=>t.toUpperCase());return{name:`${n} ${s} Token`,symbol:`${(n.substring(0,3)+s.substring(0,3)).toUpperCase()}-${r}`}}class pt extends nt{getDefaultAbi(){return S.abi}async createNFT(t,e){if(t.templateIndex||(t.templateIndex=1),!t.name||!t.symbol){const{name:e,symbol:a}=wt();t.name=e,t.symbol=a}if(t.templateIndex>await this.getCurrentNFTTemplateCount())throw new Error("Template index doesnt exist");if(0===t.templateIndex)throw new Error("Template index cannot be ZERO");if(!1===(await this.getNFTTemplate(t.templateIndex)).isActive)throw new Error("Template is not active");const a=await this.contract.deployERC721Contract.estimateGas(t.name,t.symbol,t.templateIndex,ot,ot,t.tokenURI,t.transferable,t.owner);if(e)return a;try{var i;const e=await it(a,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.deployERC721Contract,t.name,t.symbol,t.templateIndex,ot,ot,t.tokenURI,t.transferable,t.owner);if(!e){const t="Tx for deploying new NFT contract does not exist or status is not successful.";throw console.error(t),t}return at(await e.wait(),"NFTCreated").args[0]}catch(t){console.error(`Creation of NFT failed: ${t}`)}}async getCurrentNFTCount(){const t=await this.contract.getCurrentNFTCount();return Number(t)}async getCurrentTokenCount(){const t=await this.contract.getCurrentTokenCount();return Number(t)}async getOwner(){return await this.contract.owner()}async getCurrentNFTTemplateCount(){const t=await this.contract.getCurrentNFTTemplateCount();return Number(t)}async getCurrentTokenTemplateCount(){const t=await this.contract.getCurrentTemplateCount();return Number(t)}async getNFTTemplate(t){if(t>await this.getCurrentNFTTemplateCount())throw new Error("Template index doesnt exist");if(0===t)throw new Error("Template index cannot be ZERO");return await this.contract.getNFTTemplate(t)}async getTokenTemplate(t){return await this.contract.getTokenTemplate(t)}async checkDatatoken(t){return await this.contract.erc20List(t)}async checkNFT(t){return await this.contract.erc721List(t)}async addNFTTemplate(t,e,a){var i;if(await this.getOwner()!==t)throw new Error("Caller is not Factory Owner");if(e===ot)throw new Error("Template cannot be ZERO address");const r=await this.contract.add721TokenTemplate.estimateGas(e);return a?r:await it(r,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.add721TokenTemplate,e)}async disableNFTTemplate(t,e,a){var i;if(await this.getOwner()!==t)throw new Error("Caller is not Factory Owner");if(e>await this.getCurrentNFTTemplateCount())throw new Error("Template index doesnt exist");if(0===e)throw new Error("Template index cannot be ZERO");const r=await this.contract.disable721TokenTemplate.estimateGas(e);return a?r:await it(r,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.disable721TokenTemplate,e)}async reactivateNFTTemplate(t,e,a){var i;if(await this.getOwner()!==t)throw new Error("Caller is not Factory Owner");if(e>await this.getCurrentNFTTemplateCount())throw new Error("Template index doesnt exist");if(0===e)throw new Error("Template index cannot be ZERO");const r=await this.contract.reactivate721TokenTemplate.estimateGas(e);return a?r:await it(r,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.reactivate721TokenTemplate,e)}async addTokenTemplate(t,e,a){var i;if(await this.getOwner()!==t)throw new Error("Caller is not Factory Owner");if(e===ot)throw new Error("Template cannot be address ZERO");const r=await this.contract.addTokenTemplate.estimateGas(e);return a?r:await it(r,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.addTokenTemplate,e)}async disableTokenTemplate(t,e,a){var i;if(await this.getOwner()!==t)throw new Error("Caller is not Factory Owner");if(e>await this.getCurrentTokenTemplateCount())throw new Error("Template index doesnt exist");if(0===e)throw new Error("Template index cannot be ZERO");if(!1===(await this.getTokenTemplate(e)).isActive)throw new Error("Template is already disabled");const r=await this.contract.disableTokenTemplate.estimateGas(e);return a?r:await it(r,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.disableTokenTemplate,e)}async reactivateTokenTemplate(t,e,a){var i;if(await this.getOwner()!==t)throw new Error("Caller is not Factory Owner");if(e>await this.getCurrentTokenTemplateCount())throw new Error("Template index doesnt exist");if(0===e)throw new Error("Template index cannot be ZERO");if(!0===(await this.getTokenTemplate(e)).isActive)throw new Error("Template is already active");const r=await this.contract.reactivateTokenTemplate.estimateGas(e);return a?r:await it(r,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.reactivateTokenTemplate,e)}async startMultipleTokenOrder(t,e){var a;if(t.length>50)throw new Error("Too many orders");const i=await this.contract.startMultipleTokenOrder.estimateGas(t);return e?i:await it(i,this.getSignerAccordingSdk(),null==(a=this.config)?void 0:a.gasFeeMultiplier,this.contract.startMultipleTokenOrder,t)}async createNftWithDatatoken(t,e,a){var i;const r=await this.getErcCreationParams(e),n=await this.contract.createNftWithErc20.estimateGas(t,r);return a?n:await it(n,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.createNftWithErc20,t,r)}async createNftWithDatatokenWithFixedRate(t,e,a,i){var r;const n=await this.getErcCreationParams(e),s=await this.getFreCreationParams(a),o=await this.contract.createNftWithErc20WithFixedRate.estimateGas(t,n,s);return i?o:await it(o,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,this.contract.createNftWithErc20WithFixedRate,t,n,s)}async createNftWithDatatokenWithDispenser(t,e,a,i){var r;const n=await this.getErcCreationParams(e);a.maxBalance=await this.amountToUnits(null,a.maxBalance,18),a.maxTokens=await this.amountToUnits(null,a.maxTokens,18);const s=await this.contract.createNftWithErc20WithDispenser.estimateGas(t,n,a);return i?s:await it(s,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,this.contract.createNftWithErc20WithDispenser,t,n,a)}async getErcCreationParams(t){let e,a;t.name&&t.symbol||({name:e,symbol:a}=wt());let i=18;if(t.feeToken!==ot)try{i=await Y(this.signer,t.feeToken)}catch(t){_.error("getTokenDecimals error",t)}const r=[t.minter,t.paymentCollector,t.mpFeeAddress,t.feeToken];return t.filesObject&&(t.accessListFactory&&r.push(t.accessListFactory),t.allowAccessList&&r.push(t.allowAccessList),t.denyAccessList&&r.push(t.denyAccessList)),{templateIndex:t.templateIndex,strings:[t.name||e,t.symbol||a],addresses:r,uints:[await this.amountToUnits(null,t.cap,18),await this.amountToUnits(null,t.feeAmount,i)],bytess:t.filesObject?[s(JSON.stringify(t.filesObject))]:[]}}async getFreCreationParams(t){t.allowedConsumer||(t.allowedConsumer=ot);const e=!1===t.withMint?0:1;return{fixedPriceAddress:t.fixedRateAddress,addresses:[t.baseTokenAddress,t.owner,t.marketFeeCollector,t.allowedConsumer],uints:[t.baseTokenDecimals,t.datatokenDecimals,await this.amountToUnits(null,t.fixedRate,t.datatokenDecimals),await this.amountToUnits(null,t.marketFee,t.datatokenDecimals),e]}}}function mt(){try{if(process.env.ADDRESS_FILE){const t=e.readFileSync(process.env.ADDRESS_FILE,"utf8");return JSON.parse(t)}return t}catch(e){return t}}function ft(t){try{const e=mt();if(e){const a=Object.keys(e);for(const i of a)if(e[i].chainId===t)return e[i]}}catch(t){console.error(t)}return null}async function yt(t,e,i,r){const n="number"==typeof i,s=new pt(e,t,r),o=await s.getCurrentTokenTemplateCount();for(let e=1;e<=o;e++){const r=await s.getTokenTemplate(e),o=new a.Contract(r.templateAddress,E.abi,t);if(n){const t=await o.getId();if(r.isActive&&t.toString()===i.toString())return e}else if(r.isActive&&r.templateAddress===i.toString())return e}return-1}class vt extends rt{getDefaultAbi(){return b.abi}async createDatatoken(t,e,a,i,r,n,o,c,l,d,u,h,g,w,p,m){var f;if(!0!==(await this.getNftPermissions(t,e)).deployERC20)throw new Error("Caller is not DatatokenDeployer");u||(u=1),l&&d||({name:l,symbol:d}=wt());const y=this.getContract(t);if(!this.signer.provider)throw new Error("Provider is required but not available");const{chainId:v}=await this.signer.provider.getNetwork(),k=ft(Number(v));h&&(u=await yt(this.signer,k.ERC721Factory,4,Number(v)));const T=await y.createERC20.estimateGas(u,[l,d],[a,i,r,n],[await this.amountToUnits(null,c,18),await this.amountToUnits(null,o,18)],[]);if(m)return T;const b=[a,i,r,n];g&&(b.push(g.toLowerCase()),b.push(w?w.toLowerCase():ot),b.push(p||ot));const S=await it(T,this.getSignerAccordingSdk(),null==(f=this.config)?void 0:f.gasFeeMultiplier,y.createERC20,u,[l,d],b,[await this.amountToUnits(null,c,18),await this.amountToUnits(null,o,18)],h?[s(h)]:[]),E=at(await S.wait(),"TokenCreated");return null==E?void 0:E.args[0]}async addManager(t,e,a,i){var r;const n=this.getContract(t);if(await this.getNftOwner(t)!==e)throw new Error("Caller is not NFT Owner");const s=await n.addManager.estimateGas(a);return i?s:await it(s,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,n.addManager,a)}async removeManager(t,e,a,i){var r;const n=this.getContract(t);if(await this.getNftOwner(t)!==e)throw new Error("Caller is not NFT Owner");const s=await n.removeManager.estimateGas(a);return i?s:await it(s,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,n.removeManager,a)}async addDatatokenDeployer(t,e,a,i){var r;const n=this.getContract(t);if(!0!==(await this.getNftPermissions(t,e)).manager)throw new Error("Caller is not Manager");const s=await n.addToCreateERC20List.estimateGas(a);return i?s:await it(s,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,n.addToCreateERC20List,a)}async removeDatatokenDeployer(t,e,a,i){var r;const n=this.getContract(t);if(!0!==(await this.getNftPermissions(t,e)).manager||e===a&&!0!==(await this.getNftPermissions(t,e)).deployERC20)throw new Error("Caller is not Manager nor DatatokenDeployer");const s=await n.removeFromCreateERC20List.estimateGas(a);return i?s:await it(s,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,n.removeFromCreateERC20List,a)}async addMetadataUpdater(t,e,a,i){var r;const n=this.getContract(t);if(!0!==(await this.getNftPermissions(t,e)).manager)throw new Error("Caller is not Manager");const s=await n.addToMetadataList.estimateGas(a);return i?s:await it(s,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,n.addToMetadataList,a)}async removeMetadataUpdater(t,e,a,i){var r;const n=this.getContract(t);if(!0!==(await this.getNftPermissions(t,e)).manager||e!==a&&!0!==(await this.getNftPermissions(t,e)).updateMetadata)throw new Error("Caller is not Manager nor Metadata Updater");const s=await n.removeFromMetadataList.estimateGas(a);return i?s:await it(s,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,n.removeFromMetadataList,a)}async addStoreUpdater(t,e,a,i){var r;const n=this.getContract(t);if(!0!==(await this.getNftPermissions(t,e)).manager)throw new Error("Caller is not Manager");const s=await n.addTo725StoreList.estimateGas(a);return i?s:await it(s,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,n.addTo725StoreList,a)}async removeStoreUpdater(t,e,a,i){var r;const n=this.getContract(t);if(!0!==(await this.getNftPermissions(t,e)).manager||e!==a&&!0!==(await this.getNftPermissions(t,e)).store)throw new Error("Caller is not Manager nor storeUpdater");const s=await n.removeFrom725StoreList.estimateGas(a);return i?s:await it(s,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,n.removeFrom725StoreList,a)}async cleanPermissions(t,e,a){var i;const r=this.getContract(t);if(await this.getNftOwner(t)!==e)throw new Error("Caller is not NFT Owner");const n=await r.cleanPermissions.estimateGas();return a?n:await it(n,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,r.cleanPermissions)}async transferNft(t,e,a,i,r){var n;const s=this.getContract(t);if(await this.getNftOwner(t)!==e)throw new Error("Caller is not NFT Owner");const o=i||1,c=await s.transferFrom.estimateGas(e,a,o);return r?c:await it(c,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,s.transferFrom,e,a,o)}async safeTransferNft(t,e,a,i,r){var n;const s=this.getContract(t);if(await this.getNftOwner(t)!==e)throw new Error("Caller is not NFT Owner");const o=i||1,c=await s.safeTransferFrom.estimateGas(e,a,o);return r?c:await it(c,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,s.safeTransferFrom,e,a,o)}async setMetadata(t,e,a,i,r,n,s,o,c,l){var d;const u=this.getContract(t);if(c||(c=[]),!(await this.getNftPermissions(t,e)).updateMetadata)throw new Error("Caller is not Metadata updater");const h=await u.setMetaData.estimateGas(a,i,r,n,s,o,c);return l?h:await it(h,this.signer,null==(d=this.config)?void 0:d.gasFeeMultiplier,u.setMetaData,a,i,r,n,s,o,c)}async setMetadataAndTokenURI(t,e,a,i){var r;const n=this.getContract(t);if(!(await this.getNftPermissions(t,e)).updateMetadata)throw new Error("Caller is not Metadata updater");const s=G({},a,{metadataProofs:a.metadataProofs||[]}),o=await n.setMetaDataAndTokenURI.estimateGas(s);return i?o:await it(o,this.signer,null==(r=this.config)?void 0:r.gasFeeMultiplier,n.setMetaDataAndTokenURI,s)}async setMetadataState(t,e,a,i){var r;const n=this.getContract(t);if(!(await this.getNftPermissions(t,e)).updateMetadata)throw new Error("Caller is not Metadata updater");const s=await n.setMetaDataState.estimateGas(a);return i?s:await it(s,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,n.setMetaDataState,a)}async setTokenURI(t,e,a){var i;const r=this.getContract(t),n=await r.setTokenURI.estimateGas("1",e);return a?n:await it(n,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,r.setTokenURI,"1",e)}async getNftOwner(t){const e=this.getContract(t);return await e.ownerOf(1)}async getNftPermissions(t,e){const a=this.getContract(t);return await a.getPermissions(e)}async getMetadata(t){const e=this.getContract(t);return await e.getMetaData()}async isDatatokenDeployer(t,e){const a=this.getContract(t);return await a.isERC20Deployer(e)}async setData(t,e,a,i,r){var n;if(!0!==(await this.getNftPermissions(t,e)).store)throw new Error("User is not ERC20 store updater");const l=this.getContract(t),d=o(a),u=c(s(i)),h=await l.setNewData.estimateGas(d,u);return r?h:await it(h,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,l.setNewData,d,u)}async getData(t,e){const a=this.getContract(t),i=o(e),r=await a.getData(i);return r?l(r):null}async getTokenURI(t,e){const a=this.getContract(t);return await a.tokenURI(e)}async isDatatokenDeployed(t,e){const a=this.getContract(t);return await a.isDeployed(e)}}class kt extends rt{getDefaultAbi(){return k.abi}constructor(t,e,a,i,r){super(t,e,a,i),this.abiEnterprise=void 0,this.nft=void 0,this.abiEnterprise=r||T.abi,this.nft=new vt(this.signer,e)}async approve(t,e,a,i){var r;const n=this.getContract(t),s=await n.approve.estimateGas(e,et(null,null,a,18));return i?s:await it(s,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,n.approve,e,et(null,null,a,18))}async createFixedRate(t,e,a,i){var r;const n=this.getContract(t);if(!await this.isDatatokenDeployer(t,e))throw new Error("User is not Datatoken Deployer");a.allowedConsumer||(a.allowedConsumer=ot);const s=!1===a.withMint?0:1,o=await n.createFixedRate.estimateGas(a.fixedRateAddress,[a.baseTokenAddress,a.owner,a.marketFeeCollector,a.allowedConsumer],[a.baseTokenDecimals,a.datatokenDecimals,a.fixedRate,a.marketFee,s]);return i?o:await it(o,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,n.createFixedRate,a.fixedRateAddress,[a.baseTokenAddress,a.owner,a.marketFeeCollector,a.allowedConsumer],[a.baseTokenDecimals,a.datatokenDecimals,a.fixedRate,a.marketFee,s])}async createDispenser(t,e,a,i,r){var n;if(!await this.isDatatokenDeployer(t,e))throw new Error("User is not Datatoken Deployer");const s=this.getContract(t);i.allowedSwapper||(i.allowedSwapper=ot),i.withMint=!1!==i.withMint;const o=await s.createDispenser.estimateGas(a,i.maxTokens,i.maxBalance,i.withMint,i.allowedSwapper);return r?o:await it(o,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,s.createDispenser,a,i.maxTokens,i.maxBalance,i.withMint,i.allowedSwapper)}async mint(t,e,a,i,r){const n=this.getContract(t);if(!0!==(await this.getPermissions(t,e)).minter)throw new Error("Caller is not Minter");const s=await this.getCap(t);if(new m(s).gte(a)){var o;const t=await n.mint.estimateGas(i||e,et(null,null,a,18));return r?t:await it(t,this.getSignerAccordingSdk(),null==(o=this.config)?void 0:o.gasFeeMultiplier,n.mint,i||e,et(null,null,a,18))}throw new Error("Mint amount exceeds cap available")}async addMinter(t,e,a,i){var r;const n=this.getContract(t);if(!0!==await this.isDatatokenDeployer(t,e))throw new Error("Caller is not DatatokenDeployer");const s=await n.addMinter.estimateGas(a);return i?s:await it(s,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,n.addMinter,a)}async removeMinter(t,e,a,i){var r;const n=this.getContract(t);if(!0!==await this.isDatatokenDeployer(t,e))throw new Error("Caller is not DatatokenDeployer");const s=await n.removeMinter.estimateGas(a);return i?s:await it(s,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,n.removeMinter,a)}async addPaymentManager(t,e,a,i){var r;const n=this.getContract(t);if(!0!==await this.isDatatokenDeployer(t,e))throw new Error("Caller is not DatatokenDeployer");const s=await n.addPaymentManager.estimateGas(a);return i?s:await it(s,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,n.addPaymentManager,a)}async removePaymentManager(t,e,a,i){var r;const n=this.getContract(t);if(!0!==await this.isDatatokenDeployer(t,e))throw new Error("Caller is not DatatokenDeployer");const s=await n.removePaymentManager.estimateGas(a);return i?s:await it(s,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,n.removePaymentManager,a)}async setPaymentCollector(t,e,a,i){var r;const n=this.getContract(t),s=(await this.getPermissions(t,e)).paymentManager,o=!s&&await this.getNFTAddress(t),c=o&&await this.nft.getNftOwner(o)===e,l=o&&!c&&await this.nft.getNftPermissions(o,e);if(!s&&!c&&!(null==l?void 0:l.deployERC20))throw new Error("Caller is not Fee Manager, owner or Datatoken Deployer");const d=await n.setPaymentCollector.estimateGas(a);return i?d:await it(d,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,n.setPaymentCollector,a)}async getPaymentCollector(t){const e=this.getContract(t);return await e.getPaymentCollector()}async transfer(t,e,a,i){return this.transferWei(t,e,await et(null,null,a,18),i)}async transferWei(t,e,a,i){var r;const n=this.getContract(t),s=await n.transfer.estimateGas(e,a);return i?s:await it(s,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,n.transfer,e,a)}async startOrder(t,e,a,i,r,n){var s;const o=this.getContract(t,this.abi);r||(r={consumeMarketFeeAddress:ot,consumeMarketFeeToken:ot,consumeMarketFeeAmount:"0"});const c=await o.startOrder.estimateGas(e,a,i,r);return n?c:await it(c,this.getSignerAccordingSdk(),null==(s=this.config)?void 0:s.gasFeeMultiplier,o.startOrder,e,a,i,r)}async reuseOrder(t,e,a,i){var r;const n=this.getContract(t),s=await n.reuseOrder.estimateGas(e,a);return i?s:await it(s,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,n.reuseOrder,e,a)}async buyFromFreAndOrder(t,e,a,i){var r;const n=this.getContract(t,this.abiEnterprise),s=await this.getFreOrderParams(a),o=await n.buyFromFreAndOrder.estimateGas(e,s);return i?o:await it(o,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,n.buyFromFreAndOrder,e,s)}async buyFromDispenserAndOrder(t,e,a,i){var r;const n=this.getContract(t,this.abiEnterprise),s=await n.buyFromDispenserAndOrder.estimateGas(e,a);return i?s:await it(s,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,n.buyFromDispenserAndOrder,e,a)}async setData(t,e,a,i){var r;if(!await this.isDatatokenDeployer(t,e))throw new Error("User is not Datatoken Deployer");const n=this.getContract(t),o=c(s(a)),l=await n.setData.estimateGas(o);return i?l:await it(l,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,n.setData,o)}async cleanPermissions(t,e,a){var i;if(await this.nft.getNftOwner(await this.getNFTAddress(t))!==e)throw new Error("Caller is NOT Nft Owner");const r=this.getContract(t),n=await r.cleanPermissions.estimateGas();return a?n:await it(n,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,r.cleanPermissions)}async getPermissions(t,e){const a=this.getContract(t);return await a.permissions(e)}async getCap(t){const e=this.getContract(t),a=await e.cap();return await this.unitsToAmount(null,a,18)}async getDecimals(t){const e=this.getContract(t),a=await e.decimals();return Number(a)}async getId(t){const e=this.getContract(t),a=await e.getId();return Number(a)}async getSymbol(t){const e=this.getContract(t);return await e.symbol()}async getName(t){const e=this.getContract(t);return await e.name()}async getNFTAddress(t){const e=this.getContract(t);return await e.getERC721Address()}async getFixedRates(t){const e=this.getContract(t);return await e.getFixedRates()}async getDispensers(t){const e=this.getContract(t);return await e.getDispensers()}async isDatatokenDeployer(t,e){const a=this.getContract(t);return await a.isERC20Deployer(e)}async balance(t,e){const a=this.getContract(t),i=await a.balanceOf(e);return await this.unitsToAmount(null,i,18)}async allowance(t,e,a,i=18){const r=this.getContract(t),n=await r.allowance(e,a);return await this.unitsToAmount(null,n,i)}async setPublishingMarketFee(t,e,a,i,r,n){var s;const o=this.getContract(t);if((await o.getPublishingMarketFee())[0]!==r)throw new Error("Caller is not the Publishing Market Fee Address");const c=await o.setPublishingMarketFee.estimateGas(e,a,i);return n?c:await it(c,this.getSignerAccordingSdk(),null==(s=this.config)?void 0:s.gasFeeMultiplier,o.setPublishingMarketFee,e,a,i)}async getPublishingMarketFee(t){const e=this.getContract(t),a=await e.getPublishingMarketFee();return{publishMarketFeeAddress:a[0],publishMarketFeeToken:a[1],publishMarketFeeAmount:a[2].toString()}}async getFreOrderParams(t){return{exchangeContract:t.exchangeContract,exchangeId:t.exchangeId,maxBaseTokenAmount:await et(this.signer,t.baseTokenAddress,t.maxBaseTokenAmount,t.baseTokenDecimals),swapMarketFee:await et(this.signer,t.baseTokenAddress,t.swapMarketFee,t.baseTokenDecimals),marketFeeAddress:t.marketFeeAddress}}}class Tt extends kt{getDefaultAbi(){return A.abi}constructor(t,e,a,i,r){super(t,a,i,r),this.accessList=void 0,this.fileObject=void 0,this.abi=this.getDefaultAbi(),this.fileObject=e}setFileObj(t){this.fileObject=t}async getAllowlistContract(t){const e=this.getContract(t,this.getDefaultAbi());return await e.getAllowListContract()}async getDenylistContract(t){const e=this.getContract(t,this.getDefaultAbi());return await e.getDenyListContract()}async setAllowListContract(t,e,a,i){var r;if(!await this.isDatatokenDeployer(t,a))throw new Error("User is not Datatoken Deployer");const n=this.getContract(t),s=await n.setAllowListContract.estimateGas(e);return i?s:await it(s,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,n.setAllowListContract,e)}async setDenyListContract(t,e,a,i){var r;if(!await this.isDatatokenDeployer(t,a))throw new Error("User is not Datatoken Deployer");const n=this.getContract(t),s=await n.setDenyListContract.estimateGas(e);return i?s:await it(s,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,n.setDenyListContract,e)}async setFileObject(t,e,a){var i;if(!await this.isDatatokenDeployer(t,e))throw new Error("User is not Datatoken Deployer");const r=this.getContract(t),n=await r.setFilesObject.estimateGas(this.fileObject);return a?n:await it(n,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,r.setFilesObject,this.fileObject)}async getFileObject(t,e,a,i,r,n,s){const o=this.getContract(t,this.getDefaultAbi());return await o.getFileObject(e,a,i,r,n,s)}}class bt extends nt{getDefaultAbi(){return F.abi}constructor(t,e,a,i,r){super(t,e,a,i,r),this.abiEnterprise=void 0,this.abi=r||this.getDefaultAbi()}async getTokenUri(t){return await this.contract.tokenURI(t)}async getOwner(){return await this.contract.owner()}async getId(){const t=await this.contract.getId();return Number(t)}async getName(){return await this.contract.name()}async getSymbol(){return await this.contract.symbol()}async balance(t){const e=await this.contract.balanceOf(t);return await this.unitsToAmount(null,e,18)}async mint(t,e,a){var i;const r=await this.contract.mint.estimateGas(t,e);return a?r:await it(r,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.mint,t,e)}async batchMint(t,e,a){var i;const r=await this.contract.batchMint.estimateGas(t,e);return a?r:await it(r,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.batchMint,t,e)}async burn(t,e){var a;const i=await this.contract.burn.estimateGas(t);return e?i:await it(i,this.getSignerAccordingSdk(),null==(a=this.config)?void 0:a.gasFeeMultiplier,this.contract.burn,t)}async transferOwnership(t,e){var a;const i=await this.contract.transferOwnership.estimateGas(t);return e?i:await it(i,this.getSignerAccordingSdk(),null==(a=this.config)?void 0:a.gasFeeMultiplier,this.contract.transferOwnership,t)}async renounceOwnership(t){var e;const a=await this.contract.renounceOwnership.estimateGas();return t?a:await it(a,this.getSignerAccordingSdk(),null==(e=this.config)?void 0:e.gasFeeMultiplier,this.contract.renounceOwnership)}}class St extends nt{getDefaultAbi(){return C.abi}constructor(t,e,a,i,r){super(t,e,a,i,r),this.abi=r||this.getDefaultAbi()}async deployAccessListContract(t,e,a,i=!1,r,n,s){if(!t||!e){const{name:a,symbol:i}=wt();t=a,e=i}const o=await this.contract.deployAccessListContract.estimateGas(t,e,i,r,n,a);if(s)return o;try{var c;const s=await it(o,this.getSignerAccordingSdk(),null==(c=this.config)?void 0:c.gasFeeMultiplier,this.contract.deployAccessListContract,t,e,i,r,n,a);if(!s){const t="Tx for deploying new access list was not processed on chain.";throw console.error(t),t}return at(await s.wait(),"NewAccessList").args[0]}catch(t){console.error(`Creation of AccessList failed: ${t}`)}}async getOwner(){return await this.contract.owner()}async isSoulbound(t){return await this.contract.isSoulBound(t)}async isDeployed(t){return await this.contract.isDeployed(t)}async changeTemplateAddress(t,e,a){var i;if(await this.getOwner()!==t)throw new Error("Caller is not Factory Owner");if(e===ot)throw new Error("Template address cannot be ZERO address");const r=await this.contract.changeTemplateAddress.estimateGas(e);return a?r:await it(r,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.changeTemplateAddress,e)}}class Et extends nt{getDefaultAbi(){return x.abi}constructor(t,e,a,i,r){super(t,e,a,i,r),this.abiEnterprise=void 0,this.abi=r||this.getDefaultAbi()}async getFunds(t){return await this.contract.getFunds(t)}async getUserFunds(t,e){return await this.contract.getUserFunds(t,e)}async getUserTokens(t){return await this.contract.getUserTokens(t)}async getLocks(t,e,a){return await this.contract.getLocks(t,e,a)}async getAuthorizations(t,e,a){return await this.contract.getAuthorizations(t,e,a)}async verifyFundsForEscrowPayment(t,e,a,i,r,n,s){var o;const c=await(null==(o=this.signer.provider)?void 0:o.getBalance(d(e)));if(new p(c).isZero())return{isValid:!1,message:"Native token balance is 0. Please add funds"};const l=new kt(this.signer),h=await l.allowance(t,await this.signer.getAddress(),this.contract.target.toString(),s);new p(await this.amountToUnits(t,h,18)).isLessThan(new p(i))&&await l.approve(d(t),d(this.contract.target.toString()),i);const g=await l.balance(t,await this.signer.getAddress());if(new p(g).isZero())return{isValid:!1,message:"Payment token balance is 0. Please add funds"};const w=await this.getAuthorizations(t,await this.signer.getAddress(),e),m=await this.getUserFunds(await this.signer.getAddress(),t);return new p(m[0]).isZero()&&(a&&new p(u(g)).isLessThanOrEqualTo(new p(u(a)))&&new p(u(a)).isGreaterThan(new p(i))?await this.deposit(t,a,s):new p(u(g)).isLessThanOrEqualTo(new p(u(i)))?await this.deposit(t,await this.unitsToAmount(t,i,s),s):await this.deposit(t,g,s)),0===w.length&&await this.authorize(d(t),d(e),(Number(i)/2).toString(),r,n),{isValid:!0,message:""}}async deposit(t,e,a,i){var r;const n=await this.amountToUnits(t,e,a),s=await this.contract.deposit.estimateGas(t,n);return i?s:await it(s,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,this.contract.deposit,t,n)}async withdraw(t,e,a,i){var r;const n=[],s=[];if(t.length!==e.length)throw new Error("Tokens and amounts arrays must have the same length");const o=await this.signer.getAddress();for(let a=0;a<t.length;a++){const i=t[a],r=new p(e[a]),c=await this.getUserFunds(o,i),l=new p(c[0]);r.isGreaterThan(0)&&r.isLessThanOrEqualTo(l)?(n.push(i),s.push(e[a])):console.log(`Insufficient funds for token ${i}`)}const c=await Promise.all(s.map((t,e)=>this.amountToUnits(n[e],t,a))),l=await this.contract.withdraw.estimateGas(t,c);return i?l:await it(l,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,this.contract.withdraw,n,c)}async authorize(t,e,a,i,r,n,s){var o;if(0!==(await this.getAuthorizations(t,await this.signer.getAddress(),e)).length)return console.log(`Payee ${e} already authorized`),null;const c=await this.amountToUnits(t,a,n),l=await this.amountToUnits(t,i,n),d=await this.amountToUnits(t,r,n),u=await this.contract.authorize.estimateGas(t,e,c,l,d);return s?u:await it(u,this.getSignerAccordingSdk(),null==(o=this.config)?void 0:o.gasFeeMultiplier,this.contract.authorize,t,e,c,l,d)}async cancelExpiredLocks(t,e,a,i,r){var n;const s=await this.contract.cancelExpiredLocks.estimateGas(t,e,a,i);return r?s:await it(s,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,this.contract.cancelExpiredLocks,t,e,a,i)}}class At extends nt{getDefaultAbi(){return D.abi}constructor(t,e,a,i,r){super(t,e,a,i,r),this.abi=r||this.getDefaultAbi()}async isTokenAllowed(t){return await this.contract.isTokenAllowed(t)}async getToken(t){return await this.contract.getToken(t)}async calculateFee(t,e,a){const i=this.amountToUnits(t,e.toString(),a),r=await this.contract.calculateFee(t,i);return this.unitsToAmount(t,r,a)}}async function Ft(t){return new Promise(e=>{setTimeout(e,t)})}function Ct(t){return null!=t}async function xt(t,e){const a=h(e);let i=await t._legacySignMessage(a);i=i.substr(2);const r="0x"+i.slice(0,64),n="0x"+i.slice(64,128);let s="0x"+i.slice(128,130);return"0x00"===s&&(s="0x1b"),"0x01"===s&&(s="0x1c"),{v:s,r,s:n}}async function Dt(t,e){const a=o(s(e)),i=h(a);if(!t.provider)throw new Error("Provider is required but not available");const{chainId:r}=await t.provider.getNetwork();try{return await t.signMessage(i)}catch(e){if(_.error("Sign message error: ",e),8996===Number(r))return console.log("Signing message with _legacySignMessage"),await t._legacySignMessage(i)}}class Mt{constructor(t){this.aquariusURL=void 0,this.aquariusURL=t}async resolve(t,e,a){const i=this.aquariusURL+"/api/aquarius/assets/ddo/"+t;try{const t=await M(i,{method:"GET",headers:{"Content-Type":"application/json",Authorization:a},signal:e});if(t.ok)return await t.json();throw new Error("HTTP request failed with status "+t.status)}catch(t){throw _.error(t),new Error("HTTP request failed")}}async waitForIndexer(t,e,a,i=3e4,r=100,n){let s=0;r>500&&(_.warn("Max Limit exceeded, defaulting to 500 retries."),r=500);do{try{const i=this.aquariusURL+"/api/aquarius/assets/ddo/"+t,r=await M(i,{method:"GET",headers:{"Content-Type":"application/json",Authorization:n},signal:a});if(r.ok){const t=await r.json(),a=O.getDDOClass(t),{indexedMetadata:i}=a.getAssetFields();if(!e)return t;if(i.event&&i.event.txid===e)return t}}catch(t){}await Ft(i),s++}while(s<r);return null}async validate(t,e,a,i,r){const n=a+"/api/aquarius/assets/ddo/validate",s=a+"/api/services/nonce";try{const a=await e.getAddress(),o=await M(s+`?userAddress=${a}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:r},signal:i});let{nonce:c}=await o.json();console.log(`[getNonce] Consumer: ${a} nonce: ${c}`),c&&null!==c||(c="0");const l=(Number(c)+1).toString(),d=a+l,u={ddo:t,publisherAddress:a,nonce:l,signature:await Dt(e,d)},h=await M(n,{method:"POST",body:JSON.stringify(u),headers:{"Content-Type":"application/octet-stream",Authorization:r},signal:i}),g=await h.json();if(200!==h.status)throw new Error("Metadata validation failed");return console.log("Ddo successfully validated"),{valid:!0,hash:g.hash,proof:{validatorAddress:g.publicKey,r:g.r[0],s:g.s[0],v:g.v}}}catch(t){_.error("Metadata validation failed",t.message)}}async getAssetMetadata(t,e,a){const i=this.aquariusURL+"/api/aquarius/assets/metadata/"+t;try{const t=await M(i,{method:"GET",headers:{"Content-Type":"application/json",Authorization:a},signal:e});if(t.ok)return t.json();throw new Error("getAssetMetadata failed: "+t.status+t.statusText)}catch(t){throw _.error("Error getting metadata: ",t),new Error("Error getting metadata: "+t)}}async querySearch(t,e,a){const i=this.aquariusURL+"/api/aquarius/assets/query";try{const r=await M(i,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/json",Authorization:a},signal:e});if(r.ok)return r.json();throw new Error("querySearch failed: "+r.status+r.statusText)}catch(t){throw _.error("Error querying metadata: ",t),new Error("Error querying metadata: "+t)}}}class Ot{async getConsumerAddress(t){return"string"==typeof t?function(t){try{return N.decode(t,{json:!0})}catch(t){throw new Error("Error decoding JWT")}}(t).address:await t.getAddress()}async getSignature(t,e){return"string"==typeof t?null:await this.signProviderRequest(t,e)}getAuthorization(t){return"string"==typeof t?t:void 0}async getEndpoints(t,e){try{const a=await this.getData(t,e);return await a.json()}catch(t){throw _.error("Finding the service endpoints failed:",t),new Error("HTTP request failed calling Provider")}}getEndpointURL(t,e){return t?t.find(t=>t.serviceName.toLowerCase()===e.toLowerCase()):null}async getServiceEndpoints(t,e){const a=[];for(const i in e.serviceEndpoints){const r={serviceName:i,method:e.serviceEndpoints[i][0],urlPath:t.replace(/\/+$/,"")+"/"+e.serviceEndpoints[i][1].replace(/^\/+/,"")};a.push(r)}return a}async getNonce(t,e,a,i,r){i||(i=await this.getEndpoints(t)),r||(r=await this.getServiceEndpoints(t,i));const n=this.getEndpointURL(r,"nonce")?this.getEndpointURL(r,"nonce").urlPath:null;if(!n)return null;try{const t=await M(n+`?userAddress=${e}`,{method:"GET",headers:{"Content-Type":"application/json"},signal:a}),{nonce:i}=await t.json();return console.log(`[getNonce] Consumer: ${e} nonce: ${i}`),i&&null!==i?Number(i):0}catch(t){throw _.error(t),new Error(t.message)}}async signProviderRequest(t,e){const i=a.solidityPackedKeccak256(["bytes"],[a.hexlify(a.toUtf8Bytes(e))]),r=a.toBeArray(i);try{return await t.signMessage(r)}catch(e){const a=await t.provider.getNetwork();if(8996===Number(a.chainId))return await t._legacySignMessage(r)}}async encrypt(t,e,a,i,r,n){const s=await this.getEndpoints(a),o=await this.getServiceEndpoints(a,s),c=await this.getConsumerAddress(i),l=(await this.getNonce(a,c,n,s,o)+1).toString(),d=String(l),u=await this.getSignature(i,d);let h=(this.getEndpointURL(o,"encrypt")?this.getEndpointURL(o,"encrypt").urlPath:null)+`?chainId=${e}`;if(!h)return null;h+=`&nonce=${l}`,h+=`&consumerAddress=${c}`,h+=`&signature=${u}`;try{const e=await M(h,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/octet-stream"},signal:n});return await e.text()}catch(t){throw _.error(t),new Error("HTTP request failed calling Provider")}}async checkDidFiles(t,e,a,i=!1,r){var n;const s=await this.getEndpoints(a),o=await this.getServiceEndpoints(a,s),c={did:t,serviceId:e,checksum:i},l=[],d=this.getEndpointURL(o,"fileinfo")?this.getEndpointURL(o,"fileinfo").urlPath:null;if(!d)return null;let u;try{u=await M(d,{method:"POST",body:JSON.stringify(c),headers:{"Content-Type":"application/json"},signal:r})}catch(t){throw _.error("File info call failed: "),_.error(t),new Error(t)}if(null!=(n=u)&&n.ok){const t=await u.json();for(const e of t)l.push(e);return l}const h=await u.json();throw _.error("File info call failed: ",u.status,u.statusText,h),new Error(JSON.stringify(h))}async getFileInfo(t,e,a=!1,i){var r;const n=await this.getEndpoints(e),s=await this.getServiceEndpoints(e,n),o=G({},t,{checksum:a}),c=[],l=this.getEndpointURL(s,"fileinfo")?this.getEndpointURL(s,"fileinfo").urlPath:null;if(!l)return null;let d;try{d=await M(l,{method:"POST",body:JSON.stringify(o),headers:{"Content-Type":"application/json"},signal:i})}catch(t){throw _.error("File info call failed: "),_.error(t),new Error(t)}if(null!=(r=d)&&r.ok){const t=await d.json();for(const e of t)c.push(e);return c}const u=await d.json();throw _.error("File info call failed: ",d.status,d.statusText,u),new Error(JSON.stringify(u))}async getComputeEnvironments(t,e){var a,i;const r=await this.getEndpoints(t),n=await this.getServiceEndpoints(t,r),s=null==(a=this.getEndpointURL(n,"computeEnvironments"))?void 0:a.urlPath;if(!s)return null;let o;try{o=await M(s,{method:"GET",headers:{"Content-Type":"application/json"},signal:e})}catch(t){throw _.error("Fetch compute env failed: "),_.error(t),new Error(t)}if(null!=(i=o)&&i.ok)return o.json();const c=await o.json();throw _.error("Fetch compute env failed: ",o.status,o.statusText,c),new Error(JSON.stringify(c))}async initialize(t,e,a,i,r,n,s,o,c){var l;const d=await this.getEndpoints(r),u=await this.getServiceEndpoints(r,d);let h,g=this.getEndpointURL(u,"initialize")?this.getEndpointURL(u,"initialize").urlPath:null;if(!g)return null;g+=`?documentId=${t}`,g+=`&serviceId=${e}`,g+=`&fileIndex=${a}`,g+=`&consumerAddress=${i}`,s&&(g+="&userdata="+encodeURI(JSON.stringify(s))),o&&(g+="&environment="+encodeURI(o)),c&&(g+="&validUntil="+c);try{h=await M(g,{method:"GET",headers:{"Content-Type":"application/json"},signal:n})}catch(t){throw _.error("Provider initialized failed: "),_.error(t),new Error(`Provider initialize failed url: ${g} `)}if(200===(null==(l=h)?void 0:l.status))return await h.json();const w=await h.json();throw _.error("Provider initialized failed: ",h.status,h.statusText,w),new Error(JSON.stringify(w))}async initializeComputeV1(t,e,a,i,r,n,s,o,c){var l;const d=await this.getEndpoints(i),u=await this.getServiceEndpoints(i,d),h={datasets:t,algorithm:e,payment:{chainId:n,token:s,maxJobDuration:o},consumerAddress:r,environment:a},g=this.getEndpointURL(u,"initializeCompute")?this.getEndpointURL(u,"initializeCompute").urlPath:null;if(!g)return null;let w;try{w=await M(g,{method:"POST",body:JSON.stringify(h),headers:{"Content-Type":"application/json"},signal:c})}catch(t){throw _.error("Initialize compute failed: "),_.error(t),new Error("ComputeJob cannot be initialized")}if(null!=(l=w)&&l.ok)return await w.json();const p=await w.json();throw _.error("Initialize compute failed: ",w.status,w.statusText,p),_.error("Payload was:",JSON.stringify(h)),new Error(JSON.stringify(p))}async initializeCompute(t,e,a,i,r,n,s,o,c,l,d){var u,h;const g=await this.getEndpoints(n),w=await this.getServiceEndpoints(n,g),p=this.getEndpointURL(w,"initializeCompute")?this.getEndpointURL(w,"initializeCompute").urlPath:null;if(!p)return null;const m=await this.getConsumerAddress(s),f=(await this.getNonce(n,m,d,g,w)+1).toString();let y=m;y+=null==(u=t[0])?void 0:u.documentId,y+=f;const v={datasets:t,algorithm:e,environment:a,payment:{chainId:c,token:i,resources:o},maxJobDuration:r,consumerAddress:m,signature:await this.getSignature(s,y)};let k;l&&(v.policyServer=l);try{if(console.log("Initialize compute url:",p),k=await M(p,{method:"POST",body:JSON.stringify(v),headers:{"Content-Type":"application/json",Authorization:this.getAuthorization(s)},signal:d}),console.log("Raw response:",k),!k.ok){const t=await k.text();throw new Error(`${t}`)}}catch(t){throw _.error("Initialize compute failed: "),_.error(t),new Error(`ComputeJob cannot be initialized: ${t.message}.`)}if(null!=(h=k)&&h.ok)return await k.json();const T=await k.json();throw _.error("Initialize compute failed: ",k.status,k.statusText,T),_.error("Payload was:",JSON.stringify(v)),new Error(JSON.stringify(T))}async getDownloadUrl(t,e,a,i,r,n,s,o){const c=await this.getEndpoints(r),l=await this.getServiceEndpoints(r,c),d=this.getEndpointURL(l,"download")?this.getEndpointURL(l,"download").urlPath:null;if(!d)return null;const u=await this.getConsumerAddress(n),h=(await this.getNonce(r,u,null,c,l)+1).toString(),g=await this.getSignature(n,t+h);let w=d;return w+=`?fileIndex=${a}`,w+=`&documentId=${t}`,w+=`&transferTxId=${i}`,w+=`&serviceId=${e}`,w+=`&consumerAddress=${u}`,w+=`&nonce=${h}`,s&&(w+="&policyServer="+encodeURI(JSON.stringify(s))),w+=`&signature=${g}`,o&&(w+="&userdata="+encodeURI(JSON.stringify(o))),w}async computeStartV1(t,e,a,i,r,n,s,o){var c;const l=await this.getEndpoints(t),d=await this.getServiceEndpoints(t,l),u=this.getEndpointURL(d,"computeStart")?this.getEndpointURL(d,"computeStart").urlPath:null,h=await e.getAddress(),g=(await this.getNonce(t,h,n,l,d)+1).toString();let w=h;w+=i.documentId,w+=g;const p=await this.signProviderRequest(e,w),m=Object();if(m.consumerAddress=h,m.signature=p,m.nonce=g,m.environment=a,m.dataset=i,m.algorithm=r,s&&(m.additionalDatasets=s),o&&(m.output=o),!u)return null;let f;try{f=await M(u,{method:"POST",body:JSON.stringify(m),headers:{"Content-Type":"application/json"},signal:n})}catch(t){throw _.error("Compute start failed:"),_.error(t),_.error("Payload was:",m),new Error("HTTP request failed calling Provider")}return null!=(c=f)&&c.ok?await f.json():(_.error("Compute start failed: ",f.status,f.statusText,await f.json()),_.error("Payload was:",m),null)}async computeStart(t,e,a,i,r,n,s,o,c,l,d,u,h,g,w){var p,m;console.log("called new compute start method..."),console.log("datasets: ",i),console.log("algorithm: ",r);const f=await this.getEndpoints(t),y=await this.getServiceEndpoints(t,f),v=this.getEndpointURL(y,"computeStart")?this.getEndpointURL(y,"computeStart").urlPath:null;if(!v)return _.error("Compute start failed: Cannot get proper computeStart route (perhaps not implemented on provider?)"),null;const k=await this.getConsumerAddress(e),T=(await this.getNonce(t,k,g,f,y)+1).toString(),b=String(k+(null==(p=i[0])?void 0:p.documentId)+T),S=await this.getSignature(e,b),E=Object();let A;E.consumerAddress=k,E.signature=S,E.nonce=T,E.environment=a,E.maxJobDuration=n,E.resources=o,E.dataset=i[0],E.datasets=i,E.algorithm=r,E.chainId=c,E.payment={chainId:c,token:s,maxJobDuration:n},o&&(E.resources=o),l&&(E.metadata=l),d&&(E.additionalViewers=d),u&&(E.output=u),h&&(E.policyServer=h),w&&(E.queueMaxWaitTime=w);try{A=await M(v,{method:"POST",body:JSON.stringify(E),headers:{"Content-Type":"application/json",Authorization:this.getAuthorization(e)},signal:g})}catch(t){throw _.error("Compute start failed:"),_.error(t),_.error("Payload was:",E),new Error("HTTP request failed calling Provider")}if(null!=(m=A)&&m.ok)return await A.json();const F=await A.json();throw _.error("Compute start failed: ",A.status,A.statusText,F),_.error("Payload was:",E),new Error(JSON.stringify(F))}async freeComputeStart(t,e,a,i,r,n,s,o,c,l,d,u){var h;console.log("called new free compute start method..."),console.log("datasets: ",i),console.log("algorithm: ",r);const g=await this.getEndpoints(t),w=await this.getServiceEndpoints(t,g),p=this.getEndpointURL(w,"freeCompute")?this.getEndpointURL(w,"freeCompute").urlPath:null;if(!p)return _.error("Compute start failed: Cannot get proper computeStart route (perhaps not implemented on provider?)"),null;const m=await this.getConsumerAddress(e),f=(await this.getNonce(t,m,d,g,w)+1).toString(),y=f;console.log("signatureMessage: ",y);const v=await this.getSignature(e,y),k=Object();let T;k.consumerAddress=m,k.signature=v,k.nonce=f,k.environment=a,k.resources=n,k.dataset=i[0],k.datasets=i,k.algorithm=r,s&&(k.metadata=s),o&&(k.additionalViewers=o),k.output=c,l&&(k.policyServer=l),u&&(k.queueMaxWaitTime=u);try{T=await M(p,{method:"POST",body:JSON.stringify(k),headers:{"Content-Type":"application/json",Authorization:this.getAuthorization(e)},signal:d})}catch(t){throw _.error("Compute start failed:"),_.error(t),_.error("Payload was:",k),new Error("HTTP request failed calling Provider")}if(null!=(h=T)&&h.ok)return await T.json();const b=await T.json();throw _.error("Compute start failed: ",T.status,T.statusText,b),_.error("Payload was:",k),new Error(JSON.stringify(b))}async computeStreamableLogs(t,e,a,i){var r,n;const s="string"==typeof e,o=await this.getEndpoints(t),c=await this.getServiceEndpoints(t,o),l=this.getEndpointURL(c,"computeStreamableLogs")?this.getEndpointURL(c,"computeStreamableLogs").urlPath:null;if(!l)return _.error("Compute start failed: Cannot get proper computeStreamableLogs route (perhaps not implemented on provider?)"),null;const d=await this.getConsumerAddress(e),u=(await this.getNonce(t,d,i,o,c)+1).toString();let h,g=`?consumerAddress=${d}&jobId=${a}`;if(!s){const t=`${d}${a}${u}`;g+=`&signature=${await this.getSignature(e,t)}`,g+=`&nonce=${u}`}try{h=await M(l+g,{method:"GET",headers:{"Content-Type":"application/json",Authorization:this.getAuthorization(e)},signal:i}),console.log("Raw response:",h)}catch(t){throw _.error("computeStreamableLogs failed:"),_.error(t),new Error("HTTP request failed calling Provider")}return null!=(r=h)&&r.ok||200===(null==(n=h)?void 0:n.status)?(console.log("Response body:",h.body),h.body):(_.error("computeStreamableLogs failed: ",h.status,h.statusText,await h.json()),null)}async getComputeStartRoutes(t,e=!1){const a=await this.getEndpoints(t),i=await this.getServiceEndpoints(t,a);let r=null;return r=e?this.getEndpointURL(i,"freeCompute")?this.getEndpointURL(i,"freeCompute").urlPath:null:this.getEndpointURL(i,"computeStart")?this.getEndpointURL(i,"computeStart").urlPath:null,r}async computeStop(t,e,a,i,r){var n;const s="string"==typeof a,o=await this.getEndpoints(e),c=await this.getServiceEndpoints(e,o),l=this.getEndpointURL(c,"computeStop")?this.getEndpointURL(c,"computeStop").urlPath:null,d=await this.getConsumerAddress(a),u=(await this.getNonce(e,d,r,o,c)+1).toString(),h=d+(t||""),g=await this.getSignature(a,h),w=new URLSearchParams;w.set("consumerAddress",d),w.set("nonce",u),w.set("jobId",t),s||w.set("signature",g),i&&w.set("agreementId",i);const p=w.toString();if(!p)return null;let m;try{m=await M(l+"?"+p,{method:"PUT",headers:{"Content-Type":"application/json",Authorization:this.getAuthorization(a)},signal:r})}catch(t){throw _.error("Compute stop failed:"),_.error(t),new Error("HTTP request failed calling Provider")}if(null!=(n=m)&&n.ok)return await m.json();const f=await m.json();throw _.error("Compute stop failed: ",m.status,m.statusText,f),new Error(JSON.stringify(f))}async computeStatus(t,e,a,i,r,n){var s,o;const c=await this.getEndpoints(t),l=await this.getServiceEndpoints(t,c),d=this.getEndpointURL(l,"computeStatus")?this.getEndpointURL(l,"computeStatus").urlPath:null;let u,h=`?consumerAddress=${e}`;if(h+=i&&`&agreementId=${i}`||"",h+=a&&`&jobId=${a}`||"",!d)return null;try{console.log("computeStatusUrl: ",d+h),u=await M(d+h,{method:"GET",headers:{"Content-Type":"application/json",Authorization:n},signal:r})}catch(t){throw _.error("Get compute status failed"),_.error(t),new Error(t)}if(null!=(s=u)&&s.ok)return await u.json();if(_.error("Get compute status failed:",u.status,u.statusText),null!=(o=u)&&o.ok)return await u.json();const g=await u.json();throw _.error("Get compute status failed:",u.status,u.statusText,g),new Error(JSON.stringify(g))}async getComputeResultUrl(t,e,a,i){const r="string"==typeof e,n=await this.getEndpoints(t),s=await this.getServiceEndpoints(t,n),o=this.getEndpointURL(s,"computeResult")?this.getEndpointURL(s,"computeResult").urlPath:null,c=await this.getConsumerAddress(e),l=(await this.getNonce(t,c,null,n,s)+1).toString();let d=c;d+=a,d+=i.toString(),d+=l;const u=await this.getSignature(e,d);if(!o)return null;let h=o;return h+=`?consumerAddress=${c}`,h+=`&jobId=${a}`,h+=`&index=${i.toString()}`,r||(h+=`&nonce=${l}`,h+=`&signature=${u}`),h}async computeDelete(t,e,a,i,r){var n;const s=await this.getEndpoints(i),o=await this.getServiceEndpoints(i,s),c=this.getEndpointURL(o,"computeDelete")?this.getEndpointURL(o,"computeDelete").urlPath:null,l=await this.getConsumerAddress(e),d=(await this.getNonce(i,l,r,s,o)+1).toString();let u=l;u+=a||"",u+=t&&`${this.noZeroX(t)}`||"",u+=d;const h=await this.getSignature(e,u),g=Object();if(g.documentId=t,g.consumerAddress=l,g.jobId=a,h&&(g.signature=h),!c)return null;let w;try{w=await M(c,{method:"DELETE",body:JSON.stringify(g),headers:{"Content-Type":"application/json",Authorization:this.getAuthorization(e)},signal:r})}catch(t){throw _.error("Delete compute job failed:"),_.error(t),_.error("Payload was:",g),new Error("HTTP request failed calling Provider")}if(null!=(n=w)&&n.ok)return await w.json();const p=await w.json();throw _.error("Delete compute job failed:",w.status,w.statusText,p),_.error("Payload was:",g),new Error(JSON.stringify(p))}async generateAuthToken(t,e,a){const i=await t.getAddress(),r=await this.getEndpoints(e),n=await this.getServiceEndpoints(e,r),s=this.getEndpointURL(n,"generateAuthToken").urlPath||null,o=(await this.getNonce(e,i,a,r,n)+1).toString(),c=i+o,l=await this.signProviderRequest(t,c);try{const t=await M(s,{method:"POST",body:JSON.stringify({address:i,signature:l,nonce:o}),headers:{"Content-Type":"application/json"},signal:a});if(null==t||!t.ok)throw new Error(`Failed to generate auth token: ${t.status} ${t.statusText}`);const e=await t.json();return null==e?void 0:e.token}catch(t){throw _.error("Generate auth token failed:"),_.error(t),new Error("HTTP request failed calling Provider")}}async invalidateAuthToken(t,e,a,i){const r=await t.getAddress(),n=await this.getEndpoints(a),s=await this.getServiceEndpoints(a,n),o=this.getEndpointURL(s,"invalidateAuthToken").urlPath||null,c=(await this.getNonce(a,r,i,n,s)+1).toString(),l=r+c,d=await this.signProviderRequest(t,l);try{const t=await M(o,{method:"POST",body:JSON.stringify({address:r,signature:d,token:e,nonce:c}),headers:{"Content-Type":"application/json"},signal:i});if(null==t||!t.ok)throw new Error(`Failed to invalidate auth token: ${t.status} ${t.statusText}`);return await t.json()}catch(t){throw _.error("Generate auth token failed:"),_.error(t),new Error("HTTP request failed calling Provider")}}async isValidProvider(t,e){try{const a=await M(t,{method:"GET",headers:{"Content-Type":"application/json"},signal:e});if(null!=a&&a.ok){const t=await a.json();if(t&&(t.providerAddress||t.providerAddresses))return!0}return!1}catch(t){return _.error(`Error validating provider: ${t.message}`),!1}}async PolicyServerPassthrough(t,e,a){var i;const r=await this.getEndpoints(t),n=await this.getServiceEndpoints(t,r),s=this.getEndpointURL(n,"PolicyServerPassthrough")?this.getEndpointURL(n,"PolicyServerPassthrough").urlPath:null;if(!s)return null;let o;try{if(o=await M(s,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/json"},signal:a}),!o.ok){const t=await o.text();throw new Error(`${t}`)}}catch(t){throw _.error("PolicyServerPassthrough failed: "),_.error(t),new Error(`PolicyServerPassthrough failed: ${t.message}.`)}if(null!=(i=o)&&i.ok)return await o.json();const c=await o.json();throw _.error("PolicyServerPassthrough failed: ",o.status,o.statusText,c),_.error("Payload was:",JSON.stringify(e)),new Error(JSON.stringify(c))}async initializePSVerification(t,e,a){var i;const r=await this.getEndpoints(t),n=await this.getServiceEndpoints(t,r),s=this.getEndpointURL(n,"initializePSVerification")?this.getEndpointURL(n,"initializePSVerification").urlPath:null;if(!s)return null;let o;try{if(o=await M(s,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/json"},signal:a}),!o.ok){const t=await o.text();throw new Error(`${t}`)}}catch(t){throw _.error("initializePSVerification failed: "),_.error(t),new Error(`initializePSVerification failed: ${t.message}.`)}if(null!=(i=o)&&i.ok)return await o.json();const c=await o.json();throw _.error("initializePSVerification failed: ",o.status,o.statusText,c),_.error("Payload was:",JSON.stringify(e)),new Error(JSON.stringify(c))}async downloadNodeLogs(t,e,a,i,r,n,s,o,c){var l;const d=await this.getEndpoints(t),u=await this.getServiceEndpoints(t,d),h=this.getEndpointURL(u,"logs")?this.getEndpointURL(u,"logs").urlPath:null;if(!h)return _.error("Download node logs failed: Cannot get proper logs route (perhaps not implemented on provider?)"),null;const g=Date.now()+3e5,w=await e.signMessage(g.toString());let p,m=h+`?startTime=${a}&endTime=${i}`;r&&(m+=`&maxLogs=${r}`),n&&(m+=`&moduleName=${n}`),s&&(m+=`&level=${s}`),o&&(m+=`&page=${o}`);try{p=await M(m,{method:"POST",body:JSON.stringify({signature:w,expiryTimestamp:g}),headers:{"Content-Type":"application/json"},signal:c})}catch(t){throw _.error("Download node logs failed:"),_.error(t),new Error("HTTP request failed calling Provider")}if(null!=(l=p)&&l.ok)return p.body;const f=await p.json();throw _.error("Download node logs failed: ",p.status,p.statusText,f),new Error(JSON.stringify(f))}noZeroX(t){return this.zeroXTransformer(t,!1)}zeroXTransformer(t="",e){const{valid:a,output:i}=this.inputMatch(t,/^(?:0x)*([a-f0-9]+)$/i,"zeroXTransformer");return(e&&a?"0x":"")+i}inputMatch(t,e,a){if("string"!=typeof t)throw _.debug("Not input string:"),_.debug(t),new Error(`[${a}] Expected string, input type: ${typeof t}`);const i=t.match(e);return i?{valid:!0,output:i[1]}:(_.warn(`[${a}] Input transformation failed.`),{valid:!1,output:t})}async getData(t,e){return M(t,{method:"GET",headers:{"Content-type":"application/json",Authorization:e}})}}const Nt=new Ot;function Pt(t,e){return t=d(t),`did:op:${P(t+e.toString(10)).toString()}`}function Rt(t){return P(t).toString()}function Ut(t){const e=new XMLHttpRequest;e.responseType="blob",e.open("GET",t),e.onload=()=>{const t=e.getResponseHeader("content-disposition"),a=null==t?void 0:t.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/),i=a&&a[1]?a[1]:"file",r=window.URL.createObjectURL(e.response),n=document.createElement("a");n.href=r,n.setAttribute("download",i),document.body.appendChild(n),n.click(),n.remove(),window.URL.revokeObjectURL(r)},e.send()}async function It(t,e){const a=await fetch(t);if(!a.ok)throw new Error("Response error.");let i;try{i=a.headers.get("content-disposition").match(/attachment;filename=(.+)/)[1]}catch(a){try{i=t.split("/").pop()}catch(t){i=`file${e}`}}return{data:await a.arrayBuffer(),filename:i}}async function Lt(t,e,i,r,n,s,o=!1,c,l){const d=new a.Contract(r,W,t);if(!o){const e=await $t(t,r,i,n);if(new m(e).greaterThanOrEqualTo(new m(s)))return new m(e).toNumber()}const u=await et(t,r,s,c),h=await d.approve.estimateGas(n,u);return l?new m(h.toString()):await it(h,t,null==e?void 0:e.gasFeeMultiplier,d.approve,n,u)}async function jt(t,e,i,r,n,s,o=!1,c){const l=new a.Contract(r,W,t);if(!o){const e=await zt(t,r,i,n);if(new p(e).isGreaterThan(new p(s)))return BigInt(e)}let d=null;const u=await l.approve.estimateGas(n,s);if(c)return u;try{d=await it(u,t,null==e?void 0:e.gasFeeMultiplier,l.approve,n,s)}catch(t){_.error(`ERROR: Failed to approve spender to spend tokens : ${t.message}`)}return d}async function Gt(t,e,i,r,n,s,o){const c=new a.Contract(i,W,t),l=await et(t,i,n,s),d=await c.transfer.estimateGas(r,l);return o?d:await it(d,t,null==e?void 0:e.gasFeeMultiplier,c.transfer,r,l)}async function $t(t,e,i,r,n){const s=new a.Contract(e,W,t),o=await s.allowance(i,r);return await tt(t,e,o,n)}async function _t(t,e,i,r){const n=new a.Contract(e,W,t),s=await n.balanceOf(i);return await tt(t,e,s,r)}async function zt(t,e,i,r){const n=new a.Contract(e,W,t);return await n.allowance(i,r)}async function Bt(t,e){const i=new a.Contract(e,W,t),r=await i.decimals();return Number(r)}const qt={datasets:{invalid:"Datasets is not a list, as expected"},algorithm:{serviceId:{missing:"The serviceId key is missing from the algorithm s DDO.",not_found:"The provided serviceId does not exist.",service_not_access_compute:"Service type is neither access, nor compute.",main_service_compute:"If the main service is not compute for this asset when calling initialize endpoint.",compute_services_not_in_same_provider:"Files attached to the compute service are not decrypted by the correct provider. This occurs when both asset and algorithm are requested by their compute service which cannot be decrypted by a single provider as how it is supposed to be."},container:{checksum_prefix:"Container checksum does not start with the prefix sha256:.",mising_entrypoint_image_checksum:"Either entrypoint, either image, or either checksum are missing from the container dictionary from the algorithm s DDO."},documentId:{did_not_found:"The algorithm s DID could not be retrieved from the metadata store, because the algorithm asset does not exist.",missing:"The documentId key is missing from the algorithm s DDO."},transferTxId:{missing:"The transferTxId key is missing from the algorithm s DDO."},missing_meta_documentId:"Either algorithm metadata, or algorithm DID are missing.",did_not_found:"Either algorithm metadata, or algorithm DID are missing.",not_algo:"Either algorithm metadata, or algorithm DID are missing.",in_use_or_not_on_chain:"Either algorithm metadata, or algorithm DID are missing.",meta_oneof_url_rawcode_remote:"Either algorithm metadata, or algorithm DID are missing.",file_unavailable:"One possibility is that the asset could not be retrieved from Aquariuss database. Otherwise, there are issues related to services"},error:{not_trusted_algo_publisher:"The owner of the algorithm's DDO is not a trusted algorithms publishers list.",not_trusted_algo:"The algorithm's DID is not in the asset's trusted algorithms dictionary. ",no_publisherTrustedAlgorithms:"The algorithm's key publisherTrustedAlgorithms does not exist in the algorithm's DDO.",algorithm_file_checksum_mismatch:"filesChecksum from the algorithm's DDO is invalid.",algorithm_container_checksum_mismatch:"The containerChecksum from the algorithm's DDO is invalid.",no_raw_algo_allowed:"The asset does not allow raw algorithms to be run on it.","Asset malformed":"The asset published on chain is malformed, missing some required keys or not compliant with our schemas.","Asset is not consumable.":"Assets metadata status is not in the range of valid status codes for assets. The recognized states for the metadata are defined on our docs.","DID is not a valid algorithm.":"Either the algorithm assets DID is incorrectly typed, either the algorithm timeout expired.","Compute environment does not exist.":"The compute environment provided by the user does not exist, it is not served by our compute-to-data feature. The user can use get_c2d_environments to check the list of available compute environments.","The validUntil value is not correct.":"validUntil value is most probably expired.","Cannot resolve DID":"The dataset DID does not exist in the Metadata store.","Invalid serviceId":"The serviceId of that dataset is not correct.","Unable to get dataset files":"The files of that dataset could not be decrypted or retrieved","cannot decrypt files for this service.":"The files of that dataset could not be decrypted due to the fact that file object, which contains the structure and the type of specific file, is missing from the validation part.","Unsupported type ":"The file object type is not supported by Provider.","malformed file object":"The file object structure is invalid and does not contain the wanted information for the specific file."},order:{fees_not_paid:" Provider fees are not paid."},output:{invalid:"The algorithms validation after the build stage has not been decoded properly as a dictionary."}};function Jt(t){try{const a=JSON.parse(t),i=Object.keys(a)[0];if("error"===i){var e;const t=a[i];return(null==(e=qt[i])?void 0:e[t])||`Provider request failed: ${t}`}{const t=a[i];return`${a[Object.keys(a)[1]]} : ${t}`}}catch(e){return _.error("[getErrorMessage] error: ",e),t}}async function Wt(t,e,a,i,r,n,s,o,c="0",l=0,d=0,u=0){const h=O.getDDOClass(t),{datatokens:g}=h.getAssetFields(),{chainId:w,services:p}=h.getDDOFields();s||(s={consumeMarketFeeAddress:"0x0000000000000000000000000000000000000000",consumeMarketFeeAmount:"0",consumeMarketFeeToken:"0x0000000000000000000000000000000000000000"});const f=(await e.provider.getNetwork()).chainId;if(w!==Number(f))throw new Error("Chain ID from DDO is different than the configured network.");if(!g[l].address)throw new Error(`The datatoken with index: ${l} does not exist for the asset with did: ${t.id}`);if(!p[d].id)throw new Error(`There is no service with index: ${d} defined for the asset with did: ${t.id}`);const y=await i.getId(g[l].address),v=await i.getFixedRates(g[l].address),k=await i.getDispensers(g[l].address),T=await i.getPublishingMarketFee(g[l].address),b=v.length>0?"fixed":k.length>0?"free":"NOT_ALLOWED",S=o||(await Nt.initialize(t.id,p[d].id,0,await e.getAddress(),r||a.oceanNodeUri)).providerFee;if(S&&S.providerFeeAddress!==ot&&S.providerFeeAmount&&parseInt(S.providerFeeAmount)>0)try{await jt(e,a,await e.getAddress(),S.providerFeeToken,p[0].datatokenAddress,S.providerFeeAmount)}catch(t){throw new Error(`Failed to approve provider fee token ${S.providerFeeToken}`)}const E={consumer:n||await e.getAddress(),serviceIndex:d,_providerFee:S,_consumeMarketFee:s};switch(b){case"free":if(1===y){const t=new st(a.dispenserAddress,e),r=await t.dispense(g[l].address,"1",await e.getAddress());if(!r)throw new Error("Failed to dispense !");return await r.wait(),await i.startOrder(g[l].address,E.consumer,E.serviceIndex,E._providerFee,E._consumeMarketFee)}if(2===y||4===y)return await i.buyFromDispenserAndOrder(p[d].datatokenAddress,E,a.dispenserAddress);break;case"fixed":{const r=new ut(a.fixedRateExchangeAddress,e);if(!v[u].id)throw new Error(`There is no fixed rate exchange with index: ${d} for the asset with did: ${t.id}`);const n=await r.getFeesInfo(v[u].id),o=await r.getExchange(v[u].id),{baseTokenAmount:h}=await r.calcBaseInGivenDatatokensOut(n.exchangeId,"1",s.consumeMarketFeeAmount),w=new m(+h||0).add(new m(s.consumeMarketFeeAmount||0)).add(new m(+T.publishMarketFeeAmount||0)).toString(),p={exchangeContract:a.fixedRateExchangeAddress,exchangeId:n.exchangeId,maxBaseTokenAmount:w,baseTokenAddress:o.baseToken,baseTokenDecimals:parseInt(o.btDecimals)||18,swapMarketFee:c,marketFeeAddress:T.publishMarketFeeAddress};if(1===y){const t=await Lt(e,a,await e.getAddress(),o.baseToken,a.fixedRateExchangeAddress,w,!1);if(!("number"!=typeof t?await t.wait():t))throw new Error(`Failed to approve ${o.baseToken} !`);const n=await r.buyDatatokens(o.exchangeId,"1",w,T.publishMarketFeeAddress,c);if(!await n.wait())throw new Error("Failed to buy datatoken from fixed rate!");return await i.startOrder(g[l].address,E.consumer,E.serviceIndex,E._providerFee,E._consumeMarketFee)}if(2===y||4===y){const t=await Lt(e,a,await e.getAddress(),o.baseToken,g[l].address,w,!1);if(!t)throw new Error(`Failed to approve ${o.baseToken} !`);if(!("number"!=typeof t?await t.wait():t))throw new Error("Failed to confirm/mine approval transaction!");return await i.buyFromFreAndOrder(g[l].address,E,p)}break}default:throw new Error("Pricing schema not supported !")}}const Vt=8996;function Ht(t){const e=(new J).getConfig(t);return e&&"oasis"===e.sdk}async function Zt(t,e,i,r,n,o,l=!0,d,u,h,w,p,m,f,y){var v,k,T;const b=O.getDDOClass(o),{indexedMetadata:S}=b.getAssetFields(),E=(null==(v=b.getDDOData())||null==(v=v.stats)||null==(v=v.price)?void 0:v.value)||(null==S||null==(k=S.stats[0])||null==(k=k.prices[0])?void 0:k.price);let{chainId:F,nftAddress:C}=b.getDDOFields();const{services:x}=b.getDDOFields();if("string"!=typeof n&&"number"!=typeof n)throw new Error('Invalid template! Must be a "number" or a "string"');const D=(await i.provider.getNetwork()).chainId;if(F&&F!==Number(D))throw new Error("Chain ID from DDO is different than the configured network.");const M=(new J).getConfig(parseInt(String(D)));let N=await yt(i,M.nftFactoryAddress,n,Number(D));if(N<1){if(8996!==Number(D))throw new Error(`Invalid template index: ${N}`);N=1}const P=new vt(i,Number(D)),I=new pt(M.nftFactoryAddress,i,Number(D)),L=await i.getAddress(),j={name:t,symbol:e,templateIndex:1,tokenURI:"aaa",transferable:!0,owner:L},G={templateIndex:N,cap:"100000",feeAmount:"0",paymentCollector:L,feeToken:u||M.oceanTokenAddress,minter:L,mpFeeAddress:ot};let $;null!=r&&r.files[0].type&&[U.ARWEAVE,U.IPFS,U.URL].includes(null==r||null==(T=r.files[0])||null==(T=T.type)?void 0:T.toLowerCase())||(console.log('Missing or invalid files object type, defaulting to "url"'),r.type=U.URL),"oasis"===M.sdk&&(G.filesObject=r,G.accessListFactory=w||M.accessListFactory,G.allowAccessList=p,G.denyAccessList=m);try{if(E)if("0"===E.toString()){const t={dispenserAddress:M.dispenserAddress,maxTokens:"1",maxBalance:"100000000",withMint:!0,allowedSwapper:ot};$=await I.createNftWithDatatokenWithDispenser(j,G,t)}else{const t=f||M.oceanTokenAddress;y||(y=await Y(this.signer,t));const e={fixedRateAddress:M.fixedRateExchangeAddress,baseTokenAddress:t,owner:L,marketFeeCollector:L,baseTokenDecimals:y,datatokenDecimals:18,fixedRate:E.toString(),marketFee:"0",allowedConsumer:L,withMint:!0};$=await I.createNftWithDatatokenWithFixedRate(j,G,e)}else $=await I.createNftWithDatatoken(j,G)}catch(t){return console.log("ERROR creating NFT bundle",t),null}const _=await $.wait(),z=at(_,"NFTCreated"),B=at(_,"TokenCreated"),q=z.args.newTokenAddress,W=B.args.newTokenAddress;if(r.datatokenAddress=W,r.nftAddress=q,"oasis"===M.sdk){const t=new a.Contract(W,A.abi,i);try{const e=await t.setFilesObject(s(JSON.stringify(r)));e.wait&&await e.wait()}catch(t){return console.log("Error updating files object with data token and nft addresses: ",t),null}}x[0].files="oasis"===M.sdk?"":await Nt.encrypt(r,Number(D),d,i,null),x[0].datatokenAddress=W,x[0].serviceEndpoint=d,C=q;const V=b.makeDid(C,F.toString());let H,Z,X;if(o=b.updateFields({id:V,nftAddress:C}),l)H=await Nt.encrypt(o,Number(D),d,i,null),Z=(await h.validate(o,i,d)).hash,X=2;else{const t=JSON.stringify(o),e=Buffer.from(t);H=c(e),Z="0x"+R("sha256").update(H).digest("hex"),X=0}return await P.setMetadata(C,await i.getAddress(),0,d,"",g(X),H,Z),o.id}async function Xt(t,e,i){const r=new a.Contract(t,C.abi,e),n=await e.getAddress();try{const t=await r.deployAccessListContract("AllowList","ALLOW",!0,n,i||[n],["https://oceanprotocol.com/nft/"]);if(t&&t.wait)return at(await t.wait(),"NewAccessList").args[0]}catch(t){console.log("ERROR createAccessListFactory(): ",t)}return null}export{bt as AccessListContract,St as AccesslistFactory,Mt as Aquarius,j as Config,J as ConfigHelper,Vt as DEVELOPMENT_CHAIN_ID,kt as Datatoken,Tt as Datatoken4,st as Dispenser,I as EncryptMethod,At as EnterpriseFeeCollectorContract,Et as EscrowContract,dt as FEE_HISTORY_NOT_SUPPORTED,U as FileObjectType,ut as FixedRateExchange,ct as GASLIMIT_DEFAULT,q as KNOWN_CONFIDENTIAL_EVMS,L as LogLevel,$ as Logger,_ as LoggerInstance,lt as MAX_UINT_256,vt as Nft,pt as NftFactory,Ot as Provider,Nt as ProviderInstance,ht as Router,rt as SmartContract,nt as SmartContractWithAddress,ot as ZERO_ADDRESS,$t as allowance,zt as allowanceWei,et as amountToUnits,Lt as approve,jt as approveWei,_t as balance,yt as calculateActiveTemplateIndex,B as configHelperNetworks,Xt as createAccessListFactory,Zt as createAsset,Bt as decimals,It as downloadFile,Ut as downloadFileBrowser,Pt as generateDid,wt as generateDtName,Jt as getErrorMessage,at as getEventFromTx,Q as getFairGasPrice,Rt as getHash,mt as getOceanArtifactsAddresses,ft as getOceanArtifactsAddressesByChainId,Y as getTokenDecimals,Ct as isDefined,W as minAbi,Wt as orderAsset,it as sendTx,K as setContractDefaults,xt as signHash,Dt as signRequest,Ft as sleep,Gt as transfer,tt as unitsToAmount,Ht as useOasisSDK};
|
|
1
|
+
import t from"@oceanprotocol/contracts/addresses/address.json";import e from"fs";import{ethers as a,formatUnits as i,parseUnits as n,EventLog as r,toUtf8Bytes as s,keccak256 as o,hexlify as c,toUtf8String as l,getAddress as d,parseEther as u,getBytes as h,toBeHex as g}from"ethers";import*as w from"@oasisprotocol/sapphire-paratime";import p from"bignumber.js";import m from"decimal.js";import f from"@oceanprotocol/contracts/artifacts/contracts/pools/dispenser/Dispenser.sol/Dispenser.json";import y from"@oceanprotocol/contracts/artifacts/contracts/pools/fixedRate/FixedRateExchange.sol/FixedRateExchange.json";import v from"@oceanprotocol/contracts/artifacts/contracts/pools/FactoryRouter.sol/FactoryRouter.json";import T from"@oceanprotocol/contracts/artifacts/contracts/templates/ERC20Template.sol/ERC20Template.json";import k from"@oceanprotocol/contracts/artifacts/contracts/templates/ERC20TemplateEnterprise.sol/ERC20TemplateEnterprise.json";import E from"@oceanprotocol/contracts/artifacts/contracts/templates/ERC721Template.sol/ERC721Template.json";import S from"@oceanprotocol/contracts/artifacts/contracts/ERC721Factory.sol/ERC721Factory.json";import b from"@oceanprotocol/contracts/artifacts/contracts/interfaces/IERC20Template.sol/IERC20Template.json";import A from"@oceanprotocol/contracts/artifacts/contracts/templates/ERC20Template4.sol/ERC20Template4.json";import C from"@oceanprotocol/contracts/artifacts/contracts/accesslists/AccessList.sol/AccessList.json";import F from"@oceanprotocol/contracts/artifacts/contracts/accesslists/AccessListFactory.sol/AccessListFactory.json";import D from"@oceanprotocol/contracts/artifacts/contracts/escrow/Escrow.sol/Escrow.json";import x from"@oceanprotocol/contracts/artifacts/contracts/communityFee/EnterpriseFeeCollector.sol/EnterpriseFeeCollector.json";import O from"cross-fetch";import{DDOManager as M}from"@oceanprotocol/ddo-js";import N from"jsonwebtoken";import{PublicKey as P,encrypt as R}from"eciesjs";import U from"crypto-js/sha256.js";import{createHash as I}from"crypto";var L,G;!function(t){t.URL="url",t.IPFS="ipfs",t.ARWEAVE="arweave"}(L||(L={})),function(t){t.AES="AES",t.ECIES="ECIES"}(G||(G={}));const _={DOWNLOAD:"download",ENCRYPT:"encrypt",ENCRYPT_FILE:"encryptFile",DECRYPT_DDO:"decryptDDO",GET_DDO:"getDDO",QUERY:"query",NONCE:"nonce",STATUS:"status",DETAILED_STATUS:"detailedStatus",FIND_DDO:"findDDO",GET_FEES:"getFees",FILE_INFO:"fileInfo",VALIDATE_DDO:"validateDDO",COMPUTE_GET_ENVIRONMENTS:"getComputeEnvironments",COMPUTE_START:"startCompute",FREE_COMPUTE_START:"freeStartCompute",COMPUTE_STOP:"stopCompute",COMPUTE_GET_STATUS:"getComputeStatus",COMPUTE_GET_STREAMABLE_LOGS:"getComputeStreamableLogs",COMPUTE_GET_RESULT:"getComputeResult",COMPUTE_INITIALIZE:"initializeCompute",STOP_NODE:"stopNode",REINDEX_TX:"reindexTx",REINDEX_CHAIN:"reindexChain",HANDLE_INDEXING_THREAD:"handleIndexingThread",COLLECT_FEES:"collectFees",POLICY_SERVER_PASSTHROUGH:"PolicyServerPassthrough",GET_P2P_PEER:"getP2PPeer",GET_P2P_PEERS:"getP2PPeers",GET_P2P_NETWORK_STATS:"getP2PNetworkStats",FIND_PEER:"findPeer",CREATE_AUTH_TOKEN:"createAuthToken",INVALIDATE_AUTH_TOKEN:"invalidateAuthToken",FETCH_CONFIG:"fetchConfig",PUSH_CONFIG:"pushConfig",GET_LOGS:"getLogs",JOBS:"jobs"};class j{constructor(){this.nodeUri=void 0,this.providerAddress=void 0,this.oceanNodeUri=void 0,this.web3Provider=void 0,this.oceanTokenAddress=void 0,this.nftFactoryAddress=void 0,this.routerFactoryAddress=void 0,this.datatokensABI=void 0,this.fixedRateExchangeAddress=void 0,this.fixedRateExchangeAddressABI=void 0,this.dispenserAddress=void 0,this.dispenserABI=void 0,this.opfCommunityFeeCollector=void 0,this.EnterpriseFeeCollector=void 0,this.sideStakingAddress=void 0,this.startBlock=void 0,this.verbose=void 0,this.authMessage=void 0,this.authTokenExpiration=void 0,this.parityUri=void 0,this.threshold=void 0,this.chainId=void 0,this.network=void 0,this.explorerUri=void 0,this.oceanTokenSymbol=void 0,this.transactionBlockTimeout=void 0,this.transactionConfirmationBlocks=void 0,this.transactionPollingTimeout=void 0,this.gasFeeMultiplier=void 0,this.sdk=void 0,this.accessListFactory=void 0,this.escrow=void 0}}function $(){return $=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var a=arguments[e];for(var i in a)({}).hasOwnProperty.call(a,i)&&(t[i]=a[i])}return t},$.apply(null,arguments)}var z;!function(t){t[t.None=-1]="None",t[t.Error=0]="Error",t[t.Warn=1]="Warn",t[t.Log=2]="Log",t[t.Verbose=3]="Verbose"}(z||(z={}));class B{constructor(t){this.logLevel=void 0,this.logLevel=t,this.logLevel=t||z.Error}setLevel(t){this.logLevel=t}bypass(...t){this.dispatch("log",-Infinity,...t)}debug(...t){this.dispatch("debug",z.Verbose,...t)}log(...t){this.dispatch("log",z.Log,...t)}warn(...t){this.dispatch("warn",z.Warn,...t)}error(...t){this.dispatch("error",z.Error,...t)}dispatch(t,e,...a){this.logLevel>=e&&console[t](...a)}}const J=new B,q={chainId:null,network:"unknown",nodeUri:"http://127.0.0.1:8545",oceanNodeUri:"http://127.0.0.1:8001",explorerUri:null,oceanTokenAddress:null,oceanTokenSymbol:"OCEAN",fixedRateExchangeAddress:null,dispenserAddress:null,startBlock:0,transactionBlockTimeout:50,transactionConfirmationBlocks:1,transactionPollingTimeout:750,gasFeeMultiplier:1},W=[$({},q),$({},q,{chainId:8996,network:"development",oceanNodeUri:"http://127.0.0.1:8001",sdk:"evm"}),$({},q,{chainId:11155111,network:"sepolia",nodeUri:"https://sepolia.infura.io/v3",explorerUri:"https://sepolia.etherscan.io",gasFeeMultiplier:1.1,sdk:"evm"}),$({},q,{chainId:1,network:"mainnet",nodeUri:"https://mainnet.infura.io/v3",explorerUri:"https://etherscan.io",startBlock:11105459,transactionBlockTimeout:150,transactionConfirmationBlocks:5,transactionPollingTimeout:1750,gasFeeMultiplier:1.05,sdk:"evm"}),$({},q,{chainId:8453,network:"base",nodeUri:"https://mainnet.base.org",explorerUri:"https://etherscan.io",startBlock:30562198,transactionBlockTimeout:150,transactionConfirmationBlocks:5,transactionPollingTimeout:1750,gasFeeMultiplier:1.05,sdk:"evm"}),$({},q,{chainId:137,network:"polygon",nodeUri:"https://polygon-mainnet.infura.io/v3",explorerUri:"https://polygonscan.com",oceanTokenSymbol:"mOCEAN",gasFeeMultiplier:1.6,sdk:"evm"}),$({},q,{chainId:2021e3,network:"gaiaxtestnet",nodeUri:"https://rpc.gaiaxtestnet.oceanprotocol.com",explorerUri:"https://blockscout.gaiaxtestnet.oceanprotocol.com",sdk:"evm"}),$({},q,{chainId:80001,network:"mumbai",nodeUri:"https://polygon-mumbai.infura.io/v3",explorerUri:"https://mumbai.polygonscan.com",gasFeeMultiplier:1.1,sdk:"evm"}),$({},q,{chainId:56,network:"bsc",nodeUri:"https://bsc-dataseed.binance.org",explorerUri:"https://bscscan.com/",gasFeeMultiplier:1.05,sdk:"evm"}),$({},q,{chainId:246,network:"energyweb",nodeUri:"https://rpc.energyweb.org",explorerUri:"https://explorer.energyweb.org",gasFeeMultiplier:1.05,sdk:"evm"}),$({},q,{chainId:1285,network:"moonriver",nodeUri:"https://moonriver.api.onfinality.io/public",explorerUri:"https://moonriver.moonscan.io/",gasFeeMultiplier:1.05,sdk:"evm"}),$({},q,{chainId:100,network:"gen-x-testnet",nodeUri:"https://rpc.genx.minimal-gaia-x.eu",explorerUri:"https://explorer.genx.minimal-gaia-x.eu/",gasFeeMultiplier:1,sdk:"evm"}),$({},q,{chainId:10,network:"optimism",nodeUri:"https://mainnet.optimism.io",explorerUri:"https://optimistic.etherscan.io/",gasFeeMultiplier:1.1,sdk:"evm"}),$({},q,{chainId:11155420,network:"optimism_sepolia",nodeUri:"https://sepolia.optimism.io",explorerUri:"https://sepolia-optimism.etherscan.io/",gasFeeMultiplier:1.1,sdk:"evm"}),$({},q,{chainId:23294,network:"oasis_sapphire",nodeUri:"https://sapphire.oasis.io",explorerUri:"https://explorer.oasis.io/mainnet/sapphire/",gasFeeMultiplier:1,sdk:"oasis"}),$({},q,{chainId:23295,network:"oasis_sapphire_testnet",nodeUri:"https://testnet.sapphire.oasis.dev",explorerUri:"https://explorer.oasis.io/testnet/sapphire/",gasFeeMultiplier:1,sdk:"oasis"}),$({},q,{chainId:32456,network:"pontus-x-devnet",nodeUri:"https://rpc.dev.pontus-x.eu",explorerUri:"https://explorer.dev.pontus-x.eu/testnet/pontusx",sdk:"evm"})],H=[23294,23295];class V{getAddressesFromEnv(e,a){let i;const n=()=>process.env.NODE_URL?{oceanNodeUri:process.env.NODE_URL}:{};if(a&&a[e]){const{FixedPrice:t,Dispenser:r,ERC721Factory:s,OPFCommunityFeeCollector:o,Ocean:c,chainId:l,startBlock:d,Router:u,AccessListFactory:h,Escrow:g,EnterpriseFeeCollector:w}=a[e];i=$({nftFactoryAddress:s,opfCommunityFeeCollector:o,fixedRateExchangeAddress:t,dispenserAddress:r,oceanTokenAddress:c,routerFactoryAddress:u,chainId:l,startBlock:d,accessListFactory:h,escrow:g,EnterpriseFeeCollector:w},n())}else if(t[e]){const{FixedPrice:a,Dispenser:r,OPFCommunityFeeCollector:s,ERC721Factory:o,Ocean:c,chainId:l,startBlock:d,Router:u,AccessListFactory:h,Escrow:g,EnterpriseFeeCollector:w}=t[e];i=$({nftFactoryAddress:o,opfCommunityFeeCollector:s,fixedRateExchangeAddress:a,dispenserAddress:r,oceanTokenAddress:c,routerFactoryAddress:u,chainId:l,startBlock:d,accessListFactory:h,escrow:g,EnterpriseFeeCollector:w},n())}return i}getConfig(t,a){const i="string"==typeof t?"network":"chainId";let n,r=W.find(e=>e[i]===t);if(!r)return J.error(`No config found for given network '${t}'`),null;try{n=process.env.ADDRESS_FILE?JSON.parse(e.readFileSync(process.env.ADDRESS_FILE,"utf8")):null}catch(t){console.log(t),n=null}let s=this.getAddressesFromEnv(r.network,n);return!s&&H.includes(r.chainId)&&(s=this.getAddressesFromEnv(r.network.replace("sapph","saph"),n)),"sdk"in r&&null!==r.sdk||(r.sdk=H.includes(r.chainId)?"oasis":"evm"),s&&"accessListFactory"in s&&(r.accessListFactory=s.accessListFactory),r=$({},r,s),$({},r,{nodeUri:a?`${r.nodeUri}/${a}`:r.nodeUri})}}const Z=[{constant:!0,inputs:[],name:"name",outputs:[{name:"",type:"string"}],payable:!1,stateMutability:"view",type:"function"},{constant:!1,inputs:[{name:"_spender",type:"address"},{name:"_value",type:"uint256"}],name:"approve",outputs:[{name:"",type:"bool"}],payable:!1,stateMutability:"nonpayable",type:"function"},{constant:!0,inputs:[],name:"totalSupply",outputs:[{name:"",type:"uint256"}],payable:!1,stateMutability:"view",type:"function"},{constant:!1,inputs:[{name:"_from",type:"address"},{name:"_to",type:"address"},{name:"_value",type:"uint256"}],name:"transferFrom",outputs:[{name:"",type:"bool"}],payable:!1,stateMutability:"nonpayable",type:"function"},{constant:!0,inputs:[],name:"decimals",outputs:[{name:"",type:"uint8"}],payable:!1,stateMutability:"view",type:"function"},{constant:!0,inputs:[{name:"_owner",type:"address"}],name:"balanceOf",outputs:[{name:"balance",type:"uint256"}],payable:!1,stateMutability:"view",type:"function"},{constant:!0,inputs:[],name:"symbol",outputs:[{name:"",type:"string"}],payable:!1,stateMutability:"view",type:"function"},{constant:!1,inputs:[{name:"_to",type:"address"},{name:"_value",type:"uint256"}],name:"transfer",outputs:[{name:"",type:"bool"}],payable:!1,stateMutability:"nonpayable",type:"function"},{constant:!0,inputs:[{name:"_owner",type:"address"},{name:"_spender",type:"address"}],name:"allowance",outputs:[{name:"",type:"uint256"}],payable:!1,stateMutability:"view",type:"function"},{payable:!0,stateMutability:"payable",type:"fallback"},{anonymous:!1,inputs:[{indexed:!0,name:"owner",type:"address"},{indexed:!0,name:"spender",type:"address"},{indexed:!1,name:"value",type:"uint256"}],name:"Approval",type:"event"},{anonymous:!1,inputs:[{indexed:!0,name:"from",type:"address"},{indexed:!0,name:"to",type:"address"},{indexed:!1,name:"value",type:"uint256"}],name:"Transfer",type:"event"}],K=3e10,X=4e9,Y=1e10,Q=11155111;function tt(t,e){return t}async function et(t,e){const a=(await t.provider.getFeeData()).gasPrice,i=BigInt(a.toString());return e?(i*BigInt(e)).toString(10):i.toString()}async function at(t,e){return new a.Contract(e,Z,t).decimals()}async function it(t,e,a,n){let r=n||await at(t,e);return"0"===r&&(r=18),i(a,r).toString()}async function nt(t,e,a,i){let r=i||await at(t,e);return"0"===r&&(r=18),n(a,r).toString()}function rt(t,e){if(t&&t.logs)return t.logs.filter(t=>t instanceof r&&t.eventName===e)[0]}async function st(t,e,a,i,...n){const{chainId:r}=await e.provider.getNetwork(),s=await e.provider.getFeeData();let o={};if(s.maxPriorityFeePerGas){let t=s.maxPriorityFeePerGas.toString(),e=s.maxFeePerGas.toString();a>1&&(t=Math.round(Number(s.maxPriorityFeePerGas)*a).toString(),e=Math.round(Number(s.maxFeePerGas)*a).toString()),o={maxPriorityFeePerGas:(80001===Number(r)||137===Number(r))&&Number(t)<K?K:Number(r)===Q&&Number(t)<X?X:H.includes(Number(r))&&Number(t)<Y?Y:Number(t),maxFeePerGas:(80001===Number(r)||137===Number(r))&&Number(e)<K?K:Number(r)===Q&&Number(e)<X?X:H.includes(Number(r))&&Number(e)<Y?Y:Number(e)}}else o={gasPrice:s.gasPrice};o.gasLimit=BigInt(new p(t).plus(20000n).toString());try{const t=await i(...n,o);return await t.wait(),t}catch(t){return J.error("Send tx error: ",t),null}}class ot{constructor(t,e,a,i){this.signer=void 0,this.config=void 0,this.abi=void 0,this.signer=t,this.config=a||(new V).getConfig(e),this.abi=i||this.getDefaultAbi()}getSignerAccordingSdk(){return this.config&&"sdk"in this.config&&"oasis"===this.config.sdk?w.wrap(this.signer):this.signer}async amountToUnits(t,e,a){return nt(this.signer,t,e,a)}async unitsToAmount(t,e,a){return it(this.signer,t,e,a)}async getFairGasPrice(){var t;return et(this.signer,null==(t=this.config)?void 0:t.gasFeeMultiplier)}getContract(t,e){if(!t)throw new Error("Contract address is required but not provided");return tt(new a.Contract(t,new a.Interface(JSON.stringify(e||this.abi)),this.signer))}}class ct extends ot{constructor(t,e,a,i,n){super(e,a,i,n),this.address=void 0,this.contract=void 0,this.address=t,this.contract=this.getContract(this.address)}}class lt extends ct{getDefaultAbi(){return f.abi}async status(t){const e=await this.contract.status(t);if(!e)throw new Error("Np dispenser found for the given datatoken address");return{active:e.active,owner:e.owner,isMinter:e.isMinter,maxTokens:await this.unitsToAmount(null,e.maxTokens,18),maxBalance:await this.unitsToAmount(null,e.maxBalance,18),balance:await this.unitsToAmount(null,e.balance,18),allowedSwapper:e.allowedSwapper}}async create(t,e,a,i,n,r){var s;const o=await this.contract.create.estimateGas(t,this.amountToUnits(null,a,18),this.amountToUnits(null,i,18),e,n);return r?o:await st(o,this.getSignerAccordingSdk(),null==(s=this.config)?void 0:s.gasFeeMultiplier,this.contract.create,t,this.amountToUnits(null,a,18),this.amountToUnits(null,i,18),e,n)}async activate(t,e,a,i){var n;const r=await this.contract.activate.estimateGas(t,this.amountToUnits(null,e,18),this.amountToUnits(null,a,18));return i?r:await st(r,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,this.contract.activate,t,this.amountToUnits(null,e,18),this.amountToUnits(null,a,18))}async deactivate(t,e){var a;const i=await this.contract.deactivate.estimateGas(t);return e?i:await st(i,this.getSignerAccordingSdk(),null==(a=this.config)?void 0:a.gasFeeMultiplier,this.contract.deactivate,t)}async setAllowedSwapper(t,e,a){var i;const n=await this.contract.setAllowedSwapper.estimateGas(t,e);return a?n:await st(n,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.setAllowedSwapper,t,e)}async dispense(t,e="1",a,i){var n;const r=await this.contract.dispense.estimateGas(t,this.amountToUnits(null,e,18),a);return i?r:await st(r,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,this.contract.dispense,t,this.amountToUnits(null,e,18),a)}async ownerWithdraw(t,e){var a;const i=await this.contract.ownerWithdraw.estimateGas(t);return e?i:await st(i,this.getSignerAccordingSdk(),null==(a=this.config)?void 0:a.gasFeeMultiplier,this.contract.ownerWithdraw,t)}async isDispensable(t,e,a,i="1"){const n=await this.status(t);return!(!n||!1===n.active||new m(await e.balance(t,a)).greaterThanOrEqualTo(n.maxBalance)||new m(String(i)).greaterThan(n.maxTokens)||!new m(n.balance).greaterThanOrEqualTo(i)&&!0!==n.isMinter)}}const dt="0x0000000000000000000000000000000000000000",ut=1e6,ht="115792089237316195423570985008687907853269984665640564039457584007913129639934",gt="Returned error: Method eth_feeHistory not supported.";class wt extends ct{getDefaultAbi(){return y.abi}async generateExchangeId(t,e){return await this.contract.generateExchangeId(t,e)}async buyDatatokens(t,e,a,i=dt,n="0",r){var s;const o=await this.getExchange(t),c=await this.amountToUnits(null,n,18),l=await this.amountToUnits(o.datatoken,e,Number(o.dtDecimals)),d=await this.amountToUnits(o.baseToken,a,Number(o.btDecimals)),u=await this.contract.buyDT.estimateGas(t,l,d,i,c);return r?u:await st(u,this.getSignerAccordingSdk(),null==(s=this.config)?void 0:s.gasFeeMultiplier,this.contract.buyDT,t,l,d,i,c)}async sellDatatokens(t,e,a,i=dt,n="0",r){var s;const o=await this.getExchange(t),c=await this.amountToUnits(null,n,18),l=await this.amountToUnits(o.datatoken,e,Number(o.dtDecimals)),d=await this.amountToUnits(o.baseToken,a,Number(o.btDecimals)),u=await this.contract.sellDT.estimateGas(t,l,d,i,c);return r?u:await st(u,this.getSignerAccordingSdk(),null==(s=this.config)?void 0:s.gasFeeMultiplier,this.contract.sellDT,t,l,d,i,c)}async getNumberOfExchanges(){const t=await this.contract.getNumberOfExchanges();return Number(t)}async setRate(t,e,a){var i;const n=await this.contract.setRate.estimateGas(t,await this.amountToUnits(null,e,18));return a?n:await st(n,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.setRate,t,await this.amountToUnits(null,e,18))}async setAllowedSwapper(t,e,a){var i;const n=await this.contract.setAllowedSwapper.estimateGas(t,e);return a?n:await st(n,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.setAllowedSwapper,t,e)}async activate(t,e){var a;const i=await this.getExchange(t);if(!i)return null;if(!0===i.active)return null;const n=await this.contract.toggleExchangeState.estimateGas(t);return e?n:await st(n,this.getSignerAccordingSdk(),null==(a=this.config)?void 0:a.gasFeeMultiplier,this.contract.toggleExchangeState,t)}async deactivate(t,e){var a;const i=await this.getExchange(t);if(!i)return null;if(!1===i.active)return null;const n=await this.contract.toggleExchangeState.estimateGas(t);return e?n:await st(n,this.getSignerAccordingSdk(),null==(a=this.config)?void 0:a.gasFeeMultiplier,this.contract.toggleExchangeState,t)}async getRate(t){const e=await this.contract.getRate(t);return await this.unitsToAmount(null,e,18)}async getDatatokenSupply(t){const e=await this.contract.getDTSupply(t),a=await this.getExchange(t);return await this.unitsToAmount(a.datatoken,e,Number(a.dtDecimals))}async getBasetokenSupply(t){const e=await this.contract.getBTSupply(t),a=await this.getExchange(t);return await this.unitsToAmount(a.baseToken,e,Number(a.btDecimals))}async getAllowedSwapper(t){return await this.contract.getAllowedSwapper(t)}async calcBaseInGivenDatatokensOut(t,e,a="0"){const i=await this.getExchange(t),n=await this.contract.calcBaseInGivenOutDT(t,await this.amountToUnits(i.datatoken,e,Number(i.dtDecimals)),await this.amountToUnits(null,a,18));return{baseTokenAmount:await this.unitsToAmount(i.baseToken,n.baseTokenAmount,Number(i.btDecimals)),marketFeeAmount:await this.unitsToAmount(i.baseToken,n.publishMarketFeeAmount,Number(i.btDecimals)),oceanFeeAmount:await this.unitsToAmount(i.baseToken,n.oceanFeeAmount,Number(i.btDecimals)),consumeMarketFeeAmount:await this.unitsToAmount(i.baseToken,n.consumeMarketFeeAmount,Number(i.btDecimals))}}async getAmountBasetokensOut(t,e,a="0"){const i=await this.getExchange(t),n=await this.contract.calcBaseOutGivenInDT(t,await this.amountToUnits(i.datatoken,e,Number(i.dtDecimals)),await this.amountToUnits(null,a,18));return await this.unitsToAmount(i.baseToken,n[0],Number(i.btDecimals))}async getExchange(t){const e=await this.contract.getExchange(t);return{active:e.active,datatoken:e.datatoken,baseToken:e.baseToken,withMint:e.withMint,exchangeOwner:e.exchangeOwner,allowedSwapper:e.allowedSwapper,dtDecimals:e.dtDecimals.toString(),btDecimals:e.btDecimals.toString(),dtBalance:await this.unitsToAmount(e.datatoken,e.dtBalance,Number(e.dtDecimals)),btBalance:await this.unitsToAmount(e.baseToken,e.btBalance,Number(e.btDecimals)),dtSupply:await this.unitsToAmount(e.datatoken,e.dtSupply,Number(e.dtDecimals)),btSupply:await this.unitsToAmount(e.baseToken,e.btSupply,Number(e.btDecimals)),fixedRate:await this.unitsToAmount(null,e.fixedRate,18),exchangeId:t}}async getFeesInfo(t){const e=await this.contract.getFeesInfo(t),a=await this.getExchange(t);return{opcFee:await this.unitsToAmount(null,e.opcFee.toString(),18),marketFee:await this.unitsToAmount(null,e.marketFee.toString(),18),marketFeeCollector:e.marketFeeCollector,marketFeeAvailable:await this.unitsToAmount(a.baseToken,e.marketFeeAvailable,Number(a.btDecimals)),oceanFeeAvailable:await this.unitsToAmount(a.baseToken,e.oceanFeeAvailable,Number(a.btDecimals)),exchangeId:t}}async getExchanges(){return await this.contract.getExchanges()}async isActive(t){return await this.contract.isActive(t)}async activateMint(t,e){var a;const i=await this.getExchange(t);if(!i)return null;if(!0===i.withMint)return null;const n=await this.contract.toggleMintState.estimateGas(t,!0);return e?n:await st(n,this.getSignerAccordingSdk(),null==(a=this.config)?void 0:a.gasFeeMultiplier,this.contract.toggleMintState,t,!0)}async deactivateMint(t,e){var a;const i=await this.getExchange(t);if(!i)return null;if(!1===i.withMint)return null;const n=await this.contract.toggleMintState.estimateGas(t,!1);return e?n:await st(n,this.getSignerAccordingSdk(),null==(a=this.config)?void 0:a.gasFeeMultiplier,this.contract.toggleMintState,t,!1)}async collectBasetokens(t,e,a){var i;if(!await this.getExchange(t))return null;const n=await this.contract.getExchange(t),r=await this.amountToUnits(n.baseToken,e,Number(n.btDecimals)),s=await this.contract.collectBT.estimateGas(t,r);return a?s:await st(s,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.collectBT,t,r)}async collectDatatokens(t,e,a){var i;if(!await this.getExchange(t))return null;const n=await this.contract.getExchange(t),r=await this.amountToUnits(n.datatoken,e,Number(n.dtDecimals)),s=await this.contract.collectDT.estimateGas(t,r);return a?s:await st(s,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.collectDT,t,r)}async collectMarketFee(t,e){var a;if(!await this.getExchange(t))return null;const i=await this.contract.collectMarketFee.estimateGas(t);return e?i:await st(i,this.getSignerAccordingSdk(),null==(a=this.config)?void 0:a.gasFeeMultiplier,this.contract.collectMarketFee,t)}async collectOceanFee(t,e){var a;if(!await this.getExchange(t))return null;const i=await this.contract.collectOceanFee.estimateGas(t);return e?i:await st(i,this.getSignerAccordingSdk(),null==(a=this.config)?void 0:a.gasFeeMultiplier,this.contract.collectOceanFee,t)}async getOPCCollector(){return await this.contract.opcCollector()}async getRouter(){return await this.contract.router()}async getExchangeOwner(t){return(await this.getExchange(t)).exchangeOwner}async updateMarketFee(t,e,a){var i;const n=await this.contract.updateMarketFee.estimateGas(t,await this.amountToUnits(null,e,18));return a?n:await st(n,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.updateMarketFee,t,await this.amountToUnits(null,e,18))}async updateMarketFeeCollector(t,e,a){var i;const n=await this.contract.updateMarketFeeCollector.estimateGas(t,e);return a?n:await st(n,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.updateMarketFeeCollector,t,e)}}class pt extends ct{getDefaultAbi(){return v.abi}async buyDatatokenBatch(t,e){var a;const i=await this.contract.buyDTBatch.estimateGas(t);return e?i:await st(i,this.getSignerAccordingSdk(),null==(a=this.config)?void 0:a.gasFeeMultiplier,this.contract.buyDTBatch,t)}async isApprovedToken(t){return await this.contract.isApprovedToken(t)}async isFixedPrice(t){return await this.contract.isFixedRateContract(t)}async getOwner(){return await this.contract.routerOwner()}async getNFTFactory(){return await this.contract.factory()}async addApprovedToken(t,e,a){var i;if(await this.getOwner()!==t)throw new Error("Caller is not Router Owner");const n=await this.contract.addApprovedToken.estimateGas(e);return a?n:await st(n,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.addApprovedToken,e)}async removeApprovedToken(t,e,a){var i;if(await this.getOwner()!==t)throw new Error("Caller is not Router Owner");const n=await this.contract.removeApprovedToken.estimateGas(e);return a?n:await st(n,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.removeApprovedToken,e)}async addFixedRateContract(t,e,a){var i;if(await this.getOwner()!==t)throw new Error("Caller is not Router Owner");const n=await this.contract.addFixedRateContract.estimateGas(e);return a?n:await st(n,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.addFixedRateContract,e)}async removeFixedRateContract(t,e,a){var i;if(await this.getOwner()!==t)throw new Error("Caller is not Router Owner");const n=await this.contract.removeFixedRateContract.estimateGas(e);return a?n:await st(n,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.removeFixedRateContract,e)}async addDispenserContract(t,e,a){var i;if(await this.getOwner()!==t)throw new Error("Caller is not Router Owner");const n=await this.contract.addDispenserContract.estimateGas(e);return a?n:await st(n,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.addDispenserContract,e)}async removeDispenserContract(t,e,a){var i;if(await this.getOwner()!==t)throw new Error("Caller is not Router Owner");const n=await this.contract.removeDispenserContract.estimateGas(e);return a?n:await st(n,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.removeDispenserContract,e)}async getOPCFee(t){const e=await this.contract.getOPCFee(t);return Number(e)}async getCurrentOPCFee(){const t=await this.contract.swapOceanFee();return Number(t)}async updateOPCFee(t,e,a,i,n,r){var s;if(await this.getOwner()!==t)throw new Error("Caller is not Router Owner");const o=await this.contract.updateOPCFee.estimateGas(e,a,i,n);return r?o:await st(o,this.getSignerAccordingSdk(),null==(s=this.config)?void 0:s.gasFeeMultiplier,this.contract.updateOPCFee,e,a,i,n)}}var mt={nouns:["Crab","Fish","Seal","Octopus","Shark","Seahorse","Walrus","Starfish","Whale","Orca","Penguin","Jellyfish","Squid","Lobster","Pelican","Shrimp","Oyster","Clam","Seagull","Dolphin","Shell","Cormorant","Otter","Anemone","Turtle","Coral","Ray","Barracuda","Krill","Anchovy","Angelfish","Barnacle","Clownfish","Cod","Cuttlefish","Eel","Fugu","Herring","Haddock","Ling","Mackerel","Manatee","Narwhal","Nautilus","Plankton","Porpoise","Prawn","Pufferfish","Swordfish","Tuna"],adjectives:["adamant","adroit","amatory","ambitious","amused","animistic","antic","arcadian","artistic","astonishing","astounding","baleful","bellicose","bilious","blissful","boorish","brave","breathtaking","brilliant","calamitous","caustic","cerulean","clever","charming","comely","competent","concomitant","confident","contumacious","corpulent","crapulous","creative","dazzling","dedicated","defamatory","delighted","delightful","determined","didactic","dilatory","dowdy","efficacious","effulgent","egregious","empowered","endemic","enthusiastic","equanimous","exceptional","execrable","fabulous","fantastic","fastidious","feckless","fecund","friable","fulsome","garrulous","generous","gentle","guileless","gustatory","heuristic","histrionic","hubristic","incendiary","incredible","insidious","insolent","inspired","intransigent","inveterate","invidious","invigorated","irksome","jejune","juicy","jocular","joyful","judicious","kind","lachrymose","limpid","loquacious","lovely","luminous","mannered","marvelous","mendacious","meretricious","minatory","mordant","motivated","munificent","nefarious","noxious","obtuse","optimistic","parsimonious","pendulous","pernicious","pervasive","petulant","passionate","phenomenal","platitudinous","pleasant","powerful","precipitate","propitious","puckish","querulous","quiescent","rebarbative","recalcitant","redolent","rhadamanthine","risible","ruminative","sagacious","salubrious","sartorial","sclerotic","serpentine","smart","spasmodic","strident","stunning","stupendous","taciturn","tactful","tasty","tenacious","tremendous","tremulous","trenchant","turbulent","turgid","ubiquitous","uxorious","verdant","vibrant","voluble","voracious","wheedling","withering","wonderful","zealous"]};function ft(t){const e=t||mt,a=Math.floor(Math.random()*e.adjectives.length),i=Math.floor(Math.random()*e.nouns.length),n=Math.floor(100*Math.random()),r=e.adjectives[a].replace(/^\w/,t=>t.toUpperCase()),s=e.nouns[i].replace(/^\w/,t=>t.toUpperCase());return{name:`${r} ${s} Token`,symbol:`${(r.substring(0,3)+s.substring(0,3)).toUpperCase()}-${n}`}}class yt extends ct{getDefaultAbi(){return S.abi}async createNFT(t,e){if(t.templateIndex||(t.templateIndex=1),!t.name||!t.symbol){const{name:e,symbol:a}=ft();t.name=e,t.symbol=a}if(t.templateIndex>await this.getCurrentNFTTemplateCount())throw new Error("Template index doesnt exist");if(0===t.templateIndex)throw new Error("Template index cannot be ZERO");if(!1===(await this.getNFTTemplate(t.templateIndex)).isActive)throw new Error("Template is not active");const a=await this.contract.deployERC721Contract.estimateGas(t.name,t.symbol,t.templateIndex,dt,dt,t.tokenURI,t.transferable,t.owner);if(e)return a;try{var i;const e=await st(a,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.deployERC721Contract,t.name,t.symbol,t.templateIndex,dt,dt,t.tokenURI,t.transferable,t.owner);if(!e){const t="Tx for deploying new NFT contract does not exist or status is not successful.";throw console.error(t),t}return rt(await e.wait(),"NFTCreated").args[0]}catch(t){console.error(`Creation of NFT failed: ${t}`)}}async getCurrentNFTCount(){const t=await this.contract.getCurrentNFTCount();return Number(t)}async getCurrentTokenCount(){const t=await this.contract.getCurrentTokenCount();return Number(t)}async getOwner(){return await this.contract.owner()}async getCurrentNFTTemplateCount(){const t=await this.contract.getCurrentNFTTemplateCount();return Number(t)}async getCurrentTokenTemplateCount(){const t=await this.contract.getCurrentTemplateCount();return Number(t)}async getNFTTemplate(t){if(t>await this.getCurrentNFTTemplateCount())throw new Error("Template index doesnt exist");if(0===t)throw new Error("Template index cannot be ZERO");return await this.contract.getNFTTemplate(t)}async getTokenTemplate(t){return await this.contract.getTokenTemplate(t)}async checkDatatoken(t){return await this.contract.erc20List(t)}async checkNFT(t){return await this.contract.erc721List(t)}async addNFTTemplate(t,e,a){var i;if(await this.getOwner()!==t)throw new Error("Caller is not Factory Owner");if(e===dt)throw new Error("Template cannot be ZERO address");const n=await this.contract.add721TokenTemplate.estimateGas(e);return a?n:await st(n,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.add721TokenTemplate,e)}async disableNFTTemplate(t,e,a){var i;if(await this.getOwner()!==t)throw new Error("Caller is not Factory Owner");if(e>await this.getCurrentNFTTemplateCount())throw new Error("Template index doesnt exist");if(0===e)throw new Error("Template index cannot be ZERO");const n=await this.contract.disable721TokenTemplate.estimateGas(e);return a?n:await st(n,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.disable721TokenTemplate,e)}async reactivateNFTTemplate(t,e,a){var i;if(await this.getOwner()!==t)throw new Error("Caller is not Factory Owner");if(e>await this.getCurrentNFTTemplateCount())throw new Error("Template index doesnt exist");if(0===e)throw new Error("Template index cannot be ZERO");const n=await this.contract.reactivate721TokenTemplate.estimateGas(e);return a?n:await st(n,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.reactivate721TokenTemplate,e)}async addTokenTemplate(t,e,a){var i;if(await this.getOwner()!==t)throw new Error("Caller is not Factory Owner");if(e===dt)throw new Error("Template cannot be address ZERO");const n=await this.contract.addTokenTemplate.estimateGas(e);return a?n:await st(n,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.addTokenTemplate,e)}async disableTokenTemplate(t,e,a){var i;if(await this.getOwner()!==t)throw new Error("Caller is not Factory Owner");if(e>await this.getCurrentTokenTemplateCount())throw new Error("Template index doesnt exist");if(0===e)throw new Error("Template index cannot be ZERO");if(!1===(await this.getTokenTemplate(e)).isActive)throw new Error("Template is already disabled");const n=await this.contract.disableTokenTemplate.estimateGas(e);return a?n:await st(n,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.disableTokenTemplate,e)}async reactivateTokenTemplate(t,e,a){var i;if(await this.getOwner()!==t)throw new Error("Caller is not Factory Owner");if(e>await this.getCurrentTokenTemplateCount())throw new Error("Template index doesnt exist");if(0===e)throw new Error("Template index cannot be ZERO");if(!0===(await this.getTokenTemplate(e)).isActive)throw new Error("Template is already active");const n=await this.contract.reactivateTokenTemplate.estimateGas(e);return a?n:await st(n,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.reactivateTokenTemplate,e)}async startMultipleTokenOrder(t,e){var a;if(t.length>50)throw new Error("Too many orders");const i=await this.contract.startMultipleTokenOrder.estimateGas(t);return e?i:await st(i,this.getSignerAccordingSdk(),null==(a=this.config)?void 0:a.gasFeeMultiplier,this.contract.startMultipleTokenOrder,t)}async createNftWithDatatoken(t,e,a){var i;const n=await this.getErcCreationParams(e),r=await this.contract.createNftWithErc20.estimateGas(t,n);return a?r:await st(r,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.createNftWithErc20,t,n)}async createNftWithDatatokenWithFixedRate(t,e,a,i){var n;const r=await this.getErcCreationParams(e),s=await this.getFreCreationParams(a),o=await this.contract.createNftWithErc20WithFixedRate.estimateGas(t,r,s);return i?o:await st(o,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,this.contract.createNftWithErc20WithFixedRate,t,r,s)}async createNftWithDatatokenWithDispenser(t,e,a,i){var n;const r=await this.getErcCreationParams(e);a.maxBalance=await this.amountToUnits(null,a.maxBalance,18),a.maxTokens=await this.amountToUnits(null,a.maxTokens,18);const s=await this.contract.createNftWithErc20WithDispenser.estimateGas(t,r,a);return i?s:await st(s,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,this.contract.createNftWithErc20WithDispenser,t,r,a)}async getErcCreationParams(t){let e,a;t.name&&t.symbol||({name:e,symbol:a}=ft());let i=18;if(t.feeToken!==dt)try{i=await at(this.signer,t.feeToken)}catch(t){J.error("getTokenDecimals error",t)}const n=[t.minter,t.paymentCollector,t.mpFeeAddress,t.feeToken];return t.filesObject&&(t.accessListFactory&&n.push(t.accessListFactory),t.allowAccessList&&n.push(t.allowAccessList),t.denyAccessList&&n.push(t.denyAccessList)),{templateIndex:t.templateIndex,strings:[t.name||e,t.symbol||a],addresses:n,uints:[await this.amountToUnits(null,t.cap,18),await this.amountToUnits(null,t.feeAmount,i)],bytess:t.filesObject?[s(JSON.stringify(t.filesObject))]:[]}}async getFreCreationParams(t){t.allowedConsumer||(t.allowedConsumer=dt);const e=!1===t.withMint?0:1;return{fixedPriceAddress:t.fixedRateAddress,addresses:[t.baseTokenAddress,t.owner,t.marketFeeCollector,t.allowedConsumer],uints:[t.baseTokenDecimals,t.datatokenDecimals,await this.amountToUnits(null,t.fixedRate,t.datatokenDecimals),await this.amountToUnits(null,t.marketFee,t.datatokenDecimals),e]}}}function vt(){try{if(process.env.ADDRESS_FILE){const t=e.readFileSync(process.env.ADDRESS_FILE,"utf8");return JSON.parse(t)}return t}catch(e){return t}}function Tt(t){try{const e=vt();if(e){const a=Object.keys(e);for(const i of a)if(e[i].chainId===t)return e[i]}}catch(t){console.error(t)}return null}async function kt(t,e,i,n){const r="number"==typeof i,s=new yt(e,t,n),o=await s.getCurrentTokenTemplateCount();for(let e=1;e<=o;e++){const n=await s.getTokenTemplate(e),o=new a.Contract(n.templateAddress,b.abi,t);if(r){const t=await o.getId();if(n.isActive&&t.toString()===i.toString())return e}else if(n.isActive&&n.templateAddress===i.toString())return e}return-1}class Et extends ot{getDefaultAbi(){return E.abi}async createDatatoken(t,e,a,i,n,r,o,c,l,d,u,h,g,w,p,m){var f;if(!0!==(await this.getNftPermissions(t,e)).deployERC20)throw new Error("Caller is not DatatokenDeployer");u||(u=1),l&&d||({name:l,symbol:d}=ft());const y=this.getContract(t);if(!this.signer.provider)throw new Error("Provider is required but not available");const{chainId:v}=await this.signer.provider.getNetwork(),T=Tt(Number(v));h&&(u=await kt(this.signer,T.ERC721Factory,4,Number(v)));const k=await y.createERC20.estimateGas(u,[l,d],[a,i,n,r],[await this.amountToUnits(null,c,18),await this.amountToUnits(null,o,18)],[]);if(m)return k;const E=[a,i,n,r];g&&(E.push(g.toLowerCase()),E.push(w?w.toLowerCase():dt),E.push(p||dt));const S=await st(k,this.getSignerAccordingSdk(),null==(f=this.config)?void 0:f.gasFeeMultiplier,y.createERC20,u,[l,d],E,[await this.amountToUnits(null,c,18),await this.amountToUnits(null,o,18)],h?[s(h)]:[]),b=rt(await S.wait(),"TokenCreated");return null==b?void 0:b.args[0]}async addManager(t,e,a,i){var n;const r=this.getContract(t);if(await this.getNftOwner(t)!==e)throw new Error("Caller is not NFT Owner");const s=await r.addManager.estimateGas(a);return i?s:await st(s,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,r.addManager,a)}async removeManager(t,e,a,i){var n;const r=this.getContract(t);if(await this.getNftOwner(t)!==e)throw new Error("Caller is not NFT Owner");const s=await r.removeManager.estimateGas(a);return i?s:await st(s,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,r.removeManager,a)}async addDatatokenDeployer(t,e,a,i){var n;const r=this.getContract(t);if(!0!==(await this.getNftPermissions(t,e)).manager)throw new Error("Caller is not Manager");const s=await r.addToCreateERC20List.estimateGas(a);return i?s:await st(s,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,r.addToCreateERC20List,a)}async removeDatatokenDeployer(t,e,a,i){var n;const r=this.getContract(t);if(!0!==(await this.getNftPermissions(t,e)).manager||e===a&&!0!==(await this.getNftPermissions(t,e)).deployERC20)throw new Error("Caller is not Manager nor DatatokenDeployer");const s=await r.removeFromCreateERC20List.estimateGas(a);return i?s:await st(s,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,r.removeFromCreateERC20List,a)}async addMetadataUpdater(t,e,a,i){var n;const r=this.getContract(t);if(!0!==(await this.getNftPermissions(t,e)).manager)throw new Error("Caller is not Manager");const s=await r.addToMetadataList.estimateGas(a);return i?s:await st(s,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,r.addToMetadataList,a)}async removeMetadataUpdater(t,e,a,i){var n;const r=this.getContract(t);if(!0!==(await this.getNftPermissions(t,e)).manager||e!==a&&!0!==(await this.getNftPermissions(t,e)).updateMetadata)throw new Error("Caller is not Manager nor Metadata Updater");const s=await r.removeFromMetadataList.estimateGas(a);return i?s:await st(s,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,r.removeFromMetadataList,a)}async addStoreUpdater(t,e,a,i){var n;const r=this.getContract(t);if(!0!==(await this.getNftPermissions(t,e)).manager)throw new Error("Caller is not Manager");const s=await r.addTo725StoreList.estimateGas(a);return i?s:await st(s,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,r.addTo725StoreList,a)}async removeStoreUpdater(t,e,a,i){var n;const r=this.getContract(t);if(!0!==(await this.getNftPermissions(t,e)).manager||e!==a&&!0!==(await this.getNftPermissions(t,e)).store)throw new Error("Caller is not Manager nor storeUpdater");const s=await r.removeFrom725StoreList.estimateGas(a);return i?s:await st(s,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,r.removeFrom725StoreList,a)}async cleanPermissions(t,e,a){var i;const n=this.getContract(t);if(await this.getNftOwner(t)!==e)throw new Error("Caller is not NFT Owner");const r=await n.cleanPermissions.estimateGas();return a?r:await st(r,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,n.cleanPermissions)}async transferNft(t,e,a,i,n){var r;const s=this.getContract(t);if(await this.getNftOwner(t)!==e)throw new Error("Caller is not NFT Owner");const o=i||1,c=await s.transferFrom.estimateGas(e,a,o);return n?c:await st(c,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,s.transferFrom,e,a,o)}async safeTransferNft(t,e,a,i,n){var r;const s=this.getContract(t);if(await this.getNftOwner(t)!==e)throw new Error("Caller is not NFT Owner");const o=i||1,c=await s.safeTransferFrom.estimateGas(e,a,o);return n?c:await st(c,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,s.safeTransferFrom,e,a,o)}async setMetadata(t,e,a,i,n,r,s,o,c,l){var d;const u=this.getContract(t);if(c||(c=[]),!(await this.getNftPermissions(t,e)).updateMetadata)throw new Error("Caller is not Metadata updater");const h=await u.setMetaData.estimateGas(a,i,n,r,s,o,c);return l?h:await st(h,this.signer,null==(d=this.config)?void 0:d.gasFeeMultiplier,u.setMetaData,a,i,n,r,s,o,c)}async setMetadataAndTokenURI(t,e,a,i){var n;const r=this.getContract(t);if(!(await this.getNftPermissions(t,e)).updateMetadata)throw new Error("Caller is not Metadata updater");const s=$({},a,{metadataProofs:a.metadataProofs||[]}),o=await r.setMetaDataAndTokenURI.estimateGas(s);return i?o:await st(o,this.signer,null==(n=this.config)?void 0:n.gasFeeMultiplier,r.setMetaDataAndTokenURI,s)}async setMetadataState(t,e,a,i){var n;const r=this.getContract(t);if(!(await this.getNftPermissions(t,e)).updateMetadata)throw new Error("Caller is not Metadata updater");const s=await r.setMetaDataState.estimateGas(a);return i?s:await st(s,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,r.setMetaDataState,a)}async setTokenURI(t,e,a){var i;const n=this.getContract(t),r=await n.setTokenURI.estimateGas("1",e);return a?r:await st(r,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,n.setTokenURI,"1",e)}async getNftOwner(t){const e=this.getContract(t);return await e.ownerOf(1)}async getNftPermissions(t,e){const a=this.getContract(t);return await a.getPermissions(e)}async getMetadata(t){const e=this.getContract(t);return await e.getMetaData()}async isDatatokenDeployer(t,e){const a=this.getContract(t);return await a.isERC20Deployer(e)}async setData(t,e,a,i,n){var r;if(!0!==(await this.getNftPermissions(t,e)).store)throw new Error("User is not ERC20 store updater");const l=this.getContract(t),d=o(a),u=c(s(i)),h=await l.setNewData.estimateGas(d,u);return n?h:await st(h,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,l.setNewData,d,u)}async getData(t,e){const a=this.getContract(t),i=o(e),n=await a.getData(i);return n?l(n):null}async getTokenURI(t,e){const a=this.getContract(t);return await a.tokenURI(e)}async isDatatokenDeployed(t,e){const a=this.getContract(t);return await a.isDeployed(e)}}class St extends ot{getDefaultAbi(){return T.abi}constructor(t,e,a,i,n){super(t,e,a,i),this.abiEnterprise=void 0,this.nft=void 0,this.abiEnterprise=n||k.abi,this.nft=new Et(this.signer,e)}async approve(t,e,a,i){var n;const r=this.getContract(t),s=await r.approve.estimateGas(e,nt(null,null,a,18));return i?s:await st(s,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,r.approve,e,nt(null,null,a,18))}async createFixedRate(t,e,a,i){var n;const r=this.getContract(t);if(!await this.isDatatokenDeployer(t,e))throw new Error("User is not Datatoken Deployer");a.allowedConsumer||(a.allowedConsumer=dt);const s=!1===a.withMint?0:1,o=await r.createFixedRate.estimateGas(a.fixedRateAddress,[a.baseTokenAddress,a.owner,a.marketFeeCollector,a.allowedConsumer],[a.baseTokenDecimals,a.datatokenDecimals,a.fixedRate,a.marketFee,s]);return i?o:await st(o,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,r.createFixedRate,a.fixedRateAddress,[a.baseTokenAddress,a.owner,a.marketFeeCollector,a.allowedConsumer],[a.baseTokenDecimals,a.datatokenDecimals,a.fixedRate,a.marketFee,s])}async createDispenser(t,e,a,i,n){var r;if(!await this.isDatatokenDeployer(t,e))throw new Error("User is not Datatoken Deployer");const s=this.getContract(t);i.allowedSwapper||(i.allowedSwapper=dt),i.withMint=!1!==i.withMint;const o=await s.createDispenser.estimateGas(a,i.maxTokens,i.maxBalance,i.withMint,i.allowedSwapper);return n?o:await st(o,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,s.createDispenser,a,i.maxTokens,i.maxBalance,i.withMint,i.allowedSwapper)}async mint(t,e,a,i,n){const r=this.getContract(t);if(!0!==(await this.getPermissions(t,e)).minter)throw new Error("Caller is not Minter");const s=await this.getCap(t);if(new m(s).gte(a)){var o;const t=await r.mint.estimateGas(i||e,nt(null,null,a,18));return n?t:await st(t,this.getSignerAccordingSdk(),null==(o=this.config)?void 0:o.gasFeeMultiplier,r.mint,i||e,nt(null,null,a,18))}throw new Error("Mint amount exceeds cap available")}async addMinter(t,e,a,i){var n;const r=this.getContract(t);if(!0!==await this.isDatatokenDeployer(t,e))throw new Error("Caller is not DatatokenDeployer");const s=await r.addMinter.estimateGas(a);return i?s:await st(s,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,r.addMinter,a)}async removeMinter(t,e,a,i){var n;const r=this.getContract(t);if(!0!==await this.isDatatokenDeployer(t,e))throw new Error("Caller is not DatatokenDeployer");const s=await r.removeMinter.estimateGas(a);return i?s:await st(s,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,r.removeMinter,a)}async addPaymentManager(t,e,a,i){var n;const r=this.getContract(t);if(!0!==await this.isDatatokenDeployer(t,e))throw new Error("Caller is not DatatokenDeployer");const s=await r.addPaymentManager.estimateGas(a);return i?s:await st(s,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,r.addPaymentManager,a)}async removePaymentManager(t,e,a,i){var n;const r=this.getContract(t);if(!0!==await this.isDatatokenDeployer(t,e))throw new Error("Caller is not DatatokenDeployer");const s=await r.removePaymentManager.estimateGas(a);return i?s:await st(s,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,r.removePaymentManager,a)}async setPaymentCollector(t,e,a,i){var n;const r=this.getContract(t),s=(await this.getPermissions(t,e)).paymentManager,o=!s&&await this.getNFTAddress(t),c=o&&await this.nft.getNftOwner(o)===e,l=o&&!c&&await this.nft.getNftPermissions(o,e);if(!s&&!c&&!(null==l?void 0:l.deployERC20))throw new Error("Caller is not Fee Manager, owner or Datatoken Deployer");const d=await r.setPaymentCollector.estimateGas(a);return i?d:await st(d,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,r.setPaymentCollector,a)}async getPaymentCollector(t){const e=this.getContract(t);return await e.getPaymentCollector()}async transfer(t,e,a,i){return this.transferWei(t,e,await nt(null,null,a,18),i)}async transferWei(t,e,a,i){var n;const r=this.getContract(t),s=await r.transfer.estimateGas(e,a);return i?s:await st(s,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,r.transfer,e,a)}async startOrder(t,e,a,i,n,r){var s;const o=this.getContract(t,this.abi);n||(n={consumeMarketFeeAddress:dt,consumeMarketFeeToken:dt,consumeMarketFeeAmount:"0"});const c=await o.startOrder.estimateGas(e,a,i,n);return r?c:await st(c,this.getSignerAccordingSdk(),null==(s=this.config)?void 0:s.gasFeeMultiplier,o.startOrder,e,a,i,n)}async reuseOrder(t,e,a,i){var n;const r=this.getContract(t),s=await r.reuseOrder.estimateGas(e,a);return i?s:await st(s,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,r.reuseOrder,e,a)}async buyFromFreAndOrder(t,e,a,i){var n;const r=this.getContract(t,this.abiEnterprise),s=await this.getFreOrderParams(a),o=await r.buyFromFreAndOrder.estimateGas(e,s);return i?o:await st(o,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,r.buyFromFreAndOrder,e,s)}async buyFromDispenserAndOrder(t,e,a,i){var n;const r=this.getContract(t,this.abiEnterprise),s=await r.buyFromDispenserAndOrder.estimateGas(e,a);return i?s:await st(s,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,r.buyFromDispenserAndOrder,e,a)}async setData(t,e,a,i){var n;if(!await this.isDatatokenDeployer(t,e))throw new Error("User is not Datatoken Deployer");const r=this.getContract(t),o=c(s(a)),l=await r.setData.estimateGas(o);return i?l:await st(l,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,r.setData,o)}async cleanPermissions(t,e,a){var i;if(await this.nft.getNftOwner(await this.getNFTAddress(t))!==e)throw new Error("Caller is NOT Nft Owner");const n=this.getContract(t),r=await n.cleanPermissions.estimateGas();return a?r:await st(r,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,n.cleanPermissions)}async getPermissions(t,e){const a=this.getContract(t);return await a.permissions(e)}async getCap(t){const e=this.getContract(t),a=await e.cap();return await this.unitsToAmount(null,a,18)}async getDecimals(t){const e=this.getContract(t),a=await e.decimals();return Number(a)}async getId(t){const e=this.getContract(t),a=await e.getId();return Number(a)}async getSymbol(t){const e=this.getContract(t);return await e.symbol()}async getName(t){const e=this.getContract(t);return await e.name()}async getNFTAddress(t){const e=this.getContract(t);return await e.getERC721Address()}async getFixedRates(t){const e=this.getContract(t);return await e.getFixedRates()}async getDispensers(t){const e=this.getContract(t);return await e.getDispensers()}async isDatatokenDeployer(t,e){const a=this.getContract(t);return await a.isERC20Deployer(e)}async balance(t,e){const a=this.getContract(t),i=await a.balanceOf(e);return await this.unitsToAmount(null,i,18)}async allowance(t,e,a,i=18){const n=this.getContract(t),r=await n.allowance(e,a);return await this.unitsToAmount(null,r,i)}async setPublishingMarketFee(t,e,a,i,n,r){var s;const o=this.getContract(t);if((await o.getPublishingMarketFee())[0]!==n)throw new Error("Caller is not the Publishing Market Fee Address");const c=await o.setPublishingMarketFee.estimateGas(e,a,i);return r?c:await st(c,this.getSignerAccordingSdk(),null==(s=this.config)?void 0:s.gasFeeMultiplier,o.setPublishingMarketFee,e,a,i)}async getPublishingMarketFee(t){const e=this.getContract(t),a=await e.getPublishingMarketFee();return{publishMarketFeeAddress:a[0],publishMarketFeeToken:a[1],publishMarketFeeAmount:a[2].toString()}}async getFreOrderParams(t){return{exchangeContract:t.exchangeContract,exchangeId:t.exchangeId,maxBaseTokenAmount:await nt(this.signer,t.baseTokenAddress,t.maxBaseTokenAmount,t.baseTokenDecimals),swapMarketFee:await nt(this.signer,t.baseTokenAddress,t.swapMarketFee,t.baseTokenDecimals),marketFeeAddress:t.marketFeeAddress}}}class bt extends St{getDefaultAbi(){return A.abi}constructor(t,e,a,i,n){super(t,a,i,n),this.accessList=void 0,this.fileObject=void 0,this.abi=this.getDefaultAbi(),this.fileObject=e}setFileObj(t){this.fileObject=t}async getAllowlistContract(t){const e=this.getContract(t,this.getDefaultAbi());return await e.getAllowListContract()}async getDenylistContract(t){const e=this.getContract(t,this.getDefaultAbi());return await e.getDenyListContract()}async setAllowListContract(t,e,a,i){var n;if(!await this.isDatatokenDeployer(t,a))throw new Error("User is not Datatoken Deployer");const r=this.getContract(t),s=await r.setAllowListContract.estimateGas(e);return i?s:await st(s,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,r.setAllowListContract,e)}async setDenyListContract(t,e,a,i){var n;if(!await this.isDatatokenDeployer(t,a))throw new Error("User is not Datatoken Deployer");const r=this.getContract(t),s=await r.setDenyListContract.estimateGas(e);return i?s:await st(s,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,r.setDenyListContract,e)}async setFileObject(t,e,a){var i;if(!await this.isDatatokenDeployer(t,e))throw new Error("User is not Datatoken Deployer");const n=this.getContract(t),r=await n.setFilesObject.estimateGas(this.fileObject);return a?r:await st(r,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,n.setFilesObject,this.fileObject)}async getFileObject(t,e,a,i,n,r,s){const o=this.getContract(t,this.getDefaultAbi());return await o.getFileObject(e,a,i,n,r,s)}}class At extends ct{getDefaultAbi(){return C.abi}constructor(t,e,a,i,n){super(t,e,a,i,n),this.abiEnterprise=void 0,this.abi=n||this.getDefaultAbi()}async getTokenUri(t){return await this.contract.tokenURI(t)}async getOwner(){return await this.contract.owner()}async getId(){const t=await this.contract.getId();return Number(t)}async getName(){return await this.contract.name()}async getSymbol(){return await this.contract.symbol()}async balance(t){const e=await this.contract.balanceOf(t);return await this.unitsToAmount(null,e,18)}async mint(t,e,a){var i;const n=await this.contract.mint.estimateGas(t,e);return a?n:await st(n,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.mint,t,e)}async batchMint(t,e,a){var i;const n=await this.contract.batchMint.estimateGas(t,e);return a?n:await st(n,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.batchMint,t,e)}async burn(t,e){var a;const i=await this.contract.burn.estimateGas(t);return e?i:await st(i,this.getSignerAccordingSdk(),null==(a=this.config)?void 0:a.gasFeeMultiplier,this.contract.burn,t)}async transferOwnership(t,e){var a;const i=await this.contract.transferOwnership.estimateGas(t);return e?i:await st(i,this.getSignerAccordingSdk(),null==(a=this.config)?void 0:a.gasFeeMultiplier,this.contract.transferOwnership,t)}async renounceOwnership(t){var e;const a=await this.contract.renounceOwnership.estimateGas();return t?a:await st(a,this.getSignerAccordingSdk(),null==(e=this.config)?void 0:e.gasFeeMultiplier,this.contract.renounceOwnership)}}class Ct extends ct{getDefaultAbi(){return F.abi}constructor(t,e,a,i,n){super(t,e,a,i,n),this.abi=n||this.getDefaultAbi()}async deployAccessListContract(t,e,a,i=!1,n,r,s){if(!t||!e){const{name:a,symbol:i}=ft();t=a,e=i}const o=await this.contract.deployAccessListContract.estimateGas(t,e,i,n,r,a);if(s)return o;try{var c;const s=await st(o,this.getSignerAccordingSdk(),null==(c=this.config)?void 0:c.gasFeeMultiplier,this.contract.deployAccessListContract,t,e,i,n,r,a);if(!s){const t="Tx for deploying new access list was not processed on chain.";throw console.error(t),t}return rt(await s.wait(),"NewAccessList").args[0]}catch(t){console.error(`Creation of AccessList failed: ${t}`)}}async getOwner(){return await this.contract.owner()}async isSoulbound(t){return await this.contract.isSoulBound(t)}async isDeployed(t){return await this.contract.isDeployed(t)}async changeTemplateAddress(t,e,a){var i;if(await this.getOwner()!==t)throw new Error("Caller is not Factory Owner");if(e===dt)throw new Error("Template address cannot be ZERO address");const n=await this.contract.changeTemplateAddress.estimateGas(e);return a?n:await st(n,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.changeTemplateAddress,e)}}class Ft extends ct{getDefaultAbi(){return D.abi}constructor(t,e,a,i,n){super(t,e,a,i,n),this.abiEnterprise=void 0,this.abi=n||this.getDefaultAbi()}async getFunds(t){return await this.contract.getFunds(t)}async getUserFunds(t,e){return await this.contract.getUserFunds(t,e)}async getUserTokens(t){return await this.contract.getUserTokens(t)}async getLocks(t,e,a){return await this.contract.getLocks(t,e,a)}async getAuthorizations(t,e,a){return await this.contract.getAuthorizations(t,e,a)}async verifyFundsForEscrowPayment(t,e,a,i,n,r,s){var o;const c=await(null==(o=this.signer.provider)?void 0:o.getBalance(d(e)));if(new p(c).isZero())return{isValid:!1,message:"Native token balance is 0. Please add funds"};const l=new St(this.signer),h=await l.allowance(t,await this.signer.getAddress(),this.contract.target.toString(),s);new p(await this.amountToUnits(t,h,18)).isLessThan(new p(i))&&await l.approve(d(t),d(this.contract.target.toString()),i);const g=await l.balance(t,await this.signer.getAddress());if(new p(g).isZero())return{isValid:!1,message:"Payment token balance is 0. Please add funds"};const w=await this.getAuthorizations(t,await this.signer.getAddress(),e),m=await this.getUserFunds(await this.signer.getAddress(),t);return new p(m[0]).isZero()&&(a&&new p(u(g)).isLessThanOrEqualTo(new p(u(a)))&&new p(u(a)).isGreaterThan(new p(i))?await this.deposit(t,a,s):new p(u(g)).isLessThanOrEqualTo(new p(u(i)))?await this.deposit(t,await this.unitsToAmount(t,i,s),s):await this.deposit(t,g,s)),0===w.length&&await this.authorize(d(t),d(e),(Number(i)/2).toString(),n,r),{isValid:!0,message:""}}async deposit(t,e,a,i){var n;const r=await this.amountToUnits(t,e,a),s=await this.contract.deposit.estimateGas(t,r);return i?s:await st(s,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,this.contract.deposit,t,r)}async withdraw(t,e,a,i){var n;const r=[],s=[];if(t.length!==e.length)throw new Error("Tokens and amounts arrays must have the same length");const o=await this.signer.getAddress();for(let a=0;a<t.length;a++){const i=t[a],n=new p(e[a]),c=await this.getUserFunds(o,i),l=new p(c[0]);n.isGreaterThan(0)&&n.isLessThanOrEqualTo(l)?(r.push(i),s.push(e[a])):console.log(`Insufficient funds for token ${i}`)}const c=await Promise.all(s.map((t,e)=>this.amountToUnits(r[e],t,a))),l=await this.contract.withdraw.estimateGas(t,c);return i?l:await st(l,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,this.contract.withdraw,r,c)}async authorize(t,e,a,i,n,r,s){var o;if(0!==(await this.getAuthorizations(t,await this.signer.getAddress(),e)).length)return console.log(`Payee ${e} already authorized`),null;const c=await this.amountToUnits(t,a,r),l=await this.amountToUnits(t,i,r),d=await this.amountToUnits(t,n,r),u=await this.contract.authorize.estimateGas(t,e,c,l,d);return s?u:await st(u,this.getSignerAccordingSdk(),null==(o=this.config)?void 0:o.gasFeeMultiplier,this.contract.authorize,t,e,c,l,d)}async cancelExpiredLocks(t,e,a,i,n){var r;const s=await this.contract.cancelExpiredLocks.estimateGas(t,e,a,i);return n?s:await st(s,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,this.contract.cancelExpiredLocks,t,e,a,i)}}class Dt extends ct{getDefaultAbi(){return x.abi}constructor(t,e,a,i,n){super(t,e,a,i,n),this.abi=n||this.getDefaultAbi()}async isTokenAllowed(t){return await this.contract.isTokenAllowed(t)}async getToken(t){return await this.contract.getToken(t)}async calculateFee(t,e,a){const i=this.amountToUnits(t,e.toString(),a),n=await this.contract.calculateFee(t,i);return this.unitsToAmount(t,n,a)}}async function xt(t){return new Promise(e=>{setTimeout(e,t)})}function Ot(t){return null!=t}async function Mt(t,e){const a=h(e);let i=await t._legacySignMessage(a);i=i.substr(2);const n="0x"+i.slice(0,64),r="0x"+i.slice(64,128);let s="0x"+i.slice(128,130);return"0x00"===s&&(s="0x1b"),"0x01"===s&&(s="0x1c"),{v:s,r:n,s:r}}async function Nt(t,e){const i=a.solidityPackedKeccak256(["bytes"],[a.hexlify(a.toUtf8Bytes(e))]),n=a.toBeArray(i);try{return await t.signMessage(n)}catch(e){const a=await t.provider.getNetwork(),i=Number(a.chainId);if(8996===Number(i))return console.log("Signing message with _legacySignMessage"),await t._legacySignMessage(n)}}class Pt{constructor(t){this.aquariusURL=void 0,this.aquariusURL=t}getAuthorization(t){return"string"==typeof t?t:void 0}async resolve(t,e,a){const i=this.aquariusURL+"/api/aquarius/assets/ddo/"+t;try{const t=await O(i,{method:"GET",headers:{"Content-Type":"application/json",Authorization:a},signal:e});if(t.ok)return await t.json();throw new Error("HTTP request failed with status "+t.status)}catch(t){throw J.error(t),new Error("HTTP request failed")}}async waitForIndexer(t,e,a,i=3e4,n=100,r){let s=0;n>500&&(J.warn("Max Limit exceeded, defaulting to 500 retries."),n=500);do{try{const i=this.aquariusURL+"/api/aquarius/assets/ddo/"+t,n=await O(i,{method:"GET",headers:{"Content-Type":"application/json",Authorization:r},signal:a});if(n.ok){const t=await n.json(),a=M.getDDOClass(t),{indexedMetadata:i}=a.getAssetFields();if(!e)return t;if(i.event&&i.event.txid===e)return t}}catch(t){}await xt(i),s++}while(s<n);return null}async validate(t,e,a,i,n){const r=a+"/api/aquarius/assets/ddo/validate",s=a+"/api/services/nonce";try{const a=await e.getAddress(),o=await O(s+`?userAddress=${a}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:n},signal:i});let{nonce:c}=await o.json();console.log(`[getNonce] Consumer: ${a} nonce: ${c}`),c&&null!==c||(c="0");const l=(Number(c)+1).toString(),d=String(String(await e.getAddress())+String(l)+String(_.VALIDATE_DDO)),u={ddo:t,publisherAddress:a,nonce:l,signature:await Nt(e,d)},h=await O(r,{method:"POST",body:JSON.stringify(u),headers:{"Content-Type":"application/json",Authorization:this.getAuthorization(e)},signal:i}),g=await h.json();if(200!==h.status)throw new Error("Metadata validation failed");return{valid:!0,hash:g.hash,proof:{validatorAddress:g.publicKey,r:g.r[0],s:g.s[0],v:g.v}}}catch(t){J.error("Metadata validation failed",t.message)}}async getAssetMetadata(t,e,a){const i=this.aquariusURL+"/api/aquarius/assets/metadata/"+t;try{const t=await O(i,{method:"GET",headers:{"Content-Type":"application/json",Authorization:a},signal:e});if(t.ok)return t.json();throw new Error("getAssetMetadata failed: "+t.status+t.statusText)}catch(t){throw J.error("Error getting metadata: ",t),new Error("Error getting metadata: "+t)}}async querySearch(t,e,a){const i=this.aquariusURL+"/api/aquarius/assets/query";try{const n=await O(i,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/json",Authorization:a},signal:e});if(n.ok)return n.json();throw new Error("querySearch failed: "+n.status+n.statusText)}catch(t){throw J.error("Error querying metadata: ",t),new Error("Error querying metadata: "+t)}}}class Rt{async getConsumerAddress(t){return"string"==typeof t?function(t){try{return N.decode(t,{json:!0})}catch(t){throw new Error("Error decoding JWT")}}(t).address:await t.getAddress()}async getSignature(t,e,a){if("string"==typeof t)return null;const i=String(String(await t.getAddress())+String(e)+String(a));return Nt(t,i)}getAuthorization(t){return"string"==typeof t?t:void 0}async getEndpoints(t,e){try{const a=await this.getData(t,e);return await a.json()}catch(t){throw J.error("Finding the service endpoints failed:",t),new Error("HTTP request failed calling Provider")}}async getNodePublicKey(t){return(await this.getEndpoints(t)).nodePublicKey}getEndpointURL(t,e){return t?t.find(t=>t.serviceName.toLowerCase()===e.toLowerCase()):null}async getServiceEndpoints(t,e){const a=[];for(const i in e.serviceEndpoints){const n={serviceName:i,method:e.serviceEndpoints[i][0],urlPath:t.replace(/\/+$/,"")+"/"+e.serviceEndpoints[i][1].replace(/^\/+/,"")};a.push(n)}return a}async getNonce(t,e,a,i,n){i||(i=await this.getEndpoints(t)),n||(n=await this.getServiceEndpoints(t,i));const r=this.getEndpointURL(n,"nonce")?this.getEndpointURL(n,"nonce").urlPath:null;if(!r)return null;try{const t=await O(r+`?userAddress=${e}`,{method:"GET",headers:{"Content-Type":"application/json"},signal:a}),{nonce:i}=await t.json();return console.log(`[getNonce] Consumer: ${e} nonce: ${i}`),i&&null!==i?Number(i):0}catch(t){throw J.error(t),new Error(t.message)}}async encrypt(t,e,a,i,n,r){const s=await this.getEndpoints(a),o=await this.getServiceEndpoints(a,s),c=await this.getConsumerAddress(i),l=(await this.getNonce(a,c,r,s,o)+1).toString(),d=await this.getSignature(i,l,_.ENCRYPT);let u=(this.getEndpointURL(o,"encrypt")?this.getEndpointURL(o,"encrypt").urlPath:null)+`?chainId=${e}`;if(!u)return null;u+=`&nonce=${l}`,u+=`&consumerAddress=${c}`,u+=`&signature=${d}`;try{const e=await O(u,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/octet-stream"},signal:r});return await e.text()}catch(t){throw J.error(t),new Error("HTTP request failed calling Provider")}}async checkDidFiles(t,e,a,i=!1,n){var r;const s=await this.getEndpoints(a),o=await this.getServiceEndpoints(a,s),c={did:t,serviceId:e,checksum:i},l=[],d=this.getEndpointURL(o,"fileinfo")?this.getEndpointURL(o,"fileinfo").urlPath:null;if(!d)return null;let u;try{u=await O(d,{method:"POST",body:JSON.stringify(c),headers:{"Content-Type":"application/json"},signal:n})}catch(t){throw J.error("File info call failed: "),J.error(t),new Error(t)}if(null!=(r=u)&&r.ok){const t=await u.json();for(const e of t)l.push(e);return l}const h=await u.json();throw J.error("File info call failed: ",u.status,u.statusText,h),new Error(JSON.stringify(h))}async getFileInfo(t,e,a=!1,i){var n;const r=await this.getEndpoints(e),s=await this.getServiceEndpoints(e,r),o=$({},t,{checksum:a}),c=[],l=this.getEndpointURL(s,"fileinfo")?this.getEndpointURL(s,"fileinfo").urlPath:null;if(!l)return null;let d;try{d=await O(l,{method:"POST",body:JSON.stringify(o),headers:{"Content-Type":"application/json"},signal:i})}catch(t){throw J.error("File info call failed: "),J.error(t),new Error(t)}if(null!=(n=d)&&n.ok){const t=await d.json();for(const e of t)c.push(e);return c}const u=await d.json();throw J.error("File info call failed: ",d.status,d.statusText,u),new Error(JSON.stringify(u))}async getComputeEnvironments(t,e){var a,i;const n=await this.getEndpoints(t),r=await this.getServiceEndpoints(t,n),s=null==(a=this.getEndpointURL(r,"computeEnvironments"))?void 0:a.urlPath;if(!s)return null;let o;try{o=await O(s,{method:"GET",headers:{"Content-Type":"application/json"},signal:e})}catch(t){throw J.error("Fetch compute env failed: "),J.error(t),new Error(t)}if(null!=(i=o)&&i.ok)return o.json();const c=await o.json();throw J.error("Fetch compute env failed: ",o.status,o.statusText,c),new Error(JSON.stringify(c))}async initialize(t,e,a,i,n,r,s,o,c){var l;const d=await this.getEndpoints(n),u=await this.getServiceEndpoints(n,d);let h,g=this.getEndpointURL(u,"initialize")?this.getEndpointURL(u,"initialize").urlPath:null;if(!g)return null;g+=`?documentId=${t}`,g+=`&serviceId=${e}`,g+=`&fileIndex=${a}`,g+=`&consumerAddress=${i}`,s&&(g+="&userdata="+encodeURI(JSON.stringify(s))),o&&(g+="&environment="+encodeURI(o)),c&&(g+="&validUntil="+c);try{h=await O(g,{method:"GET",headers:{"Content-Type":"application/json"},signal:r})}catch(t){throw J.error("Provider initialized failed: "),J.error(t),new Error(`Provider initialize failed url: ${g} `)}if(200===(null==(l=h)?void 0:l.status))return await h.json();const w=await h.json();throw J.error("Provider initialized failed: ",h.status,h.statusText,w),new Error(JSON.stringify(w))}async initializeComputeV1(t,e,a,i,n,r,s,o,c){var l;const d=await this.getEndpoints(i),u=await this.getServiceEndpoints(i,d),h={datasets:t,algorithm:e,payment:{chainId:r,token:s,maxJobDuration:o},consumerAddress:n,environment:a},g=this.getEndpointURL(u,"initializeCompute")?this.getEndpointURL(u,"initializeCompute").urlPath:null;if(!g)return null;let w;try{w=await O(g,{method:"POST",body:JSON.stringify(h),headers:{"Content-Type":"application/json"},signal:c})}catch(t){throw J.error("Initialize compute failed: "),J.error(t),new Error("ComputeJob cannot be initialized")}if(null!=(l=w)&&l.ok)return await w.json();const p=await w.json();throw J.error("Initialize compute failed: ",w.status,w.statusText,p),J.error("Payload was:",JSON.stringify(h)),new Error(JSON.stringify(p))}async initializeCompute(t,e,a,i,n,r,s,o,c,l,d,u){var h;const g=await this.getEndpoints(r),w=await this.getServiceEndpoints(r,g),p=this.getEndpointURL(w,"initializeCompute")?this.getEndpointURL(w,"initializeCompute").urlPath:null;if(!p)return null;const m=await this.getConsumerAddress(s),f=(await this.getNonce(r,m,u,g,w)+1).toString();let y;if("string"!=typeof s){var v;let e=m;e+=null==(v=t[0])?void 0:v.documentId,e+=f,y=await Nt(s,e)}const T={datasets:t,algorithm:e,environment:a,payment:{chainId:c,token:i,resources:o},maxJobDuration:n,consumerAddress:m,signature:y};if(d){const t=await this.getNodePublicKey(r);t&&(T.dockerRegistryAuth=function(t,e){const a=P.fromHex(t),i=R(a.toHex(),Buffer.from(e));return Buffer.from(i).toString("hex")}(t,JSON.stringify(d)))}let k;l&&(T.policyServer=l);try{if(console.log("Initialize compute url:",p),k=await O(p,{method:"POST",body:JSON.stringify(T),headers:{"Content-Type":"application/json",Authorization:this.getAuthorization(s)},signal:u}),console.log("Raw response:",k),!k.ok){const t=await k.text();throw new Error(`${t}`)}}catch(t){throw J.error("Initialize compute failed: "),J.error(t),new Error(`ComputeJob cannot be initialized: ${t.message}.`)}if(null!=(h=k)&&h.ok)return await k.json();const E=await k.json();throw J.error("Initialize compute failed: ",k.status,k.statusText,E),J.error("Payload was:",JSON.stringify(T)),new Error(JSON.stringify(E))}async getDownloadUrl(t,e,a,i,n,r,s,o){const c=await this.getEndpoints(n),l=await this.getServiceEndpoints(n,c),d=this.getEndpointURL(l,"download")?this.getEndpointURL(l,"download").urlPath:null;if(!d)return null;const u=await this.getConsumerAddress(r),h=(await this.getNonce(n,u,null,c,l)+1).toString(),g=await this.getSignature(r,h,_.DOWNLOAD);let w=d;return w+=`?fileIndex=${a}`,w+=`&documentId=${t}`,w+=`&transferTxId=${i}`,w+=`&serviceId=${e}`,w+=`&consumerAddress=${u}`,w+=`&nonce=${h}`,s&&(w+="&policyServer="+encodeURI(JSON.stringify(s))),w+=`&signature=${g}`,o&&(w+="&userdata="+encodeURI(JSON.stringify(o))),w}async computeStartV1(t,e,a,i,n,r,s,o){var c;const l=await this.getEndpoints(t),d=await this.getServiceEndpoints(t,l),u=this.getEndpointURL(d,"computeStart")?this.getEndpointURL(d,"computeStart").urlPath:null,h=await e.getAddress(),g=(await this.getNonce(t,h,r,l,d)+1).toString();let w=h;w+=i.documentId,w+=g;const p=await Nt(e,w),m=Object();if(m.consumerAddress=h,m.signature=p,m.nonce=g,m.environment=a,m.dataset=i,m.algorithm=n,s&&(m.additionalDatasets=s),o&&(m.output=o),!u)return null;let f;try{f=await O(u,{method:"POST",body:JSON.stringify(m),headers:{"Content-Type":"application/json"},signal:r})}catch(t){throw J.error("Compute start failed:"),J.error(t),J.error("Payload was:",m),new Error("HTTP request failed calling Provider")}return null!=(c=f)&&c.ok?await f.json():(J.error("Compute start failed: ",f.status,f.statusText,await f.json()),J.error("Payload was:",m),null)}async computeStart(t,e,a,i,n,r,s,o,c,l,d,u,h,g,w){var p;console.log("called new compute start method..."),console.log("datasets: ",i),console.log("algorithm: ",n);const m=await this.getEndpoints(t),f=await this.getServiceEndpoints(t,m),y=this.getEndpointURL(f,"computeStart")?this.getEndpointURL(f,"computeStart").urlPath:null;if(!y)return J.error("Compute start failed: Cannot get proper computeStart route (perhaps not implemented on provider?)"),null;const v=await this.getConsumerAddress(e),T=(await this.getNonce(t,v,g,m,f)+1).toString(),k=await this.getSignature(e,T,_.COMPUTE_START),E=Object();let S;E.consumerAddress=v,E.signature=k,E.nonce=T,E.environment=a,E.maxJobDuration=r,E.resources=o,E.dataset=i[0],E.datasets=i,E.algorithm=n,E.chainId=c,E.payment={chainId:c,token:s,maxJobDuration:r},o&&(E.resources=o),l&&(E.metadata=l),d&&(E.additionalViewers=d),u&&(E.output=u),h&&(E.policyServer=h),w&&(E.queueMaxWaitTime=w);try{S=await O(y,{method:"POST",body:JSON.stringify(E),headers:{"Content-Type":"application/json",Authorization:this.getAuthorization(e)},signal:g})}catch(t){throw J.error("Compute start failed:"),J.error(t),J.error("Payload was:",E),new Error("HTTP request failed calling Provider")}if(null!=(p=S)&&p.ok)return await S.json();const b=await S.json();throw J.error("Compute start failed: ",S.status,S.statusText,b),J.error("Payload was:",E),new Error(JSON.stringify(b))}async freeComputeStart(t,e,a,i,n,r,s,o,c,l,d,u){var h;console.log("called new free compute start method..."),console.log("datasets: ",i),console.log("algorithm: ",n);const g=await this.getEndpoints(t),w=await this.getServiceEndpoints(t,g),p=this.getEndpointURL(w,"freeCompute")?this.getEndpointURL(w,"freeCompute").urlPath:null;if(!p)return J.error("Compute start failed: Cannot get proper computeStart route (perhaps not implemented on provider?)"),null;const m=await this.getConsumerAddress(e),f=(await this.getNonce(t,m,d,g,w)+1).toString(),y=await this.getSignature(e,f,_.FREE_COMPUTE_START),v=Object();let T;v.consumerAddress=m,v.signature=y,v.nonce=f,v.environment=a,v.resources=r,v.dataset=i[0],v.datasets=i,v.algorithm=n,s&&(v.metadata=s),o&&(v.additionalViewers=o),v.output=c,l&&(v.policyServer=l),u&&(v.queueMaxWaitTime=u);try{T=await O(p,{method:"POST",body:JSON.stringify(v),headers:{"Content-Type":"application/json",Authorization:this.getAuthorization(e)},signal:d})}catch(t){throw J.error("Compute start failed:"),J.error(t),J.error("Payload was:",v),new Error("HTTP request failed calling Provider")}if(null!=(h=T)&&h.ok)return await T.json();const k=await T.json();throw J.error("Compute start failed: ",T.status,T.statusText,k),J.error("Payload was:",v),new Error(JSON.stringify(k))}async computeStreamableLogs(t,e,a,i){var n,r;const s="string"==typeof e,o=await this.getEndpoints(t),c=await this.getServiceEndpoints(t,o),l=this.getEndpointURL(c,"computeStreamableLogs")?this.getEndpointURL(c,"computeStreamableLogs").urlPath:null;if(!l)return J.error("Compute start failed: Cannot get proper computeStreamableLogs route (perhaps not implemented on provider?)"),null;const d=await this.getConsumerAddress(e),u=(await this.getNonce(t,d,i,o,c)+1).toString();let h,g=`?consumerAddress=${d}&jobId=${a}`;s||(g+=`&signature=${await this.getSignature(e,u,_.COMPUTE_GET_STREAMABLE_LOGS)}`,g+=`&nonce=${u}`);try{h=await O(l+g,{method:"GET",headers:{"Content-Type":"application/json",Authorization:this.getAuthorization(e)},signal:i}),console.log("Raw response:",h)}catch(t){throw J.error("computeStreamableLogs failed:"),J.error(t),new Error("HTTP request failed calling Provider")}return null!=(n=h)&&n.ok||200===(null==(r=h)?void 0:r.status)?(console.log("Response body:",h.body),h.body):(J.error("computeStreamableLogs failed: ",h.status,h.statusText,await h.json()),null)}async getComputeStartRoutes(t,e=!1){const a=await this.getEndpoints(t),i=await this.getServiceEndpoints(t,a);let n=null;return n=e?this.getEndpointURL(i,"freeCompute")?this.getEndpointURL(i,"freeCompute").urlPath:null:this.getEndpointURL(i,"computeStart")?this.getEndpointURL(i,"computeStart").urlPath:null,n}async computeStop(t,e,a,i,n){var r;const s="string"==typeof a,o=await this.getEndpoints(e),c=await this.getServiceEndpoints(e,o),l=this.getEndpointURL(c,"computeStop")?this.getEndpointURL(c,"computeStop").urlPath:null,d=await this.getConsumerAddress(a),u=(await this.getNonce(e,d,n,o,c)+1).toString(),h=await this.getSignature(a,u,_.COMPUTE_STOP),g=new URLSearchParams;g.set("consumerAddress",d),g.set("nonce",u),g.set("jobId",t),s||g.set("signature",h),i&&g.set("agreementId",i);const w=g.toString();if(!w)return null;let p;try{p=await O(l+"?"+w,{method:"PUT",headers:{"Content-Type":"application/json",Authorization:this.getAuthorization(a)},signal:n})}catch(t){throw J.error("Compute stop failed:"),J.error(t),new Error("HTTP request failed calling Provider")}if(null!=(r=p)&&r.ok)return await p.json();const m=await p.json();throw J.error("Compute stop failed: ",p.status,p.statusText,m),new Error(JSON.stringify(m))}async computeStatus(t,e,a,i,n,r){var s,o;const c=await this.getEndpoints(t),l=await this.getServiceEndpoints(t,c),d=this.getEndpointURL(l,"computeStatus")?this.getEndpointURL(l,"computeStatus").urlPath:null;let u,h=`?consumerAddress=${e}`;if(h+=i&&`&agreementId=${i}`||"",h+=a&&`&jobId=${a}`||"",!d)return null;try{console.log("computeStatusUrl: ",d+h),u=await O(d+h,{method:"GET",headers:{"Content-Type":"application/json",Authorization:r},signal:n})}catch(t){throw J.error("Get compute status failed"),J.error(t),new Error(t)}if(null!=(s=u)&&s.ok)return await u.json();if(J.error("Get compute status failed:",u.status,u.statusText),null!=(o=u)&&o.ok)return await u.json();const g=await u.json();throw J.error("Get compute status failed:",u.status,u.statusText,g),new Error(JSON.stringify(g))}async getComputeResultUrl(t,e,a,i){const n="string"==typeof e,r=await this.getEndpoints(t),s=await this.getServiceEndpoints(t,r),o=this.getEndpointURL(s,"computeResult")?this.getEndpointURL(s,"computeResult").urlPath:null,c=await this.getConsumerAddress(e),l=(await this.getNonce(t,c,null,r,s)+1).toString(),d=await this.getSignature(e,l,_.COMPUTE_GET_RESULT);if(!o)return null;let u=o;return u+=`?consumerAddress=${c}`,u+=`&jobId=${a}`,u+=`&index=${i.toString()}`,n||(u+=`&nonce=${l}`,u+=`&signature=${d}`),u}async generateAuthToken(t,e,a){const i=await t.getAddress(),n=await this.getEndpoints(e),r=await this.getServiceEndpoints(e,n),s=this.getEndpointURL(r,"generateAuthToken").urlPath||null,o=(await this.getNonce(e,i,a,n,r)+1).toString(),c=await this.getSignature(t,o,_.CREATE_AUTH_TOKEN);try{const t=await O(s,{method:"POST",body:JSON.stringify({address:i,signature:c,nonce:o}),headers:{"Content-Type":"application/json"},signal:a});if(null==t||!t.ok)throw new Error(`Failed to generate auth token: ${t.status} ${t.statusText}`);const e=await t.json();return null==e?void 0:e.token}catch(t){throw J.error("Generate auth token failed:"),J.error(t),new Error("HTTP request failed calling Provider")}}async invalidateAuthToken(t,e,a,i){const n=await t.getAddress(),r=await this.getEndpoints(a),s=await this.getServiceEndpoints(a,r),o=this.getEndpointURL(s,"invalidateAuthToken").urlPath||null,c=(await this.getNonce(a,n,i,r,s)+1).toString(),l=n+c,d=await Nt(t,l);try{const t=await O(o,{method:"POST",body:JSON.stringify({address:n,signature:d,token:e,nonce:c}),headers:{"Content-Type":"application/json"},signal:i});if(null==t||!t.ok)throw new Error(`Failed to invalidate auth token: ${t.status} ${t.statusText}`);return await t.json()}catch(t){throw J.error("Generate auth token failed:"),J.error(t),new Error("HTTP request failed calling Provider")}}async isValidProvider(t,e){try{const a=await O(t,{method:"GET",headers:{"Content-Type":"application/json"},signal:e});if(null!=a&&a.ok){const t=await a.json();if(t&&(t.providerAddress||t.providerAddresses))return!0}return!1}catch(t){return J.error(`Error validating provider: ${t.message}`),!1}}async PolicyServerPassthrough(t,e,a){var i;const n=await this.getEndpoints(t),r=await this.getServiceEndpoints(t,n),s=this.getEndpointURL(r,"PolicyServerPassthrough")?this.getEndpointURL(r,"PolicyServerPassthrough").urlPath:null;if(!s)return null;let o;try{if(o=await O(s,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/json"},signal:a}),!o.ok){const t=await o.text();throw new Error(`${t}`)}}catch(t){throw J.error("PolicyServerPassthrough failed: "),J.error(t),new Error(`PolicyServerPassthrough failed: ${t.message}.`)}if(null!=(i=o)&&i.ok)return await o.json();const c=await o.json();throw J.error("PolicyServerPassthrough failed: ",o.status,o.statusText,c),J.error("Payload was:",JSON.stringify(e)),new Error(JSON.stringify(c))}async initializePSVerification(t,e,a){var i;const n=await this.getEndpoints(t),r=await this.getServiceEndpoints(t,n),s=this.getEndpointURL(r,"initializePSVerification")?this.getEndpointURL(r,"initializePSVerification").urlPath:null;if(!s)return null;let o;try{if(o=await O(s,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/json"},signal:a}),!o.ok){const t=await o.text();throw new Error(`${t}`)}}catch(t){throw J.error("initializePSVerification failed: "),J.error(t),new Error(`initializePSVerification failed: ${t.message}.`)}if(null!=(i=o)&&i.ok)return await o.json();const c=await o.json();throw J.error("initializePSVerification failed: ",o.status,o.statusText,c),J.error("Payload was:",JSON.stringify(e)),new Error(JSON.stringify(c))}async downloadNodeLogs(t,e,a,i,n,r,s,o,c){var l;const d=await this.getEndpoints(t),u=await this.getServiceEndpoints(t,d),h=this.getEndpointURL(u,"logs")?this.getEndpointURL(u,"logs").urlPath:null;if(!h)return J.error("Download node logs failed: Cannot get proper logs route (perhaps not implemented on provider?)"),null;const g=await e.getAddress(),w=(await this.getNonce(t,g,c,d,u)+1).toString(),p=await this.getSignature(e,w,_.GET_LOGS);let m,f=h+`?startTime=${a}&endTime=${i}`;n&&(f+=`&maxLogs=${n}`),r&&(f+=`&moduleName=${r}`),s&&(f+=`&level=${s}`),o&&(f+=`&page=${o}`);try{m=await O(f,{method:"POST",body:JSON.stringify({signature:p,nonce:w,address:g}),headers:{"Content-Type":"application/json"},signal:c})}catch(t){throw J.error("Download node logs failed:"),J.error(t),new Error("HTTP request failed calling Provider")}if(null!=(l=m)&&l.ok)return m.body;const y=await m.json();throw J.error("Download node logs failed: ",m.status,m.statusText,y),new Error(JSON.stringify(y))}noZeroX(t){return this.zeroXTransformer(t,!1)}zeroXTransformer(t="",e){const{valid:a,output:i}=this.inputMatch(t,/^(?:0x)*([a-f0-9]+)$/i,"zeroXTransformer");return(e&&a?"0x":"")+i}inputMatch(t,e,a){if("string"!=typeof t)throw J.debug("Not input string:"),J.debug(t),new Error(`[${a}] Expected string, input type: ${typeof t}`);const i=t.match(e);return i?{valid:!0,output:i[1]}:(J.warn(`[${a}] Input transformation failed.`),{valid:!1,output:t})}async getData(t,e){return O(t,{method:"GET",headers:{"Content-type":"application/json",Authorization:e}})}}const Ut=new Rt;function It(t,e){return t=d(t),`did:op:${U(t+e.toString(10)).toString()}`}function Lt(t){return U(t).toString()}function Gt(t){const e=new XMLHttpRequest;e.responseType="blob",e.open("GET",t),e.onload=()=>{const t=e.getResponseHeader("content-disposition"),a=null==t?void 0:t.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/),i=a&&a[1]?a[1]:"file",n=window.URL.createObjectURL(e.response),r=document.createElement("a");r.href=n,r.setAttribute("download",i),document.body.appendChild(r),r.click(),r.remove(),window.URL.revokeObjectURL(n)},e.send()}async function _t(t,e){const a=await fetch(t);if(!a.ok)throw new Error("Response error.");let i;try{i=a.headers.get("content-disposition").match(/attachment;filename=(.+)/)[1]}catch(a){try{i=t.split("/").pop()}catch(t){i=`file${e}`}}return{data:await a.arrayBuffer(),filename:i}}async function jt(t,e,i,n,r,s,o=!1,c,l){const d=new a.Contract(n,Z,t);if(!o){const e=await Bt(t,n,i,r);if(new m(e).greaterThanOrEqualTo(new m(s)))return new m(e).toNumber()}const u=await nt(t,n,s,c),h=await d.approve.estimateGas(r,u);return l?new m(h.toString()):await st(h,t,null==e?void 0:e.gasFeeMultiplier,d.approve,r,u)}async function $t(t,e,i,n,r,s,o=!1,c){const l=new a.Contract(n,Z,t);if(!o){const e=await qt(t,n,i,r);if(new p(e).isGreaterThan(new p(s)))return BigInt(e)}let d=null;const u=await l.approve.estimateGas(r,s);if(c)return u;try{d=await st(u,t,null==e?void 0:e.gasFeeMultiplier,l.approve,r,s)}catch(t){J.error(`ERROR: Failed to approve spender to spend tokens : ${t.message}`)}return d}async function zt(t,e,i,n,r,s,o){const c=new a.Contract(i,Z,t),l=await nt(t,i,r,s),d=await c.transfer.estimateGas(n,l);return o?d:await st(d,t,null==e?void 0:e.gasFeeMultiplier,c.transfer,n,l)}async function Bt(t,e,i,n,r){const s=new a.Contract(e,Z,t),o=await s.allowance(i,n);return await it(t,e,o,r)}async function Jt(t,e,i,n){const r=new a.Contract(e,Z,t),s=await r.balanceOf(i);return await it(t,e,s,n)}async function qt(t,e,i,n){const r=new a.Contract(e,Z,t);return await r.allowance(i,n)}async function Wt(t,e){const i=new a.Contract(e,Z,t),n=await i.decimals();return Number(n)}const Ht={datasets:{invalid:"Datasets is not a list, as expected"},algorithm:{serviceId:{missing:"The serviceId key is missing from the algorithm s DDO.",not_found:"The provided serviceId does not exist.",service_not_access_compute:"Service type is neither access, nor compute.",main_service_compute:"If the main service is not compute for this asset when calling initialize endpoint.",compute_services_not_in_same_provider:"Files attached to the compute service are not decrypted by the correct provider. This occurs when both asset and algorithm are requested by their compute service which cannot be decrypted by a single provider as how it is supposed to be."},container:{checksum_prefix:"Container checksum does not start with the prefix sha256:.",mising_entrypoint_image_checksum:"Either entrypoint, either image, or either checksum are missing from the container dictionary from the algorithm s DDO."},documentId:{did_not_found:"The algorithm s DID could not be retrieved from the metadata store, because the algorithm asset does not exist.",missing:"The documentId key is missing from the algorithm s DDO."},transferTxId:{missing:"The transferTxId key is missing from the algorithm s DDO."},missing_meta_documentId:"Either algorithm metadata, or algorithm DID are missing.",did_not_found:"Either algorithm metadata, or algorithm DID are missing.",not_algo:"Either algorithm metadata, or algorithm DID are missing.",in_use_or_not_on_chain:"Either algorithm metadata, or algorithm DID are missing.",meta_oneof_url_rawcode_remote:"Either algorithm metadata, or algorithm DID are missing.",file_unavailable:"One possibility is that the asset could not be retrieved from Aquariuss database. Otherwise, there are issues related to services"},error:{not_trusted_algo_publisher:"The owner of the algorithm's DDO is not a trusted algorithms publishers list.",not_trusted_algo:"The algorithm's DID is not in the asset's trusted algorithms dictionary. ",no_publisherTrustedAlgorithms:"The algorithm's key publisherTrustedAlgorithms does not exist in the algorithm's DDO.",algorithm_file_checksum_mismatch:"filesChecksum from the algorithm's DDO is invalid.",algorithm_container_checksum_mismatch:"The containerChecksum from the algorithm's DDO is invalid.",no_raw_algo_allowed:"The asset does not allow raw algorithms to be run on it.","Asset malformed":"The asset published on chain is malformed, missing some required keys or not compliant with our schemas.","Asset is not consumable.":"Assets metadata status is not in the range of valid status codes for assets. The recognized states for the metadata are defined on our docs.","DID is not a valid algorithm.":"Either the algorithm assets DID is incorrectly typed, either the algorithm timeout expired.","Compute environment does not exist.":"The compute environment provided by the user does not exist, it is not served by our compute-to-data feature. The user can use get_c2d_environments to check the list of available compute environments.","The validUntil value is not correct.":"validUntil value is most probably expired.","Cannot resolve DID":"The dataset DID does not exist in the Metadata store.","Invalid serviceId":"The serviceId of that dataset is not correct.","Unable to get dataset files":"The files of that dataset could not be decrypted or retrieved","cannot decrypt files for this service.":"The files of that dataset could not be decrypted due to the fact that file object, which contains the structure and the type of specific file, is missing from the validation part.","Unsupported type ":"The file object type is not supported by Provider.","malformed file object":"The file object structure is invalid and does not contain the wanted information for the specific file."},order:{fees_not_paid:" Provider fees are not paid."},output:{invalid:"The algorithms validation after the build stage has not been decoded properly as a dictionary."}};function Vt(t){try{const a=JSON.parse(t),i=Object.keys(a)[0];if("error"===i){var e;const t=a[i];return(null==(e=Ht[i])?void 0:e[t])||`Provider request failed: ${t}`}{const t=a[i];return`${a[Object.keys(a)[1]]} : ${t}`}}catch(e){return J.error("[getErrorMessage] error: ",e),t}}async function Zt(t,e,a,i,n,r,s,o,c="0",l=0,d=0,u=0){const h=M.getDDOClass(t),{datatokens:g}=h.getAssetFields(),{chainId:w,services:p}=h.getDDOFields();s||(s={consumeMarketFeeAddress:"0x0000000000000000000000000000000000000000",consumeMarketFeeAmount:"0",consumeMarketFeeToken:"0x0000000000000000000000000000000000000000"});const f=(await e.provider.getNetwork()).chainId;if(w!==Number(f))throw new Error("Chain ID from DDO is different than the configured network.");if(!g[l].address)throw new Error(`The datatoken with index: ${l} does not exist for the asset with did: ${t.id}`);if(!p[d].id)throw new Error(`There is no service with index: ${d} defined for the asset with did: ${t.id}`);const y=await i.getId(g[l].address),v=await i.getFixedRates(g[l].address),T=await i.getDispensers(g[l].address),k=await i.getPublishingMarketFee(g[l].address),E=v.length>0?"fixed":T.length>0?"free":"NOT_ALLOWED",S=o||(await Ut.initialize(t.id,p[d].id,0,await e.getAddress(),n||a.oceanNodeUri)).providerFee;if(S&&S.providerFeeAddress!==dt&&S.providerFeeAmount&&parseInt(S.providerFeeAmount)>0)try{await $t(e,a,await e.getAddress(),S.providerFeeToken,p[0].datatokenAddress,S.providerFeeAmount)}catch(t){throw new Error(`Failed to approve provider fee token ${S.providerFeeToken}`)}const b={consumer:r||await e.getAddress(),serviceIndex:d,_providerFee:S,_consumeMarketFee:s};switch(E){case"free":if(1===y){const t=new lt(a.dispenserAddress,e),n=await t.dispense(g[l].address,"1",await e.getAddress());if(!n)throw new Error("Failed to dispense !");return await n.wait(),await i.startOrder(g[l].address,b.consumer,b.serviceIndex,b._providerFee,b._consumeMarketFee)}if(2===y||4===y)return await i.buyFromDispenserAndOrder(p[d].datatokenAddress,b,a.dispenserAddress);break;case"fixed":{const n=new wt(a.fixedRateExchangeAddress,e);if(!v[u].id)throw new Error(`There is no fixed rate exchange with index: ${d} for the asset with did: ${t.id}`);const r=await n.getFeesInfo(v[u].id),o=await n.getExchange(v[u].id),{baseTokenAmount:h}=await n.calcBaseInGivenDatatokensOut(r.exchangeId,"1",s.consumeMarketFeeAmount),w=new m(+h||0).add(new m(s.consumeMarketFeeAmount||0)).add(new m(+k.publishMarketFeeAmount||0)).toString(),p={exchangeContract:a.fixedRateExchangeAddress,exchangeId:r.exchangeId,maxBaseTokenAmount:w,baseTokenAddress:o.baseToken,baseTokenDecimals:parseInt(o.btDecimals)||18,swapMarketFee:c,marketFeeAddress:k.publishMarketFeeAddress};if(1===y){const t=await jt(e,a,await e.getAddress(),o.baseToken,a.fixedRateExchangeAddress,w,!1);if(!("number"!=typeof t?await t.wait():t))throw new Error(`Failed to approve ${o.baseToken} !`);const r=await n.buyDatatokens(o.exchangeId,"1",w,k.publishMarketFeeAddress,c);if(!await r.wait())throw new Error("Failed to buy datatoken from fixed rate!");return await i.startOrder(g[l].address,b.consumer,b.serviceIndex,b._providerFee,b._consumeMarketFee)}if(2===y||4===y){const t=await jt(e,a,await e.getAddress(),o.baseToken,g[l].address,w,!1);if(!t)throw new Error(`Failed to approve ${o.baseToken} !`);if(!("number"!=typeof t?await t.wait():t))throw new Error("Failed to confirm/mine approval transaction!");return await i.buyFromFreAndOrder(g[l].address,b,p)}break}default:throw new Error("Pricing schema not supported !")}}const Kt=8996;function Xt(t){const e=(new V).getConfig(t);return e&&"oasis"===e.sdk}async function Yt(t,e,i,n,r,o,l=!0,d,u,h,w,p,m,f,y){var v,T,k;const E=M.getDDOClass(o),{indexedMetadata:S}=E.getAssetFields(),b=(null==(v=E.getDDOData())||null==(v=v.stats)||null==(v=v.price)?void 0:v.value)||(null==S||null==(T=S.stats[0])||null==(T=T.prices[0])?void 0:T.price);let{chainId:C,nftAddress:F}=E.getDDOFields();const{services:D}=E.getDDOFields();if("string"!=typeof r&&"number"!=typeof r)throw new Error('Invalid template! Must be a "number" or a "string"');const x=(await i.provider.getNetwork()).chainId;if(C&&C!==Number(x))throw new Error("Chain ID from DDO is different than the configured network.");const O=(new V).getConfig(parseInt(String(x)));let N=await kt(i,O.nftFactoryAddress,r,Number(x));if(N<1){if(8996!==Number(x))throw new Error(`Invalid template index: ${N}`);N=1}const P=new Et(i,Number(x)),R=new yt(O.nftFactoryAddress,i,Number(x)),U=await i.getAddress(),G={name:t,symbol:e,templateIndex:1,tokenURI:"aaa",transferable:!0,owner:U},_={templateIndex:N,cap:"100000",feeAmount:"0",paymentCollector:U,feeToken:u||O.oceanTokenAddress,minter:U,mpFeeAddress:dt};let j;null!=n&&n.files[0].type&&[L.ARWEAVE,L.IPFS,L.URL].includes(null==n||null==(k=n.files[0])||null==(k=k.type)?void 0:k.toLowerCase())||(console.log('Missing or invalid files object type, defaulting to "url"'),n.type=L.URL),"oasis"===O.sdk&&(_.filesObject=n,_.accessListFactory=w||O.accessListFactory,_.allowAccessList=p,_.denyAccessList=m);try{if(b)if("0"===b.toString()){const t={dispenserAddress:O.dispenserAddress,maxTokens:"1",maxBalance:"100000000",withMint:!0,allowedSwapper:dt};j=await R.createNftWithDatatokenWithDispenser(G,_,t)}else{const t=f||O.oceanTokenAddress;y||(y=await at(this.signer,t));const e={fixedRateAddress:O.fixedRateExchangeAddress,baseTokenAddress:t,owner:U,marketFeeCollector:U,baseTokenDecimals:y,datatokenDecimals:18,fixedRate:b.toString(),marketFee:"0",allowedConsumer:U,withMint:!0};j=await R.createNftWithDatatokenWithFixedRate(G,_,e)}else j=await R.createNftWithDatatoken(G,_)}catch(t){return console.log("ERROR creating NFT bundle",t),null}const $=await j.wait(),z=rt($,"NFTCreated"),B=rt($,"TokenCreated"),J=z.args.newTokenAddress,q=B.args.newTokenAddress;if(n.datatokenAddress=q,n.nftAddress=J,"oasis"===O.sdk){const t=new a.Contract(q,A.abi,i);try{const e=await t.setFilesObject(s(JSON.stringify(n)));e.wait&&await e.wait()}catch(t){return console.log("Error updating files object with data token and nft addresses: ",t),null}}D[0].files="oasis"===O.sdk?"":await Ut.encrypt(n,Number(x),d,i,null),D[0].datatokenAddress=q,D[0].serviceEndpoint=d,F=J;const W=E.makeDid(F,C.toString());let H,Z,K;if(o=E.updateFields({id:W,nftAddress:F}),l)H=await Ut.encrypt(o,Number(x),d,i,null),Z=(await h.validate(o,i,d)).hash,K=2;else{const t=JSON.stringify(o),e=Buffer.from(t);H=c(e),Z="0x"+I("sha256").update(H).digest("hex"),K=0}return await P.setMetadata(F,await i.getAddress(),0,d,"",g(K),H,Z),o.id}async function Qt(t,e,i){const n=new a.Contract(t,F.abi,e),r=await e.getAddress();try{const t=await n.deployAccessListContract("AllowList","ALLOW",!0,r,i||[r],["https://oceanprotocol.com/nft/"]);if(t&&t.wait)return rt(await t.wait(),"NewAccessList").args[0]}catch(t){console.log("ERROR createAccessListFactory(): ",t)}return null}export{At as AccessListContract,Ct as AccesslistFactory,Pt as Aquarius,j as Config,V as ConfigHelper,Kt as DEVELOPMENT_CHAIN_ID,St as Datatoken,bt as Datatoken4,lt as Dispenser,G as EncryptMethod,Dt as EnterpriseFeeCollectorContract,Ft as EscrowContract,gt as FEE_HISTORY_NOT_SUPPORTED,L as FileObjectType,wt as FixedRateExchange,ut as GASLIMIT_DEFAULT,H as KNOWN_CONFIDENTIAL_EVMS,z as LogLevel,B as Logger,J as LoggerInstance,ht as MAX_UINT_256,Et as Nft,yt as NftFactory,_ as PROTOCOL_COMMANDS,Rt as Provider,Ut as ProviderInstance,pt as Router,ot as SmartContract,ct as SmartContractWithAddress,dt as ZERO_ADDRESS,Bt as allowance,qt as allowanceWei,nt as amountToUnits,jt as approve,$t as approveWei,Jt as balance,kt as calculateActiveTemplateIndex,W as configHelperNetworks,Qt as createAccessListFactory,Yt as createAsset,Wt as decimals,_t as downloadFile,Gt as downloadFileBrowser,It as generateDid,ft as generateDtName,Vt as getErrorMessage,rt as getEventFromTx,et as getFairGasPrice,Lt as getHash,vt as getOceanArtifactsAddresses,Tt as getOceanArtifactsAddressesByChainId,at as getTokenDecimals,Ot as isDefined,Z as minAbi,Zt as orderAsset,st as sendTx,tt as setContractDefaults,Mt as signHash,Nt as signRequest,xt as sleep,zt as transfer,it as unitsToAmount,Xt as useOasisSDK};
|
|
2
2
|
//# sourceMappingURL=lib.modern.js.map
|