@oceanprotocol/lib 4.3.5 → 4.3.6
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 +13 -3
- 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/utils/index.d.ts +1 -0
- package/package.json +1 -1
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,BigNumber as i}from"ethers";import*as n from"@oasisprotocol/sapphire-paratime";import r from"decimal.js";import s from"@oceanprotocol/contracts/artifacts/contracts/pools/dispenser/Dispenser.sol/Dispenser.json";import o from"@oceanprotocol/contracts/artifacts/contracts/pools/fixedRate/FixedRateExchange.sol/FixedRateExchange.json";import c from"@oceanprotocol/contracts/artifacts/contracts/pools/FactoryRouter.sol/FactoryRouter.json";import l from"@oceanprotocol/contracts/artifacts/contracts/templates/ERC20Template.sol/ERC20Template.json";import d from"@oceanprotocol/contracts/artifacts/contracts/templates/ERC20TemplateEnterprise.sol/ERC20TemplateEnterprise.json";import u from"@oceanprotocol/contracts/artifacts/contracts/templates/ERC721Template.sol/ERC721Template.json";import h from"@oceanprotocol/contracts/artifacts/contracts/ERC721Factory.sol/ERC721Factory.json";import g from"@oceanprotocol/contracts/artifacts/contracts/interfaces/IERC20Template.sol/IERC20Template.json";import w from"@oceanprotocol/contracts/artifacts/contracts/templates/ERC20Template4.sol/ERC20Template4.json";import p from"@oceanprotocol/contracts/artifacts/contracts/accesslists/AccessList.sol/AccessList.json";import m from"@oceanprotocol/contracts/artifacts/contracts/accesslists/AccessListFactory.sol/AccessListFactory.json";import f from"@oceanprotocol/contracts/artifacts/contracts/ve/veOCEAN.vy/veOCEAN.json";import y from"@oceanprotocol/contracts/artifacts/contracts/ve/veFeeDistributor.vy/veFeeDistributor.json";import v from"@oceanprotocol/contracts/artifacts/contracts/ve/veFeeEstimate.vy/veFeeEstimate.json";import k from"@oceanprotocol/contracts/artifacts/contracts/ve/veAllocate.sol/veAllocate.json";import T from"@oceanprotocol/contracts/artifacts/contracts/df/DFRewards.sol/DFRewards.json";import A from"@oceanprotocol/contracts/artifacts/contracts/df/DFStrategyV1.sol/DFStrategyV1.json";import S from"@oceanprotocol/contracts/artifacts/contracts/escrow/Escrow.sol/Escrow.json";import b from"@oceanprotocol/contracts/artifacts/contracts/communityFee/EnterpriseFeeCollector.sol/EnterpriseFeeCollector.json";import F from"cross-fetch";import{DDOManager as E}from"@oceanprotocol/ddo-js";import C from"jsonwebtoken";import D from"crypto-js/sha256.js";import{hexlify as x}from"ethers/lib/utils.js";import{createHash as M}from"crypto";var O,R,P;!function(t){t.URL="url",t.IPFS="ipfs",t.ARWEAVE="arweave"}(O||(O={})),function(t){t.AES="AES",t.ECIES="ECIES"}(R||(R={}));class U{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.veAllocate=void 0,this.veOCEAN=void 0,this.veDelegation=void 0,this.veFeeDistributor=void 0,this.veDelegationProxy=void 0,this.DFRewards=void 0,this.DFStrategyV1=void 0,this.veFeeEstimate=void 0,this.sdk=void 0,this.accessListFactory=void 0}}function N(){return N=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},N.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"}(P||(P={}));class I{constructor(t){this.logLevel=void 0,this.logLevel=t,this.logLevel=t||P.Error}setLevel(t){this.logLevel=t}bypass(...t){this.dispatch("log",-Infinity,...t)}debug(...t){this.dispatch("debug",P.Verbose,...t)}log(...t){this.dispatch("log",P.Log,...t)}warn(...t){this.dispatch("warn",P.Warn,...t)}error(...t){this.dispatch("error",P.Error,...t)}dispatch(t,e,...a){this.logLevel>=e&&console[t](...a)}}const L=new I,j={chainId:null,network:"unknown",nodeUri:"http://127.0.0.1:8545",oceanNodeUri:"https://1.c2d.nodes.oceanprotocol.com:8000/",explorerUri:null,oceanTokenAddress:null,oceanTokenSymbol:"OCEAN",fixedRateExchangeAddress:null,dispenserAddress:null,startBlock:0,transactionBlockTimeout:50,transactionConfirmationBlocks:1,transactionPollingTimeout:750,gasFeeMultiplier:1},G=[N({},j),N({},j,{chainId:8996,network:"development",oceanNodeUri:"https://1.c2d.nodes.oceanprotocol.com:8000/",sdk:"evm"}),N({},j,{chainId:11155111,network:"sepolia",nodeUri:"https://sepolia.infura.io/v3",explorerUri:"https://sepolia.etherscan.io",gasFeeMultiplier:1.1,sdk:"evm"}),N({},j,{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"}),N({},j,{chainId:137,network:"polygon",nodeUri:"https://polygon-mainnet.infura.io/v3",explorerUri:"https://polygonscan.com",oceanTokenSymbol:"mOCEAN",gasFeeMultiplier:1.6,sdk:"evm"}),N({},j,{chainId:2021e3,network:"gaiaxtestnet",nodeUri:"https://rpc.gaiaxtestnet.oceanprotocol.com",explorerUri:"https://blockscout.gaiaxtestnet.oceanprotocol.com",sdk:"evm"}),N({},j,{chainId:80001,network:"mumbai",nodeUri:"https://polygon-mumbai.infura.io/v3",explorerUri:"https://mumbai.polygonscan.com",gasFeeMultiplier:1.1,sdk:"evm"}),N({},j,{chainId:56,network:"bsc",nodeUri:"https://bsc-dataseed.binance.org",explorerUri:"https://bscscan.com/",gasFeeMultiplier:1.05,sdk:"evm"}),N({},j,{chainId:246,network:"energyweb",nodeUri:"https://rpc.energyweb.org",explorerUri:"https://explorer.energyweb.org",gasFeeMultiplier:1.05,sdk:"evm"}),N({},j,{chainId:1285,network:"moonriver",nodeUri:"https://moonriver.api.onfinality.io/public",explorerUri:"https://moonriver.moonscan.io/",gasFeeMultiplier:1.05,sdk:"evm"}),N({},j,{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"}),N({},j,{chainId:10,network:"optimism",nodeUri:"https://mainnet.optimism.io",explorerUri:"https://optimistic.etherscan.io/",gasFeeMultiplier:1.1,sdk:"evm"}),N({},j,{chainId:11155420,network:"optimism_sepolia",nodeUri:"https://sepolia.optimism.io",explorerUri:"https://sepolia-optimism.etherscan.io/",gasFeeMultiplier:1.1,sdk:"evm"}),N({},j,{chainId:23294,network:"oasis_sapphire",nodeUri:"https://sapphire.oasis.io",explorerUri:"https://explorer.oasis.io/mainnet/sapphire/",gasFeeMultiplier:1,sdk:"oasis"}),N({},j,{chainId:23295,network:"oasis_sapphire_testnet",nodeUri:"https://testnet.sapphire.oasis.dev",explorerUri:"https://explorer.oasis.io/testnet/sapphire/",gasFeeMultiplier:1,sdk:"oasis"}),N({},j,{chainId:32456,network:"pontus-x-devnet",nodeUri:"https://rpc.dev.pontus-x.eu",explorerUri:"https://explorer.dev.pontus-x.eu/testnet/pontusx",sdk:"evm"})],_=[23294,23295];class ${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,veAllocate:u,veOCEAN:h,veDelegation:g,veFeeDistributor:w,veDelegationProxy:p,DFRewards:m,DFStrategyV1:f,veFeeEstimate:y,Router:v,AccessListFactory:k,EnterpriseFeeCollector:T}=a[e];i=N({nftFactoryAddress:s,opfCommunityFeeCollector:o,fixedRateExchangeAddress:t,dispenserAddress:r,oceanTokenAddress:c,routerFactoryAddress:v,chainId:l,startBlock:d,veAllocate:u,veOCEAN:h,veDelegation:g,veFeeDistributor:w,veDelegationProxy:p,DFRewards:m,DFStrategyV1:f,veFeeEstimate:y,accessListFactory:k,EnterpriseFeeCollector:T},n())}else if(t[e]){const{FixedPrice:a,Dispenser:r,OPFCommunityFeeCollector:s,ERC721Factory:o,Ocean:c,chainId:l,startBlock:d,veAllocate:u,veOCEAN:h,veDelegation:g,veFeeDistributor:w,veDelegationProxy:p,DFRewards:m,DFStrategyV1:f,veFeeEstimate:y,Router:v,AccessListFactory:k,EnterpriseFeeCollector:T}=t[e];i=N({nftFactoryAddress:o,opfCommunityFeeCollector:s,fixedRateExchangeAddress:a,dispenserAddress:r,oceanTokenAddress:c,routerFactoryAddress:v,chainId:l,startBlock:d,veAllocate:u,veOCEAN:h,veDelegation:g,veFeeDistributor:w,veDelegationProxy:p,DFRewards:m,DFStrategyV1:f,veFeeEstimate:y,accessListFactory:k,EnterpriseFeeCollector:T},n())}return i}getConfig(t,a){const i="string"==typeof t?"network":"chainId";let n,r=G.find(e=>e[i]===t);if(!r)return L.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&&_.includes(r.chainId)&&(s=this.getAddressesFromEnv(r.network.replace("sapph","saph"),n)),"sdk"in r&&null!==r.sdk||(r.sdk=_.includes(r.chainId)?"oasis":"evm"),s&&"accessListFactory"in s&&(r.accessListFactory=s.accessListFactory),r=N({},r,s),N({},r,{nodeUri:a?`${r.nodeUri}/${a}`:r.nodeUri})}}const B=[{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"}],z=3e10,q=4e9,J=1e10,W=11155111;function V(t,e){return t}async function H(t,e){const i=await(await t.provider.getFeeData()).gasPrice,n=a.BigNumber.from(i.toString());return e?n.mul(e).toBigInt().toString(10):n.toString()}async function Z(t,e){return new a.Contract(e,B,t).decimals()}async function X(t,e,i,n){let r=n||await Z(t,e);return"0"===r&&(r=18),a.utils.formatUnits(i,r).toString()}async function K(t,e,i,n){let r=n||await Z(t,e);return"0"===r&&(r=18),a.utils.parseUnits(i,r).toString()}function Q(t,e){var a;return null==t||null==(a=t.events)?void 0:a.filter(t=>t.event===e)[0]}async function Y(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(s.maxPriorityFeePerGas.toNumber()*a).toString(),e=Math.round(s.maxFeePerGas.toNumber()*a).toString()),o={maxPriorityFeePerGas:(80001===r||137===r)&&Number(t)<z?z:r===W&&Number(t)<q?q:_.includes(r)&&Number(t)<J?J:Number(t),maxFeePerGas:(80001===r||137===r)&&Number(e)<z?z:r===W&&Number(e)<q?q:_.includes(r)&&Number(e)<J?J:Number(e)}}else o={gasPrice:s.gasPrice};o.gasLimit=t.add(2e4);try{const t=await i(...n,o);return await t.wait(),t}catch(t){return L.error("Send tx error: ",t),null}}class tt{constructor(t,e,a,i){this.signer=void 0,this.config=void 0,this.abi=void 0,this.signer=t,this.config=a||(new $).getConfig(e),this.abi=i||this.getDefaultAbi()}getSignerAccordingSdk(){return this.config&&"sdk"in this.config&&"oasis"===this.config.sdk?n.wrap(this.signer):this.signer}async amountToUnits(t,e,a){return K(this.signer,t,e,a)}async unitsToAmount(t,e,a){return X(this.signer,t,e,a)}async getFairGasPrice(){var t;return H(this.signer,null==(t=this.config)?void 0:t.gasFeeMultiplier)}getContract(t,e){return V(new a.Contract(t,new a.utils.Interface(JSON.stringify(e||this.abi)),this.signer))}}class et extends tt{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 at extends et{getDefaultAbi(){return s.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.estimateGas.create(t,this.amountToUnits(null,a,18),this.amountToUnits(null,i,18),e,n);return r?o:await Y(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.estimateGas.activate(t,this.amountToUnits(null,e,18),this.amountToUnits(null,a,18));return i?r:await Y(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.estimateGas.deactivate(t);return e?i:await Y(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.estimateGas.setAllowedSwapper(t,e);return a?n:await Y(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.estimateGas.dispense(t,this.amountToUnits(null,e,18),a);return i?r:await Y(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.estimateGas.ownerWithdraw(t);return e?i:await Y(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 r(await e.balance(t,a)).greaterThanOrEqualTo(n.maxBalance)||new r(String(i)).greaterThan(n.maxTokens)||!new r(n.balance).greaterThanOrEqualTo(i)&&!0!==n.isMinter)}}const it="0x0000000000000000000000000000000000000000",nt=1e6,rt="115792089237316195423570985008687907853269984665640564039457584007913129639934",st="Returned error: Method eth_feeHistory not supported.";class ot extends et{getDefaultAbi(){return o.abi}async generateExchangeId(t,e){return await this.contract.generateExchangeId(t,e)}async buyDatatokens(t,e,a,i=it,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,+o.dtDecimals),d=await this.amountToUnits(o.baseToken,a,+o.btDecimals),u=await this.contract.estimateGas.buyDT(t,l,d,i,c);return r?u:await Y(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=it,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,+o.dtDecimals),d=await this.amountToUnits(o.baseToken,a,+o.btDecimals),u=await this.contract.estimateGas.sellDT(t,l,d,i,c);return r?u:await Y(u,this.getSignerAccordingSdk(),null==(s=this.config)?void 0:s.gasFeeMultiplier,this.contract.sellDT,t,l,d,i,c)}async getNumberOfExchanges(){return await this.contract.getNumberOfExchanges()}async setRate(t,e,a){var i;const n=await this.contract.estimateGas.setRate(t,await this.amountToUnits(null,e,18));return a?n:await Y(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.estimateGas.setAllowedSwapper(t,e);return a?n:await Y(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.estimateGas.toggleExchangeState(t);return e?n:await Y(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.estimateGas.toggleExchangeState(t);return e?n:await Y(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,+a.dtDecimals)}async getBasetokenSupply(t){const e=await this.contract.getBTSupply(t),a=await this.getExchange(t);return await this.unitsToAmount(a.baseToken,e,+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,+i.dtDecimals),await this.amountToUnits(null,a,18));return{baseTokenAmount:await this.unitsToAmount(i.baseToken,n.baseTokenAmount,+i.btDecimals),marketFeeAmount:await this.unitsToAmount(i.baseToken,n.publishMarketFeeAmount,+i.btDecimals),oceanFeeAmount:await this.unitsToAmount(i.baseToken,n.oceanFeeAmount,+i.btDecimals),consumeMarketFeeAmount:await this.unitsToAmount(i.baseToken,n.consumeMarketFeeAmount,+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,+i.dtDecimals),await this.amountToUnits(null,a,18));return await this.unitsToAmount(i.baseToken,n[0],+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,+e.dtDecimals),btBalance:await this.unitsToAmount(e.baseToken,e.btBalance,+e.btDecimals),dtSupply:await this.unitsToAmount(e.datatoken,e.dtSupply,+e.dtDecimals),btSupply:await this.unitsToAmount(e.baseToken,e.btSupply,+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,+a.btDecimals),oceanFeeAvailable:await this.unitsToAmount(a.baseToken,e.oceanFeeAvailable,+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.estimateGas.toggleMintState(t,!0);return e?n:await Y(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.estimateGas.toggleMintState(t,!1);return e?n:await Y(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,+n.btDecimals),s=await this.contract.estimateGas.collectBT(t,r);return a?s:await Y(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,+n.dtDecimals),s=await this.contract.estimateGas.collectDT(t,r);return a?s:await Y(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.estimateGas.collectMarketFee(t);return e?i:await Y(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.estimateGas.collectOceanFee(t);return e?i:await Y(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(await this.getExchange(t)).exchangeOwner}async updateMarketFee(t,e,a){var i;const n=await this.contract.estimateGas.updateMarketFee(t,await this.amountToUnits(null,e,18));return a?n:await Y(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.estimateGas.updateMarketFeeCollector(t,e);return a?n:await Y(n,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.updateMarketFeeCollector,t,e)}}class ct extends et{getDefaultAbi(){return c.abi}async buyDatatokenBatch(t,e){var a;const i=await this.contract.estimateGas.buyDTBatch(t);return e?i:await Y(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.estimateGas.addApprovedToken(e);return a?n:await Y(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.estimateGas.removeApprovedToken(e);return a?n:await Y(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.estimateGas.addFixedRateContract(e);return a?n:await Y(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.estimateGas.removeFixedRateContract(e);return a?n:await Y(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.estimateGas.addDispenserContract(e);return a?n:await Y(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.estimateGas.removeDispenserContract(e);return a?n:await Y(n,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.removeDispenserContract,e)}async getOPCFee(t){return await this.contract.getOPCFee(t)}async getCurrentOPCFee(){return await this.contract.swapOceanFee()}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.estimateGas.updateOPCFee(e,a,i,n);return r?o:await Y(o,this.getSignerAccordingSdk(),null==(s=this.config)?void 0:s.gasFeeMultiplier,this.contract.updateOPCFee,e,a,i,n)}}var lt={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 dt(t){const e=t||lt,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 ut extends et{getDefaultAbi(){return h.abi}async createNFT(t,e){if(t.templateIndex||(t.templateIndex=1),!t.name||!t.symbol){const{name:e,symbol:a}=dt();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.estimateGas.deployERC721Contract(t.name,t.symbol,t.templateIndex,it,it,t.tokenURI,t.transferable,t.owner);if(e)return a;try{var i;const e=await Y(a,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.deployERC721Contract,t.name,t.symbol,t.templateIndex,it,it,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 Q(await e.wait(),"NFTCreated").args[0]}catch(t){console.error(`Creation of NFT failed: ${t}`)}}async getCurrentNFTCount(){return await this.contract.getCurrentNFTCount()}async getCurrentTokenCount(){return await this.contract.getCurrentTokenCount()}async getOwner(){return await this.contract.owner()}async getCurrentNFTTemplateCount(){return await this.contract.getCurrentNFTTemplateCount()}async getCurrentTokenTemplateCount(){return await this.contract.getCurrentTemplateCount()}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===it)throw new Error("Template cannot be ZERO address");const n=await this.contract.estimateGas.add721TokenTemplate(e);return a?n:await Y(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.estimateGas.disable721TokenTemplate(e);return a?n:await Y(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.estimateGas.reactivate721TokenTemplate(e);return a?n:await Y(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===it)throw new Error("Template cannot be address ZERO");const n=await this.contract.estimateGas.addTokenTemplate(e);return a?n:await Y(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.estimateGas.disableTokenTemplate(e);return a?n:await Y(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.estimateGas.reactivateTokenTemplate(e);return a?n:await Y(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.estimateGas.startMultipleTokenOrder(t);return e?i:await Y(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.estimateGas.createNftWithErc20(t,n);return a?r:await Y(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.estimateGas.createNftWithErc20WithFixedRate(t,r,s);return i?o:await Y(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.estimateGas.createNftWithErc20WithDispenser(t,r,a);return i?s:await Y(s,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,this.contract.createNftWithErc20WithDispenser,t,r,a)}async getErcCreationParams(t){let e,i;t.name&&t.symbol||({name:e,symbol:i}=dt());let n=18;if(t.feeToken!==it)try{n=await Z(this.signer,t.feeToken)}catch(t){L.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||i],addresses:r,uints:[await this.amountToUnits(null,t.cap,18),await this.amountToUnits(null,t.feeAmount,n)],bytess:t.filesObject?[a.utils.toUtf8Bytes(JSON.stringify(t.filesObject))]:[]}}async getFreCreationParams(t){t.allowedConsumer||(t.allowedConsumer=it);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,18),await this.amountToUnits(null,t.marketFee,18),e]}}}async function ht(t,e,i,n){const r="number"==typeof i,s=new ut(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,g.abi,t);if(r){const a=await o.connect(t).getId();if(n.isActive&&a.toString()===i.toString())return e}else if(n.isActive&&n.templateAddress===i.toString())return e}return-1}class gt extends tt{getDefaultAbi(){return u.abi}async createDatatoken(i,n,r,s,o,c,l,d,u,h,g,w,p,m,f,y){var v;if(!0!==(await this.getNftPermissions(i,n)).deployERC20)throw new Error("Caller is not DatatokenDeployer");g||(g=1),u&&h||({name:u,symbol:h}=dt());const k=this.getContract(i),{chainId:T}=await k.provider.getNetwork(),A=function(a){try{const i=function(){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}}();if(i){const t=Object.keys(i);for(const e of t)if(i[e].chainId===a)return i[e]}}catch(t){console.error(t)}return null}(T);w&&(g=await ht(this.signer,A.ERC721Factory,4,T));const S=await k.estimateGas.createERC20(g,[u,h],[r,s,o,c],[await this.amountToUnits(null,d,18),await this.amountToUnits(null,l,18)],[]);if(y)return S;const b=[r,s,o,c];p&&(b.push(p.toLowerCase()),b.push(m?m.toLowerCase():it),b.push(f||it));const F=await Y(S,this.getSignerAccordingSdk(),null==(v=this.config)?void 0:v.gasFeeMultiplier,k.createERC20,g,[u,h],b,[await this.amountToUnits(null,d,18),await this.amountToUnits(null,l,18)],w?[a.utils.toUtf8Bytes(w)]:[]),E=Q(await F.wait(),"TokenCreated");return null==E?void 0:E.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.estimateGas.addManager(a);return i?s:await Y(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.estimateGas.removeManager(a);return i?s:await Y(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.estimateGas.addToCreateERC20List(a);return i?s:await Y(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.estimateGas.removeFromCreateERC20List(a);return i?s:await Y(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.estimateGas.addToMetadataList(a);return i?s:await Y(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.estimateGas.removeFromMetadataList(a);return i?s:await Y(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.estimateGas.addTo725StoreList(a);return i?s:await Y(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.estimateGas.removeFrom725StoreList(a);return i?s:await Y(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.estimateGas.cleanPermissions();return a?r:await Y(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.estimateGas.transferFrom(e,a,o);return n?c:await Y(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.estimateGas.safeTransferFrom(e,a,o);return n?c:await Y(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.estimateGas.setMetaData(a,i,n,r,s,o,c);return l?h:await Y(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=N({},a,{metadataProofs:a.metadataProofs||[]}),o=await r.estimateGas.setMetaDataAndTokenURI(s);return i?o:await Y(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.estimateGas.setMetaDataState(a);return i?s:await Y(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.estimateGas.setTokenURI("1",e);return a?r:await Y(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,i,n,r){var s;if(!0!==(await this.getNftPermissions(t,e)).store)throw new Error("User is not ERC20 store updater");const o=this.getContract(t),c=a.utils.keccak256(i),l=a.utils.hexlify(a.utils.toUtf8Bytes(n)),d=await o.estimateGas.setNewData(c,l);return r?d:await Y(d,this.getSignerAccordingSdk(),null==(s=this.config)?void 0:s.gasFeeMultiplier,o.setNewData,c,l)}async getData(t,e){const i=this.getContract(t),n=a.utils.keccak256(e),r=await i.getData(n);return r?a.utils.toUtf8String(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 wt extends tt{getDefaultAbi(){return l.abi}constructor(t,e,a,i,n){super(t,e,a,i),this.abiEnterprise=void 0,this.nft=void 0,this.abiEnterprise=n||d.abi,this.nft=new gt(this.signer,e)}async approve(t,e,a,i){var n;const r=this.getContract(t),s=await r.estimateGas.approve(e,K(null,null,a,18));return i?s:await Y(s,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,r.approve,e,K(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=it);const s=!1===a.withMint?0:1,o=await r.estimateGas.createFixedRate(a.fixedRateAddress,[a.baseTokenAddress,a.owner,a.marketFeeCollector,a.allowedConsumer],[a.baseTokenDecimals,a.datatokenDecimals,a.fixedRate,a.marketFee,s]);return i?o:await Y(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=it),i.withMint=!1!==i.withMint;const o=await s.estimateGas.createDispenser(a,i.maxTokens,i.maxBalance,i.withMint,i.allowedSwapper);return n?o:await Y(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 s=this.getContract(t);if(!0!==(await this.getPermissions(t,e)).minter)throw new Error("Caller is not Minter");const o=await this.getCap(t);if(new r(o).gte(a)){var c;const t=await s.estimateGas.mint(i||e,K(null,null,a,18));return n?t:await Y(t,this.getSignerAccordingSdk(),null==(c=this.config)?void 0:c.gasFeeMultiplier,s.mint,i||e,K(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.estimateGas.addMinter(a);return i?s:await Y(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.estimateGas.removeMinter(a);return i?s:await Y(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.estimateGas.addPaymentManager(a);return i?s:await Y(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.estimateGas.removePaymentManager(a);return i?s:await Y(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.estimateGas.setPaymentCollector(a);return i?d:await Y(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 K(null,null,a,18),i)}async transferWei(t,e,a,i){var n;const r=this.getContract(t),s=await r.estimateGas.transfer(e,a);return i?s:await Y(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:it,consumeMarketFeeToken:it,consumeMarketFeeAmount:"0"});const c=await o.estimateGas.startOrder(e,a,i,n);return r?c:await Y(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.estimateGas.reuseOrder(e,a);return i?s:await Y(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.estimateGas.buyFromFreAndOrder(e,s);return i?o:await Y(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.estimateGas.buyFromDispenserAndOrder(e,a);return i?s:await Y(s,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,r.buyFromDispenserAndOrder,e,a)}async setData(t,e,i,n){var r;if(!await this.isDatatokenDeployer(t,e))throw new Error("User is not Datatoken Deployer");const s=this.getContract(t),o=a.utils.hexlify(a.utils.toUtf8Bytes(i)),c=await s.estimateGas.setData(o);return n?c:await Y(c,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,s.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.estimateGas.cleanPermissions();return a?r:await Y(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);return await e.decimals()}async getId(t){const e=this.getContract(t);return await e.getId()}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.estimateGas.setPublishingMarketFee(e,a,i);return r?c:await Y(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 K(this.signer,t.baseTokenAddress,t.maxBaseTokenAmount,t.baseTokenDecimals),swapMarketFee:await K(this.signer,t.baseTokenAddress,t.swapMarketFee,t.baseTokenDecimals),marketFeeAddress:t.marketFeeAddress}}}class pt extends wt{getDefaultAbi(){return w.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.estimateGas.setAllowListContract(e);return i?s:await Y(s,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,r.functions.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.estimateGas.setDenyListContract(e);return i?s:await Y(s,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,r.functions.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.estimateGas.setFilesObject(this.fileObject);return a?r:await Y(r,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,n.functions.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 mt extends et{getDefaultAbi(){return p.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(){return await this.contract.getId()}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.estimateGas.mint(t,e);return a?n:await Y(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.estimateGas.batchMint(t,e);return a?n:await Y(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.estimateGas.burn(t);return e?i:await Y(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.estimateGas.transferOwnership(t);return e?i:await Y(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.estimateGas.renounceOwnership();return t?a:await Y(a,this.getSignerAccordingSdk(),null==(e=this.config)?void 0:e.gasFeeMultiplier,this.contract.renounceOwnership)}}class ft extends et{getDefaultAbi(){return m.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}=dt();t=a,e=i}const o=await this.contract.estimateGas.deployAccessListContract(t,e,i,n,r,a);if(s)return o;try{var c;const s=await Y(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 Q(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===it)throw new Error("Template address cannot be ZERO address");const n=await this.contract.estimateGas.changeTemplateAddress(e);return a?n:await Y(n,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.functions.changeTemplateAddress,e)}}class yt extends et{getDefaultAbi(){return f.abi}async lockTokens(t,e,a){var i;const n=await this.amountToUnits(await this.getToken(),t),r=await this.contract.estimateGas.create_lock(n,e);return a?r:await Y(r.add(2e4),this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.create_lock,n,e)}async depositFor(t,e,a){var i;const n=await this.amountToUnits(await this.getToken(),e),r=await this.contract.estimateGas.deposit_for(t,n);return a?r:await Y(r.add(2e4),this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.deposit_for,t,n)}async increaseAmount(t,e){var a;const i=await this.amountToUnits(await this.getToken(),t),n=await this.contract.estimateGas.increase_amount(i);return e?n:await Y(n.add(2e4),this.getSignerAccordingSdk(),null==(a=this.config)?void 0:a.gasFeeMultiplier,this.contract.increase_amount,i)}async increaseUnlockTime(t,e){var a;const i=await this.contract.estimateGas.increase_unlock_time(t);return e?i:await Y(i.add(2e4),this.getSignerAccordingSdk(),null==(a=this.config)?void 0:a.gasFeeMultiplier,this.contract.increase_unlock_time,t)}async withdraw(t){var e;const a=await this.contract.estimateGas.withdraw();return t?a:await Y(a.add(2e4),this.getSignerAccordingSdk(),null==(e=this.config)?void 0:e.gasFeeMultiplier,this.contract.withdraw)}async getVotingPower(t){return await this.contract.balanceOf(t)}async getLockedAmount(t){const e=await this.contract.locked(t);return await this.unitsToAmount(await this.getToken(),e.amount.toString())}async lockEnd(t){const e=await this.contract.locked__end(t);return parseInt(e.toString())}async totalSupply(){return await this.unitsToAmount(await this.getToken(),await this.contract.totalSupply())}async getToken(){return await this.contract.token()}}class vt extends et{getDefaultAbi(){return y.abi}async claim(t){var e;const a=await this.contract.estimateGas.claim();return t?a:await Y(a.add(2e4),this.getSignerAccordingSdk(),null==(e=this.config)?void 0:e.gasFeeMultiplier,this.contract.claim)}async claimMany(t,e){var a;const i=await this.contract.estimateGas.claim_many(t);return e?i:await Y(i.add(2e4),this.getSignerAccordingSdk(),null==(a=this.config)?void 0:a.gasFeeMultiplier,this.contract.claim_many,t)}}class kt extends et{getDefaultAbi(){return v.abi}async estimateClaim(t){const e=await this.contract.estimateClaim(t),a=new yt(await this.contract.voting_escrow(),this.signer);return await this.unitsToAmount(await a.getToken(),e)}}class Tt extends et{getDefaultAbi(){return k.abi}async setAllocation(t,e,a,i){var n;const r=await this.contract.estimateGas.setAllocation(t,e,a);return i?r:await Y(r.add(2e4),this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,this.contract.setAllocation,t,e,a)}async setBatchAllocation(t,e,a,i){var n;const r=await this.contract.estimateGas.setBatchAllocation(t,e,a);return i?r:await Y(r.add(2e4),this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,this.contract.setBatchAllocation,t,e,a)}async getTotalAllocation(t){return await this.contract.getTotalAllocation(t)}async getVeAllocation(t,e,a){return await this.contract.getveAllocation(t,e,a)}}class At extends et{getDefaultAbi(){return T.abi}async getAvailableRewards(t,e){const a=await this.contract.claimable(t,e);return await this.unitsToAmount(e,a)}async claimRewards(t,e,a){var i;const n=await this.contract.estimateGas.claimFor(t,e);return a?n:await Y(n,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.claimFor,t,e)}async allocateRewards(t,e,a,i){var n;for(let t=0;t<e.length;t++)e[t]=await this.amountToUnits(a,e[t]);const r=await this.contract.estimateGas.allocate(t,e,a);return i?r:await Y(r,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,this.contract.allocate,t,e,a)}}class St extends et{getDefaultAbi(){return A.abi}async getMultipleAvailableRewards(t,e){const a=await this.contract.claimables(t,e),i=[];for(let t=0;t<a.length;t++)i.push(await this.unitsToAmount(e[t],a[t]));return i}async claimMultipleRewards(t,e,a){var i;const n=await this.contract.estimateGas.claimMultiple(t,e);return a?n:await Y(n,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.claimMultiple,t,e)}}class bt extends et{getDefaultAbi(){return S.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 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,n,r,s,o){const{provider:c}=this.contract;if(await c.getBalance(a.utils.getAddress(e))===i.from(0))return{isValid:!1,message:"Native token balance is 0. Please add funds"};const l=new wt(this.signer),d=await l.allowance(t,await this.signer.getAddress(),this.contract.address);i.from(await this.amountToUnits(t,d,18)).lt(i.from(r))&&await l.approve(a.utils.getAddress(t),a.utils.getAddress(this.contract.address),r);const u=await l.balance(t,await this.signer.getAddress());if(a.utils.parseEther(u)===i.from(0))return{isValid:!1,message:"Payment token balance is 0. Please add funds"};const h=await this.getAuthorizations(t,await this.signer.getAddress(),e),g=await this.getUserFunds(await this.signer.getAddress(),t);return i.from(g[0]).eq(i.from(0))&&(n&&a.utils.parseEther(u).lte(a.utils.parseEther(n))&&a.utils.parseEther(n)>i.from(r)?await this.deposit(t,n):a.utils.parseEther(u).lte(i.from(r))?await this.deposit(t,await this.unitsToAmount(t,r)):await this.deposit(t,u)),0===h.length&&await this.authorize(a.utils.getAddress(t),a.utils.getAddress(e),(Number(r)/2).toString(),s,o),{isValid:!0,message:""}}async deposit(t,e,a){var i;const n=K(null,null,e,18),r=await this.contract.estimateGas.deposit(t,n);return a?r:await Y(r,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.deposit,t,n)}async withdraw(t,e,a){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 n=t[a],c=i.from(e[a]),l=await this.getUserFunds(o,n),d=i.from(l[0]);c.gt(0)&&c.lte(d)?(r.push(n),s.push(e[a])):console.log(`Insufficient funds for token ${n}`)}const c=s.map(t=>K(null,null,t,18)),l=await this.contract.estimateGas.withdraw(t,c);return a?l:await Y(l,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,this.contract.withdraw,r,c)}async authorize(t,e,a,i,n,r){var s;if(0!==(await this.getAuthorizations(t,await this.signer.getAddress(),e)).length)return console.log(`Payee ${e} already authorized`),null;const o=K(null,null,a,18),c=K(null,null,i,18),l=K(null,null,n,18),d=await this.contract.estimateGas.authorize(t,e,o,c,l);return r?d:await Y(d,this.getSignerAccordingSdk(),null==(s=this.config)?void 0:s.gasFeeMultiplier,this.contract.authorize,t,e,o,c,l)}async cancelExpiredLocks(t,e,a,i,n){var r;const s=await this.contract.estimateGas.cancelExpiredLocks(t,e,a,i);return n?s:await Y(s,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,this.contract.cancelExpiredLocks,t,e,a,i)}}class Ft extends et{getDefaultAbi(){return b.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){const a=this.amountToUnits(t,e.toString()),i=await this.contract.calculateFee(t,a);return this.unitsToAmount(t,i)}}async function Et(t){return new Promise(e=>{setTimeout(e,t)})}function Ct(t){return null!=t}async function Dt(t,e){const i=a.utils.arrayify(e);let n=await t._legacySignMessage(i);n=n.substr(2);const r="0x"+n.slice(0,64),s="0x"+n.slice(64,128);let o="0x"+n.slice(128,130);return"0x00"===o&&(o="0x1b"),"0x01"===o&&(o="0x1c"),{v:o,r,s}}async function xt(t,e){const i=a.utils.solidityKeccak256(["bytes"],[a.utils.hexlify(a.utils.toUtf8Bytes(e))]),n=a.utils.arrayify(i),r=await t.getChainId();try{return await t.signMessage(n)}catch(e){if(L.error("Sign message error: ",e),8996===r)return console.log("Signing message with _legacySignMessage"),await t._legacySignMessage(n)}}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 F(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 L.error(t),new Error("HTTP request failed")}}async waitForIndexer(t,e,a,i=3e4,n=100,r){let s=0;n>500&&(L.warn("Max Limit exceeded, defaulting to 500 retries."),n=500);do{try{const i=this.aquariusURL+"/api/aquarius/assets/ddo/"+t,n=await F(i,{method:"GET",headers:{"Content-Type":"application/json",Authorization:r},signal:a});if(n.ok){const t=await n.json(),a=E.getDDOClass(t),{indexedMetadata:i}=a.getAssetFields();if(!e)return t;if(i.event&&i.event.txid===e)return t}}catch(t){}await Et(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 F(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=a+l,u={ddo:t,publisherAddress:a,nonce:l,signature:await xt(e,d)},h=await F(r,{method:"POST",body:JSON.stringify(u),headers:{"Content-Type":"application/octet-stream",Authorization:n},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){L.error("Metadata validation failed",t.message)}}async getAssetMetadata(t,e,a){const i=this.aquariusURL+"/api/aquarius/assets/metadata/"+t;try{const t=await F(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 L.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 F(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 L.error("Error querying metadata: ",t),new Error("Error querying metadata: "+t)}}}class Ot{async getConsumerAddress(t){return"string"==typeof t?function(t){try{return C.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 L.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 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 F(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 L.error(t),new Error(t.message)}}async signProviderRequest(t,e){const i=a.utils.solidityKeccak256(["bytes"],[a.utils.hexlify(a.utils.toUtf8Bytes(e))]),n=a.utils.arrayify(i);try{return await t.signMessage(n)}catch(e){if(8996===await t.getChainId())return await t._legacySignMessage(n)}}async encrypt(t,e,a,i){const n=await this.getEndpoints(a),r=await this.getServiceEndpoints(a,n),s=(this.getEndpointURL(r,"encrypt")?this.getEndpointURL(r,"encrypt").urlPath:null)+`?chainId=${e}`;if(!s)return null;try{const e=await F(s,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/octet-stream"},signal:i});return await e.text()}catch(t){throw L.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 F(d,{method:"POST",body:JSON.stringify(c),headers:{"Content-Type":"application/json"},signal:n})}catch(t){throw L.error("File info call failed: "),L.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 L.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=N({},t,{checksum:a}),c=[],l=this.getEndpointURL(s,"fileinfo")?this.getEndpointURL(s,"fileinfo").urlPath:null;if(!l)return null;let d;try{d=await F(l,{method:"POST",body:JSON.stringify(o),headers:{"Content-Type":"application/json"},signal:i})}catch(t){throw L.error("File info call failed: "),L.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 L.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 F(s,{method:"GET",headers:{"Content-Type":"application/json"},signal:e})}catch(t){throw L.error("Fetch compute env failed: "),L.error(t),new Error(t)}if(null!=(i=o)&&i.ok)return o.json();const c=await o.json();throw L.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 F(g,{method:"GET",headers:{"Content-Type":"application/json"},signal:r})}catch(t){throw L.error("Provider initialized failed: "),L.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 L.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 F(g,{method:"POST",body:JSON.stringify(h),headers:{"Content-Type":"application/json"},signal:c})}catch(t){throw L.error("Initialize compute failed: "),L.error(t),new Error("ComputeJob cannot be initialized")}if(null!=(l=w)&&l.ok)return await w.json();const p=await w.json();throw L.error("Initialize compute failed: ",w.status,w.statusText,p),L.error("Payload was:",JSON.stringify(h)),new Error(JSON.stringify(p))}async initializeCompute(t,e,a,i,n,r,s,o,c,l,d){var u,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,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:n,consumerAddress:m,signature:await this.getSignature(s,y)};let k;l&&(v.policyServer=l);try{if(console.log("Initialize compute url:",p),k=await F(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 L.error("Initialize compute failed: "),L.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 L.error("Initialize compute failed: ",k.status,k.statusText,T),L.error("Payload was:",JSON.stringify(v)),new Error(JSON.stringify(T))}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,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,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 this.signProviderRequest(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 F(u,{method:"POST",body:JSON.stringify(m),headers:{"Content-Type":"application/json"},signal:r})}catch(t){throw L.error("Compute start failed:"),L.error(t),L.error("Payload was:",m),new Error("HTTP request failed calling Provider")}return null!=(c=f)&&c.ok?await f.json():(L.error("Compute start failed: ",f.status,f.statusText,await f.json()),L.error("Payload was:",m),null)}async computeStart(t,e,a,i,n,r,s,o,c,l,d,u,h){var g,w;console.log("called new compute start method..."),console.log("datasets: ",i),console.log("algorithm: ",n);const p=await this.getEndpoints(t),m=await this.getServiceEndpoints(t,p),f=this.getEndpointURL(m,"computeStart")?this.getEndpointURL(m,"computeStart").urlPath:null;if(!f)return L.error("Compute start failed: Cannot get proper computeStart route (perhaps not implemented on provider?)"),null;const y=await this.getConsumerAddress(e),v=(await this.getNonce(t,y,h,p,m)+1).toString();let k=y;k+=null==(g=i[0])?void 0:g.documentId,k+=v;const T=await this.getSignature(e,k),A=Object();let S;A.consumerAddress=y,A.signature=T,A.nonce=v,A.environment=a,A.maxJobDuration=r,A.resources=o,A.dataset=i[0],A.datasets=i,A.algorithm=n,A.chainId=c,A.payment={chainId:c,token:s,maxJobDuration:r},o&&(A.payment.resources=o),l&&(A.metadata=l),d&&(A.output=d),u&&(A.policyServer=u);try{S=await F(f,{method:"POST",body:JSON.stringify(A),headers:{"Content-Type":"application/json",Authorization:this.getAuthorization(e)},signal:h})}catch(t){throw L.error("Compute start failed:"),L.error(t),L.error("Payload was:",A),new Error("HTTP request failed calling Provider")}return null!=(w=S)&&w.ok?await S.json():(L.error("Compute start failed: ",S.status,S.statusText,await S.json()),L.error("Payload was:",A),null)}async freeComputeStart(t,e,a,i,n,r,s,o,c,l){var d;console.log("called new free compute start method..."),console.log("datasets: ",i),console.log("algorithm: ",n);const u=await this.getEndpoints(t),h=await this.getServiceEndpoints(t,u),g=this.getEndpointURL(h,"freeCompute")?this.getEndpointURL(h,"freeCompute").urlPath:null;if(!g)return L.error("Compute start failed: Cannot get proper computeStart route (perhaps not implemented on provider?)"),null;const w=await this.getConsumerAddress(e),p=(await this.getNonce(t,w,l,u,h)+1).toString(),m=p;console.log("signatureMessage: ",m);const f=await this.getSignature(e,m),y=Object();let v;y.consumerAddress=w,y.signature=f,y.nonce=p,y.environment=a,y.resources=r,y.dataset=i[0],y.datasets=i,y.algorithm=n,s&&(y.metadata=s),y.output=o,c&&(y.policyServer=c);try{v=await F(g,{method:"POST",body:JSON.stringify(y),headers:{"Content-Type":"application/json",Authorization:this.getAuthorization(e)},signal:l})}catch(t){throw L.error("Compute start failed:"),L.error(t),L.error("Payload was:",y),new Error("HTTP request failed calling Provider")}return null!=(d=v)&&d.ok?await v.json():(L.error("Compute start failed: ",v.status,v.statusText,await v.json()),L.error("Payload was:",y),null)}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 L.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 F(l+g,{method:"GET",headers:{"Content-Type":"application/json",Authorization:this.getAuthorization(e)},signal:i}),console.log("Raw response:",h)}catch(t){throw L.error("computeStreamableLogs failed:"),L.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):(L.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=await this.getEndpoints(e),o=await this.getServiceEndpoints(e,s),c=this.getEndpointURL(o,"computeStop")?this.getEndpointURL(o,"computeStop").urlPath:null,l=await this.getConsumerAddress(a),d=(await this.getNonce(e,l,n,s,o)+1).toString(),u=l+(t||""),h=await this.getSignature(a,u),g=new URLSearchParams;g.set("consumerAddress",l),g.set("signature",h),g.set("nonce",d),g.set("jobId",t),i&&g.set("agreementId",i);const w=g.toString();if(!w)return null;let p;try{p=await F(c+"?"+w,{method:"PUT",headers:{"Content-Type":"application/json",Authorization:this.getAuthorization(a)},signal:n})}catch(t){throw L.error("Compute stop failed:"),L.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 L.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 F(d+h,{method:"GET",headers:{"Content-Type":"application/json",Authorization:r},signal:n})}catch(t){throw L.error("Get compute status failed"),L.error(t),new Error(t)}if(null!=(s=u)&&s.ok)return await u.json();if(L.error("Get compute status failed:",u.status,u.statusText),null!=(o=u)&&o.ok)return await u.json();const g=await u.json();throw L.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();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()}`,n||(h+=`&nonce=${l}`,h+=`&signature=${u}`),h}async computeDelete(t,e,a,i,n){var r;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,n,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 F(c,{method:"DELETE",body:JSON.stringify(g),headers:{"Content-Type":"application/json",Authorization:this.getAuthorization(e)},signal:n})}catch(t){throw L.error("Delete compute job failed:"),L.error(t),L.error("Payload was:",g),new Error("HTTP request failed calling Provider")}if(null!=(r=w)&&r.ok)return await w.json();const p=await w.json();throw L.error("Delete compute job failed:",w.status,w.statusText,p),L.error("Payload was:",g),new Error(JSON.stringify(p))}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=i+o,l=await this.signProviderRequest(t,c);try{const t=await F(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 L.error("Generate auth token failed:"),L.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 this.signProviderRequest(t,l);try{const t=await F(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 L.error("Generate auth token failed:"),L.error(t),new Error("HTTP request failed calling Provider")}}async isValidProvider(t,e){try{const a=await F(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 L.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 F(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 L.error("PolicyServerPassthrough failed: "),L.error(t),new Error(`PolicyServerPassthrough failed: ${t.message}.`)}if(null!=(i=o)&&i.ok)return await o.json();const c=await o.json();throw L.error("PolicyServerPassthrough failed: ",o.status,o.statusText,c),L.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 F(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 L.error("initializePSVerification failed: "),L.error(t),new Error(`initializePSVerification failed: ${t.message}.`)}if(null!=(i=o)&&i.ok)return await o.json();const c=await o.json();throw L.error("initializePSVerification failed: ",o.status,o.statusText,c),L.error("Payload was:",JSON.stringify(e)),new Error(JSON.stringify(c))}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 L.debug("Not input string:"),L.debug(t),new Error(`[${a}] Expected string, input type: ${typeof t}`);const i=t.match(e);return i?{valid:!0,output:i[1]}:(L.warn(`[${a}] Input transformation failed.`),{valid:!1,output:t})}async getData(t,e){return F(t,{method:"GET",headers:{"Content-type":"application/json",Authorization:e}})}}const Rt=new Ot;function Pt(t,e){return t=a.utils.getAddress(t),`did:op:${D(t+e.toString(10)).toString()}`}function Ut(t){return D(t).toString()}function Nt(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 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,n,s,o,c=!1,l,d){const u=new a.Contract(n,B,t);if(!c){const e=await _t(t,n,i,s);if(new r(e).greaterThanOrEqualTo(new r(o)))return new r(e).toNumber()}const h=await K(t,n,o,l),g=await u.estimateGas.approve(s,h);return d?new r(g.toString()):await Y(g,t,null==e?void 0:e.gasFeeMultiplier,u.approve,s,h)}async function jt(t,e,i,n,r,s,o=!1,c){const l=new a.Contract(n,B,t);if(!o){const e=await Bt(t,n,i,r);if(a.BigNumber.from(e).gt(a.BigNumber.from(s)))return a.BigNumber.from(e)}let d=null;const u=await l.estimateGas.approve(r,s);if(c)return u;try{d=await Y(u,t,null==e?void 0:e.gasFeeMultiplier,l.approve,r,s)}catch(t){L.error(`ERROR: Failed to approve spender to spend tokens : ${t.message}`)}return d}async function Gt(t,e,i,n,r,s){const o=new a.Contract(i,B,t),c=await K(t,i,r),l=await o.estimateGas.transfer(n,c);return s?l:await Y(l,t,null==e?void 0:e.gasFeeMultiplier,o.transfer,n,c)}async function _t(t,e,i,n,r){const s=new a.Contract(e,B,t),o=await s.allowance(i,n);return await X(t,e,o,r)}async function $t(t,e,i,n){const r=new a.Contract(e,B,t),s=await r.balanceOf(i);return await X(t,e,s,n)}async function Bt(t,e,i,n){const r=new a.Contract(e,B,t);return await r.allowance(i,n)}async function zt(t,e){const i=new a.Contract(e,B,t);return await i.decimals()}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 L.error("[getErrorMessage] error: ",e),t}}async function Wt(t,e,a,i,n,s,o,c,l="0",d=0,u=0,h=0){const g=E.getDDOClass(t),{datatokens:w}=g.getAssetFields(),{chainId:p,services:m}=g.getDDOFields();if(o||(o={consumeMarketFeeAddress:"0x0000000000000000000000000000000000000000",consumeMarketFeeAmount:"0",consumeMarketFeeToken:"0x0000000000000000000000000000000000000000"}),p!==(await e.provider.getNetwork()).chainId)throw new Error("Chain ID from DDO is different than the configured network.");if(!w[d].address)throw new Error(`The datatoken with index: ${d} does not exist for the asset with did: ${t.id}`);if(!m[u].id)throw new Error(`There is no service with index: ${u} defined for the asset with did: ${t.id}`);const f=await i.getId(w[d].address),y=await i.getFixedRates(w[d].address),v=await i.getDispensers(w[d].address),k=await i.getPublishingMarketFee(w[d].address),T=y.length>0?"fixed":v.length>0?"free":"NOT_ALLOWED",A=c||(await Rt.initialize(t.id,m[u].id,0,await e.getAddress(),n||a.oceanNodeUri)).providerFee;if(A&&A.providerFeeAddress!==it&&A.providerFeeAmount&&parseInt(A.providerFeeAmount)>0)try{await jt(e,a,await e.getAddress(),A.providerFeeToken,m[0].datatokenAddress,A.providerFeeAmount)}catch(t){throw new Error(`Failed to approve provider fee token ${A.providerFeeToken}`)}const S={consumer:s||await e.getAddress(),serviceIndex:u,_providerFee:A,_consumeMarketFee:o};switch(T){case"free":if(1===f){const t=new at(a.dispenserAddress,e),n=await t.dispense(w[d].address,"1",await e.getAddress());if(!n)throw new Error("Failed to dispense !");return await n.wait(),await i.startOrder(w[d].address,S.consumer,S.serviceIndex,S._providerFee,S._consumeMarketFee)}if(2===f||4===f)return await i.buyFromDispenserAndOrder(m[u].datatokenAddress,S,a.dispenserAddress);break;case"fixed":{const n=new ot(a.fixedRateExchangeAddress,e);if(!y[h].id)throw new Error(`There is no fixed rate exchange with index: ${u} for the asset with did: ${t.id}`);const s=await n.getFeesInfo(y[h].id),c=await n.getExchange(y[h].id),{baseTokenAmount:g}=await n.calcBaseInGivenDatatokensOut(s.exchangeId,"1",o.consumeMarketFeeAmount),p=new r(+g||0).add(new r(o.consumeMarketFeeAmount||0)).add(new r(+k.publishMarketFeeAmount||0)).toString(),m={exchangeContract:a.fixedRateExchangeAddress,exchangeId:s.exchangeId,maxBaseTokenAmount:p,baseTokenAddress:c.baseToken,baseTokenDecimals:parseInt(c.btDecimals)||18,swapMarketFee:l,marketFeeAddress:k.publishMarketFeeAddress};if(1===f){const t=await Lt(e,a,await e.getAddress(),c.baseToken,a.fixedRateExchangeAddress,p,!1);if(!("number"!=typeof t?await t.wait():t))throw new Error(`Failed to approve ${c.baseToken} !`);const r=await n.buyDatatokens(c.exchangeId,"1",p,k.publishMarketFeeAddress,l);if(!await r.wait())throw new Error("Failed to buy datatoken from fixed rate!");return await i.startOrder(w[d].address,S.consumer,S.serviceIndex,S._providerFee,S._consumeMarketFee)}if(2===f||4===f){const t=await Lt(e,a,await e.getAddress(),c.baseToken,w[d].address,p,!1);if(!t)throw new Error(`Failed to approve ${c.baseToken} !`);if(!("number"!=typeof t?await t.wait():t))throw new Error("Failed to confirm/mine approval transaction!");return await i.buyFromFreAndOrder(w[d].address,S,m)}break}default:throw new Error("Pricing schema not supported !")}}const Vt=8996;function Ht(t){const e=(new $).getConfig(t);return e&&"oasis"===e.sdk}async function Zt(t,e,i,n,r,s,o=!0,c,l,d,u,h,g){var p,m,f;const y=E.getDDOClass(s),{indexedMetadata:v}=y.getAssetFields(),k=(null==(p=y.getDDOData())||null==(p=p.stats)||null==(p=p.price)?void 0:p.value)||(null==v||null==(m=v.stats[0])||null==(m=m.prices[0])?void 0:m.price);let{chainId:T,nftAddress:A}=y.getDDOFields();const{services:S}=y.getDDOFields();if("string"!=typeof r&&"number"!=typeof r)throw new Error('Invalid template! Must be a "number" or a "string"');const b=(await i.provider.getNetwork()).chainId;if(T&&T!==b)throw new Error("Chain ID from DDO is different than the configured network.");const F=(new $).getConfig(parseInt(String(b)));let C=await ht(i,F.nftFactoryAddress,r,b);if(C<1){if(8996!==b)throw new Error(`Invalid template index: ${C}`);C=1}const D=new gt(i,b),R=new ut(F.nftFactoryAddress,i,b),P=await i.getAddress(),U={name:t,symbol:e,templateIndex:1,tokenURI:"aaa",transferable:!0,owner:P},N={templateIndex:C,cap:"100000",feeAmount:"0",paymentCollector:P,feeToken:l||F.oceanTokenAddress,minter:P,mpFeeAddress:it};let I;null!=n&&n.files[0].type&&[O.ARWEAVE,O.IPFS,O.URL].includes(null==n||null==(f=n.files[0])||null==(f=f.type)?void 0:f.toLowerCase())||(console.log('Missing or invalid files object type, defaulting to "url"'),n.type=O.URL),"oasis"===F.sdk&&(N.filesObject=n,N.accessListFactory=u||F.accessListFactory,N.allowAccessList=h,N.denyAccessList=g);try{if(k)if("0"===k.toString()){const t={dispenserAddress:F.dispenserAddress,maxTokens:"1",maxBalance:"100000000",withMint:!0,allowedSwapper:it};I=await R.createNftWithDatatokenWithDispenser(U,N,t)}else{const t={fixedRateAddress:F.fixedRateExchangeAddress,baseTokenAddress:F.oceanTokenAddress,owner:P,marketFeeCollector:P,baseTokenDecimals:18,datatokenDecimals:18,fixedRate:k.toString(),marketFee:"0",allowedConsumer:P,withMint:!0};I=await R.createNftWithDatatokenWithFixedRate(U,N,t)}else I=await R.createNftWithDatatoken(U,N)}catch(t){return console.log("ERROR creating NFT bundle",t),null}const L=await I.wait(),j=Q(L,"NFTCreated"),G=Q(L,"TokenCreated"),_=j.args.newTokenAddress,B=G.args.newTokenAddress;if(n.datatokenAddress=B,n.nftAddress=_,"oasis"===F.sdk){const t=new a.Contract(B,w.abi,i);try{const e=await t.setFilesObject(a.utils.toUtf8Bytes(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}}S[0].files="oasis"===F.sdk?"":await Rt.encrypt(n,b,c),S[0].datatokenAddress=B,S[0].serviceEndpoint=c,A=_;const z=y.makeDid(A,T.toString());let q,J,W;if(s=y.updateFields({id:z,nftAddress:A}),o)q=await Rt.encrypt(s,b,c),J=(await d.validate(s,i,c)).hash,W=2;else{const t=JSON.stringify(s),e=Buffer.from(t);q=x(e),J="0x"+M("sha256").update(q).digest("hex"),W=0}return await D.setMetadata(A,await i.getAddress(),0,c,"",a.utils.hexlify(W),q,J),s.id}async function Xt(t,e,i){const n=new a.Contract(t,m.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 Q(await t.wait(),"NewAccessList").args[0]}catch(t){console.log("ERROR createAccessListFactory(): ",t)}return null}export{mt as AccessListContract,ft as AccesslistFactory,Mt as Aquarius,U as Config,$ as ConfigHelper,Vt as DEVELOPMENT_CHAIN_ID,wt as Datatoken,pt as Datatoken4,At as DfRewards,St as DfStrategyV1,at as Dispenser,R as EncryptMethod,Ft as EnterpriseFeeCollectorContract,bt as EscrowContract,st as FEE_HISTORY_NOT_SUPPORTED,O as FileObjectType,ot as FixedRateExchange,nt as GASLIMIT_DEFAULT,_ as KNOWN_CONFIDENTIAL_EVMS,P as LogLevel,I as Logger,L as LoggerInstance,rt as MAX_UINT_256,gt as Nft,ut as NftFactory,Ot as Provider,Rt as ProviderInstance,ct as Router,tt as SmartContract,et as SmartContractWithAddress,Tt as VeAllocate,vt as VeFeeDistributor,kt as VeFeeEstimate,yt as VeOcean,it as ZERO_ADDRESS,_t as allowance,Bt as allowanceWei,K as amountToUnits,Lt as approve,jt as approveWei,$t as balance,G as configHelperNetworks,Xt as createAccessListFactory,Zt as createAsset,zt as decimals,It as downloadFile,Nt as downloadFileBrowser,Pt as generateDid,dt as generateDtName,Jt as getErrorMessage,Q as getEventFromTx,H as getFairGasPrice,Ut as getHash,Z as getTokenDecimals,Ct as isDefined,B as minAbi,Wt as orderAsset,Y as sendTx,V as setContractDefaults,Dt as signHash,xt as signRequest,Et as sleep,Gt as transfer,X as unitsToAmount,Ht as useOasisSDK};
|
|
1
|
+
import t from"@oceanprotocol/contracts/addresses/address.json";import e from"fs";import{ethers as a,BigNumber as i}from"ethers";import*as n from"@oasisprotocol/sapphire-paratime";import r from"decimal.js";import s from"@oceanprotocol/contracts/artifacts/contracts/pools/dispenser/Dispenser.sol/Dispenser.json";import o from"@oceanprotocol/contracts/artifacts/contracts/pools/fixedRate/FixedRateExchange.sol/FixedRateExchange.json";import c from"@oceanprotocol/contracts/artifacts/contracts/pools/FactoryRouter.sol/FactoryRouter.json";import l from"@oceanprotocol/contracts/artifacts/contracts/templates/ERC20Template.sol/ERC20Template.json";import d from"@oceanprotocol/contracts/artifacts/contracts/templates/ERC20TemplateEnterprise.sol/ERC20TemplateEnterprise.json";import u from"@oceanprotocol/contracts/artifacts/contracts/templates/ERC721Template.sol/ERC721Template.json";import h from"@oceanprotocol/contracts/artifacts/contracts/ERC721Factory.sol/ERC721Factory.json";import g from"@oceanprotocol/contracts/artifacts/contracts/interfaces/IERC20Template.sol/IERC20Template.json";import w from"@oceanprotocol/contracts/artifacts/contracts/templates/ERC20Template4.sol/ERC20Template4.json";import p from"@oceanprotocol/contracts/artifacts/contracts/accesslists/AccessList.sol/AccessList.json";import m from"@oceanprotocol/contracts/artifacts/contracts/accesslists/AccessListFactory.sol/AccessListFactory.json";import f from"@oceanprotocol/contracts/artifacts/contracts/ve/veOCEAN.vy/veOCEAN.json";import y from"@oceanprotocol/contracts/artifacts/contracts/ve/veFeeDistributor.vy/veFeeDistributor.json";import v from"@oceanprotocol/contracts/artifacts/contracts/ve/veFeeEstimate.vy/veFeeEstimate.json";import k from"@oceanprotocol/contracts/artifacts/contracts/ve/veAllocate.sol/veAllocate.json";import T from"@oceanprotocol/contracts/artifacts/contracts/df/DFRewards.sol/DFRewards.json";import A from"@oceanprotocol/contracts/artifacts/contracts/df/DFStrategyV1.sol/DFStrategyV1.json";import S from"@oceanprotocol/contracts/artifacts/contracts/escrow/Escrow.sol/Escrow.json";import b from"@oceanprotocol/contracts/artifacts/contracts/communityFee/EnterpriseFeeCollector.sol/EnterpriseFeeCollector.json";import F from"cross-fetch";import{DDOManager as E}from"@oceanprotocol/ddo-js";import C from"jsonwebtoken";import D from"crypto-js/sha256.js";import{hexlify as x}from"ethers/lib/utils.js";import{createHash as M}from"crypto";var O,R,P;!function(t){t.URL="url",t.IPFS="ipfs",t.ARWEAVE="arweave"}(O||(O={})),function(t){t.AES="AES",t.ECIES="ECIES"}(R||(R={}));class U{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.veAllocate=void 0,this.veOCEAN=void 0,this.veDelegation=void 0,this.veFeeDistributor=void 0,this.veDelegationProxy=void 0,this.DFRewards=void 0,this.DFStrategyV1=void 0,this.veFeeEstimate=void 0,this.sdk=void 0,this.accessListFactory=void 0}}function N(){return N=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},N.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"}(P||(P={}));class I{constructor(t){this.logLevel=void 0,this.logLevel=t,this.logLevel=t||P.Error}setLevel(t){this.logLevel=t}bypass(...t){this.dispatch("log",-Infinity,...t)}debug(...t){this.dispatch("debug",P.Verbose,...t)}log(...t){this.dispatch("log",P.Log,...t)}warn(...t){this.dispatch("warn",P.Warn,...t)}error(...t){this.dispatch("error",P.Error,...t)}dispatch(t,e,...a){this.logLevel>=e&&console[t](...a)}}const L=new I,j={chainId:null,network:"unknown",nodeUri:"http://127.0.0.1:8545",oceanNodeUri:"https://1.c2d.nodes.oceanprotocol.com:8000/",explorerUri:null,oceanTokenAddress:null,oceanTokenSymbol:"OCEAN",fixedRateExchangeAddress:null,dispenserAddress:null,startBlock:0,transactionBlockTimeout:50,transactionConfirmationBlocks:1,transactionPollingTimeout:750,gasFeeMultiplier:1},G=[N({},j),N({},j,{chainId:8996,network:"development",oceanNodeUri:"https://1.c2d.nodes.oceanprotocol.com:8000/",sdk:"evm"}),N({},j,{chainId:11155111,network:"sepolia",nodeUri:"https://sepolia.infura.io/v3",explorerUri:"https://sepolia.etherscan.io",gasFeeMultiplier:1.1,sdk:"evm"}),N({},j,{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"}),N({},j,{chainId:137,network:"polygon",nodeUri:"https://polygon-mainnet.infura.io/v3",explorerUri:"https://polygonscan.com",oceanTokenSymbol:"mOCEAN",gasFeeMultiplier:1.6,sdk:"evm"}),N({},j,{chainId:2021e3,network:"gaiaxtestnet",nodeUri:"https://rpc.gaiaxtestnet.oceanprotocol.com",explorerUri:"https://blockscout.gaiaxtestnet.oceanprotocol.com",sdk:"evm"}),N({},j,{chainId:80001,network:"mumbai",nodeUri:"https://polygon-mumbai.infura.io/v3",explorerUri:"https://mumbai.polygonscan.com",gasFeeMultiplier:1.1,sdk:"evm"}),N({},j,{chainId:56,network:"bsc",nodeUri:"https://bsc-dataseed.binance.org",explorerUri:"https://bscscan.com/",gasFeeMultiplier:1.05,sdk:"evm"}),N({},j,{chainId:246,network:"energyweb",nodeUri:"https://rpc.energyweb.org",explorerUri:"https://explorer.energyweb.org",gasFeeMultiplier:1.05,sdk:"evm"}),N({},j,{chainId:1285,network:"moonriver",nodeUri:"https://moonriver.api.onfinality.io/public",explorerUri:"https://moonriver.moonscan.io/",gasFeeMultiplier:1.05,sdk:"evm"}),N({},j,{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"}),N({},j,{chainId:10,network:"optimism",nodeUri:"https://mainnet.optimism.io",explorerUri:"https://optimistic.etherscan.io/",gasFeeMultiplier:1.1,sdk:"evm"}),N({},j,{chainId:11155420,network:"optimism_sepolia",nodeUri:"https://sepolia.optimism.io",explorerUri:"https://sepolia-optimism.etherscan.io/",gasFeeMultiplier:1.1,sdk:"evm"}),N({},j,{chainId:23294,network:"oasis_sapphire",nodeUri:"https://sapphire.oasis.io",explorerUri:"https://explorer.oasis.io/mainnet/sapphire/",gasFeeMultiplier:1,sdk:"oasis"}),N({},j,{chainId:23295,network:"oasis_sapphire_testnet",nodeUri:"https://testnet.sapphire.oasis.dev",explorerUri:"https://explorer.oasis.io/testnet/sapphire/",gasFeeMultiplier:1,sdk:"oasis"}),N({},j,{chainId:32456,network:"pontus-x-devnet",nodeUri:"https://rpc.dev.pontus-x.eu",explorerUri:"https://explorer.dev.pontus-x.eu/testnet/pontusx",sdk:"evm"})],_=[23294,23295];class ${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,veAllocate:u,veOCEAN:h,veDelegation:g,veFeeDistributor:w,veDelegationProxy:p,DFRewards:m,DFStrategyV1:f,veFeeEstimate:y,Router:v,AccessListFactory:k,EnterpriseFeeCollector:T}=a[e];i=N({nftFactoryAddress:s,opfCommunityFeeCollector:o,fixedRateExchangeAddress:t,dispenserAddress:r,oceanTokenAddress:c,routerFactoryAddress:v,chainId:l,startBlock:d,veAllocate:u,veOCEAN:h,veDelegation:g,veFeeDistributor:w,veDelegationProxy:p,DFRewards:m,DFStrategyV1:f,veFeeEstimate:y,accessListFactory:k,EnterpriseFeeCollector:T},n())}else if(t[e]){const{FixedPrice:a,Dispenser:r,OPFCommunityFeeCollector:s,ERC721Factory:o,Ocean:c,chainId:l,startBlock:d,veAllocate:u,veOCEAN:h,veDelegation:g,veFeeDistributor:w,veDelegationProxy:p,DFRewards:m,DFStrategyV1:f,veFeeEstimate:y,Router:v,AccessListFactory:k,EnterpriseFeeCollector:T}=t[e];i=N({nftFactoryAddress:o,opfCommunityFeeCollector:s,fixedRateExchangeAddress:a,dispenserAddress:r,oceanTokenAddress:c,routerFactoryAddress:v,chainId:l,startBlock:d,veAllocate:u,veOCEAN:h,veDelegation:g,veFeeDistributor:w,veDelegationProxy:p,DFRewards:m,DFStrategyV1:f,veFeeEstimate:y,accessListFactory:k,EnterpriseFeeCollector:T},n())}return i}getConfig(t,a){const i="string"==typeof t?"network":"chainId";let n,r=G.find(e=>e[i]===t);if(!r)return L.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&&_.includes(r.chainId)&&(s=this.getAddressesFromEnv(r.network.replace("sapph","saph"),n)),"sdk"in r&&null!==r.sdk||(r.sdk=_.includes(r.chainId)?"oasis":"evm"),s&&"accessListFactory"in s&&(r.accessListFactory=s.accessListFactory),r=N({},r,s),N({},r,{nodeUri:a?`${r.nodeUri}/${a}`:r.nodeUri})}}const B=[{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"}],z=3e10,q=4e9,J=1e10,W=11155111;function V(t,e){return t}async function H(t,e){const i=await(await t.provider.getFeeData()).gasPrice,n=a.BigNumber.from(i.toString());return e?n.mul(e).toBigInt().toString(10):n.toString()}async function Z(t,e){return new a.Contract(e,B,t).decimals()}async function X(t,e,i,n){let r=n||await Z(t,e);return"0"===r&&(r=18),a.utils.formatUnits(i,r).toString()}async function K(t,e,i,n){let r=n||await Z(t,e);return"0"===r&&(r=18),a.utils.parseUnits(i,r).toString()}function Q(t,e){var a;return null==t||null==(a=t.events)?void 0:a.filter(t=>t.event===e)[0]}async function Y(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(s.maxPriorityFeePerGas.toNumber()*a).toString(),e=Math.round(s.maxFeePerGas.toNumber()*a).toString()),o={maxPriorityFeePerGas:(80001===r||137===r)&&Number(t)<z?z:r===W&&Number(t)<q?q:_.includes(r)&&Number(t)<J?J:Number(t),maxFeePerGas:(80001===r||137===r)&&Number(e)<z?z:r===W&&Number(e)<q?q:_.includes(r)&&Number(e)<J?J:Number(e)}}else o={gasPrice:s.gasPrice};o.gasLimit=t.add(2e4);try{const t=await i(...n,o);return await t.wait(),t}catch(t){return L.error("Send tx error: ",t),null}}class tt{constructor(t,e,a,i){this.signer=void 0,this.config=void 0,this.abi=void 0,this.signer=t,this.config=a||(new $).getConfig(e),this.abi=i||this.getDefaultAbi()}getSignerAccordingSdk(){return this.config&&"sdk"in this.config&&"oasis"===this.config.sdk?n.wrap(this.signer):this.signer}async amountToUnits(t,e,a){return K(this.signer,t,e,a)}async unitsToAmount(t,e,a){return X(this.signer,t,e,a)}async getFairGasPrice(){var t;return H(this.signer,null==(t=this.config)?void 0:t.gasFeeMultiplier)}getContract(t,e){return V(new a.Contract(t,new a.utils.Interface(JSON.stringify(e||this.abi)),this.signer))}}class et extends tt{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 at extends et{getDefaultAbi(){return s.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.estimateGas.create(t,this.amountToUnits(null,a,18),this.amountToUnits(null,i,18),e,n);return r?o:await Y(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.estimateGas.activate(t,this.amountToUnits(null,e,18),this.amountToUnits(null,a,18));return i?r:await Y(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.estimateGas.deactivate(t);return e?i:await Y(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.estimateGas.setAllowedSwapper(t,e);return a?n:await Y(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.estimateGas.dispense(t,this.amountToUnits(null,e,18),a);return i?r:await Y(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.estimateGas.ownerWithdraw(t);return e?i:await Y(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 r(await e.balance(t,a)).greaterThanOrEqualTo(n.maxBalance)||new r(String(i)).greaterThan(n.maxTokens)||!new r(n.balance).greaterThanOrEqualTo(i)&&!0!==n.isMinter)}}const it="0x0000000000000000000000000000000000000000",nt=1e6,rt="115792089237316195423570985008687907853269984665640564039457584007913129639934",st="Returned error: Method eth_feeHistory not supported.";class ot extends et{getDefaultAbi(){return o.abi}async generateExchangeId(t,e){return await this.contract.generateExchangeId(t,e)}async buyDatatokens(t,e,a,i=it,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,+o.dtDecimals),d=await this.amountToUnits(o.baseToken,a,+o.btDecimals),u=await this.contract.estimateGas.buyDT(t,l,d,i,c);return r?u:await Y(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=it,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,+o.dtDecimals),d=await this.amountToUnits(o.baseToken,a,+o.btDecimals),u=await this.contract.estimateGas.sellDT(t,l,d,i,c);return r?u:await Y(u,this.getSignerAccordingSdk(),null==(s=this.config)?void 0:s.gasFeeMultiplier,this.contract.sellDT,t,l,d,i,c)}async getNumberOfExchanges(){return await this.contract.getNumberOfExchanges()}async setRate(t,e,a){var i;const n=await this.contract.estimateGas.setRate(t,await this.amountToUnits(null,e,18));return a?n:await Y(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.estimateGas.setAllowedSwapper(t,e);return a?n:await Y(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.estimateGas.toggleExchangeState(t);return e?n:await Y(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.estimateGas.toggleExchangeState(t);return e?n:await Y(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,+a.dtDecimals)}async getBasetokenSupply(t){const e=await this.contract.getBTSupply(t),a=await this.getExchange(t);return await this.unitsToAmount(a.baseToken,e,+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,+i.dtDecimals),await this.amountToUnits(null,a,18));return{baseTokenAmount:await this.unitsToAmount(i.baseToken,n.baseTokenAmount,+i.btDecimals),marketFeeAmount:await this.unitsToAmount(i.baseToken,n.publishMarketFeeAmount,+i.btDecimals),oceanFeeAmount:await this.unitsToAmount(i.baseToken,n.oceanFeeAmount,+i.btDecimals),consumeMarketFeeAmount:await this.unitsToAmount(i.baseToken,n.consumeMarketFeeAmount,+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,+i.dtDecimals),await this.amountToUnits(null,a,18));return await this.unitsToAmount(i.baseToken,n[0],+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,+e.dtDecimals),btBalance:await this.unitsToAmount(e.baseToken,e.btBalance,+e.btDecimals),dtSupply:await this.unitsToAmount(e.datatoken,e.dtSupply,+e.dtDecimals),btSupply:await this.unitsToAmount(e.baseToken,e.btSupply,+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,+a.btDecimals),oceanFeeAvailable:await this.unitsToAmount(a.baseToken,e.oceanFeeAvailable,+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.estimateGas.toggleMintState(t,!0);return e?n:await Y(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.estimateGas.toggleMintState(t,!1);return e?n:await Y(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,+n.btDecimals),s=await this.contract.estimateGas.collectBT(t,r);return a?s:await Y(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,+n.dtDecimals),s=await this.contract.estimateGas.collectDT(t,r);return a?s:await Y(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.estimateGas.collectMarketFee(t);return e?i:await Y(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.estimateGas.collectOceanFee(t);return e?i:await Y(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(await this.getExchange(t)).exchangeOwner}async updateMarketFee(t,e,a){var i;const n=await this.contract.estimateGas.updateMarketFee(t,await this.amountToUnits(null,e,18));return a?n:await Y(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.estimateGas.updateMarketFeeCollector(t,e);return a?n:await Y(n,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.updateMarketFeeCollector,t,e)}}class ct extends et{getDefaultAbi(){return c.abi}async buyDatatokenBatch(t,e){var a;const i=await this.contract.estimateGas.buyDTBatch(t);return e?i:await Y(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.estimateGas.addApprovedToken(e);return a?n:await Y(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.estimateGas.removeApprovedToken(e);return a?n:await Y(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.estimateGas.addFixedRateContract(e);return a?n:await Y(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.estimateGas.removeFixedRateContract(e);return a?n:await Y(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.estimateGas.addDispenserContract(e);return a?n:await Y(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.estimateGas.removeDispenserContract(e);return a?n:await Y(n,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.removeDispenserContract,e)}async getOPCFee(t){return await this.contract.getOPCFee(t)}async getCurrentOPCFee(){return await this.contract.swapOceanFee()}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.estimateGas.updateOPCFee(e,a,i,n);return r?o:await Y(o,this.getSignerAccordingSdk(),null==(s=this.config)?void 0:s.gasFeeMultiplier,this.contract.updateOPCFee,e,a,i,n)}}var lt={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 dt(t){const e=t||lt,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 ut extends et{getDefaultAbi(){return h.abi}async createNFT(t,e){if(t.templateIndex||(t.templateIndex=1),!t.name||!t.symbol){const{name:e,symbol:a}=dt();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.estimateGas.deployERC721Contract(t.name,t.symbol,t.templateIndex,it,it,t.tokenURI,t.transferable,t.owner);if(e)return a;try{var i;const e=await Y(a,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.deployERC721Contract,t.name,t.symbol,t.templateIndex,it,it,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 Q(await e.wait(),"NFTCreated").args[0]}catch(t){console.error(`Creation of NFT failed: ${t}`)}}async getCurrentNFTCount(){return await this.contract.getCurrentNFTCount()}async getCurrentTokenCount(){return await this.contract.getCurrentTokenCount()}async getOwner(){return await this.contract.owner()}async getCurrentNFTTemplateCount(){return await this.contract.getCurrentNFTTemplateCount()}async getCurrentTokenTemplateCount(){return await this.contract.getCurrentTemplateCount()}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===it)throw new Error("Template cannot be ZERO address");const n=await this.contract.estimateGas.add721TokenTemplate(e);return a?n:await Y(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.estimateGas.disable721TokenTemplate(e);return a?n:await Y(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.estimateGas.reactivate721TokenTemplate(e);return a?n:await Y(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===it)throw new Error("Template cannot be address ZERO");const n=await this.contract.estimateGas.addTokenTemplate(e);return a?n:await Y(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.estimateGas.disableTokenTemplate(e);return a?n:await Y(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.estimateGas.reactivateTokenTemplate(e);return a?n:await Y(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.estimateGas.startMultipleTokenOrder(t);return e?i:await Y(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.estimateGas.createNftWithErc20(t,n);return a?r:await Y(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.estimateGas.createNftWithErc20WithFixedRate(t,r,s);return i?o:await Y(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.estimateGas.createNftWithErc20WithDispenser(t,r,a);return i?s:await Y(s,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,this.contract.createNftWithErc20WithDispenser,t,r,a)}async getErcCreationParams(t){let e,i;t.name&&t.symbol||({name:e,symbol:i}=dt());let n=18;if(t.feeToken!==it)try{n=await Z(this.signer,t.feeToken)}catch(t){L.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||i],addresses:r,uints:[await this.amountToUnits(null,t.cap,18),await this.amountToUnits(null,t.feeAmount,n)],bytess:t.filesObject?[a.utils.toUtf8Bytes(JSON.stringify(t.filesObject))]:[]}}async getFreCreationParams(t){t.allowedConsumer||(t.allowedConsumer=it);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,18),await this.amountToUnits(null,t.marketFee,18),e]}}}function ht(){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 gt(t){try{const e=ht();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 wt(t,e,i,n){const r="number"==typeof i,s=new ut(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,g.abi,t);if(r){const a=await o.connect(t).getId();if(n.isActive&&a.toString()===i.toString())return e}else if(n.isActive&&n.templateAddress===i.toString())return e}return-1}class pt extends tt{getDefaultAbi(){return u.abi}async createDatatoken(t,e,i,n,r,s,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}=dt());const y=this.getContract(t),{chainId:v}=await y.provider.getNetwork(),k=gt(v);h&&(u=await wt(this.signer,k.ERC721Factory,4,v));const T=await y.estimateGas.createERC20(u,[l,d],[i,n,r,s],[await this.amountToUnits(null,c,18),await this.amountToUnits(null,o,18)],[]);if(m)return T;const A=[i,n,r,s];g&&(A.push(g.toLowerCase()),A.push(w?w.toLowerCase():it),A.push(p||it));const S=await Y(T,this.getSignerAccordingSdk(),null==(f=this.config)?void 0:f.gasFeeMultiplier,y.createERC20,u,[l,d],A,[await this.amountToUnits(null,c,18),await this.amountToUnits(null,o,18)],h?[a.utils.toUtf8Bytes(h)]:[]),b=Q(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.estimateGas.addManager(a);return i?s:await Y(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.estimateGas.removeManager(a);return i?s:await Y(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.estimateGas.addToCreateERC20List(a);return i?s:await Y(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.estimateGas.removeFromCreateERC20List(a);return i?s:await Y(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.estimateGas.addToMetadataList(a);return i?s:await Y(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.estimateGas.removeFromMetadataList(a);return i?s:await Y(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.estimateGas.addTo725StoreList(a);return i?s:await Y(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.estimateGas.removeFrom725StoreList(a);return i?s:await Y(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.estimateGas.cleanPermissions();return a?r:await Y(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.estimateGas.transferFrom(e,a,o);return n?c:await Y(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.estimateGas.safeTransferFrom(e,a,o);return n?c:await Y(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.estimateGas.setMetaData(a,i,n,r,s,o,c);return l?h:await Y(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=N({},a,{metadataProofs:a.metadataProofs||[]}),o=await r.estimateGas.setMetaDataAndTokenURI(s);return i?o:await Y(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.estimateGas.setMetaDataState(a);return i?s:await Y(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.estimateGas.setTokenURI("1",e);return a?r:await Y(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,i,n,r){var s;if(!0!==(await this.getNftPermissions(t,e)).store)throw new Error("User is not ERC20 store updater");const o=this.getContract(t),c=a.utils.keccak256(i),l=a.utils.hexlify(a.utils.toUtf8Bytes(n)),d=await o.estimateGas.setNewData(c,l);return r?d:await Y(d,this.getSignerAccordingSdk(),null==(s=this.config)?void 0:s.gasFeeMultiplier,o.setNewData,c,l)}async getData(t,e){const i=this.getContract(t),n=a.utils.keccak256(e),r=await i.getData(n);return r?a.utils.toUtf8String(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 mt extends tt{getDefaultAbi(){return l.abi}constructor(t,e,a,i,n){super(t,e,a,i),this.abiEnterprise=void 0,this.nft=void 0,this.abiEnterprise=n||d.abi,this.nft=new pt(this.signer,e)}async approve(t,e,a,i){var n;const r=this.getContract(t),s=await r.estimateGas.approve(e,K(null,null,a,18));return i?s:await Y(s,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,r.approve,e,K(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=it);const s=!1===a.withMint?0:1,o=await r.estimateGas.createFixedRate(a.fixedRateAddress,[a.baseTokenAddress,a.owner,a.marketFeeCollector,a.allowedConsumer],[a.baseTokenDecimals,a.datatokenDecimals,a.fixedRate,a.marketFee,s]);return i?o:await Y(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=it),i.withMint=!1!==i.withMint;const o=await s.estimateGas.createDispenser(a,i.maxTokens,i.maxBalance,i.withMint,i.allowedSwapper);return n?o:await Y(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 s=this.getContract(t);if(!0!==(await this.getPermissions(t,e)).minter)throw new Error("Caller is not Minter");const o=await this.getCap(t);if(new r(o).gte(a)){var c;const t=await s.estimateGas.mint(i||e,K(null,null,a,18));return n?t:await Y(t,this.getSignerAccordingSdk(),null==(c=this.config)?void 0:c.gasFeeMultiplier,s.mint,i||e,K(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.estimateGas.addMinter(a);return i?s:await Y(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.estimateGas.removeMinter(a);return i?s:await Y(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.estimateGas.addPaymentManager(a);return i?s:await Y(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.estimateGas.removePaymentManager(a);return i?s:await Y(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.estimateGas.setPaymentCollector(a);return i?d:await Y(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 K(null,null,a,18),i)}async transferWei(t,e,a,i){var n;const r=this.getContract(t),s=await r.estimateGas.transfer(e,a);return i?s:await Y(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:it,consumeMarketFeeToken:it,consumeMarketFeeAmount:"0"});const c=await o.estimateGas.startOrder(e,a,i,n);return r?c:await Y(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.estimateGas.reuseOrder(e,a);return i?s:await Y(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.estimateGas.buyFromFreAndOrder(e,s);return i?o:await Y(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.estimateGas.buyFromDispenserAndOrder(e,a);return i?s:await Y(s,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,r.buyFromDispenserAndOrder,e,a)}async setData(t,e,i,n){var r;if(!await this.isDatatokenDeployer(t,e))throw new Error("User is not Datatoken Deployer");const s=this.getContract(t),o=a.utils.hexlify(a.utils.toUtf8Bytes(i)),c=await s.estimateGas.setData(o);return n?c:await Y(c,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,s.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.estimateGas.cleanPermissions();return a?r:await Y(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);return await e.decimals()}async getId(t){const e=this.getContract(t);return await e.getId()}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.estimateGas.setPublishingMarketFee(e,a,i);return r?c:await Y(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 K(this.signer,t.baseTokenAddress,t.maxBaseTokenAmount,t.baseTokenDecimals),swapMarketFee:await K(this.signer,t.baseTokenAddress,t.swapMarketFee,t.baseTokenDecimals),marketFeeAddress:t.marketFeeAddress}}}class ft extends mt{getDefaultAbi(){return w.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.estimateGas.setAllowListContract(e);return i?s:await Y(s,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,r.functions.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.estimateGas.setDenyListContract(e);return i?s:await Y(s,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,r.functions.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.estimateGas.setFilesObject(this.fileObject);return a?r:await Y(r,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,n.functions.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 yt extends et{getDefaultAbi(){return p.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(){return await this.contract.getId()}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.estimateGas.mint(t,e);return a?n:await Y(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.estimateGas.batchMint(t,e);return a?n:await Y(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.estimateGas.burn(t);return e?i:await Y(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.estimateGas.transferOwnership(t);return e?i:await Y(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.estimateGas.renounceOwnership();return t?a:await Y(a,this.getSignerAccordingSdk(),null==(e=this.config)?void 0:e.gasFeeMultiplier,this.contract.renounceOwnership)}}class vt extends et{getDefaultAbi(){return m.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}=dt();t=a,e=i}const o=await this.contract.estimateGas.deployAccessListContract(t,e,i,n,r,a);if(s)return o;try{var c;const s=await Y(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 Q(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===it)throw new Error("Template address cannot be ZERO address");const n=await this.contract.estimateGas.changeTemplateAddress(e);return a?n:await Y(n,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.functions.changeTemplateAddress,e)}}class kt extends et{getDefaultAbi(){return f.abi}async lockTokens(t,e,a){var i;const n=await this.amountToUnits(await this.getToken(),t),r=await this.contract.estimateGas.create_lock(n,e);return a?r:await Y(r.add(2e4),this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.create_lock,n,e)}async depositFor(t,e,a){var i;const n=await this.amountToUnits(await this.getToken(),e),r=await this.contract.estimateGas.deposit_for(t,n);return a?r:await Y(r.add(2e4),this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.deposit_for,t,n)}async increaseAmount(t,e){var a;const i=await this.amountToUnits(await this.getToken(),t),n=await this.contract.estimateGas.increase_amount(i);return e?n:await Y(n.add(2e4),this.getSignerAccordingSdk(),null==(a=this.config)?void 0:a.gasFeeMultiplier,this.contract.increase_amount,i)}async increaseUnlockTime(t,e){var a;const i=await this.contract.estimateGas.increase_unlock_time(t);return e?i:await Y(i.add(2e4),this.getSignerAccordingSdk(),null==(a=this.config)?void 0:a.gasFeeMultiplier,this.contract.increase_unlock_time,t)}async withdraw(t){var e;const a=await this.contract.estimateGas.withdraw();return t?a:await Y(a.add(2e4),this.getSignerAccordingSdk(),null==(e=this.config)?void 0:e.gasFeeMultiplier,this.contract.withdraw)}async getVotingPower(t){return await this.contract.balanceOf(t)}async getLockedAmount(t){const e=await this.contract.locked(t);return await this.unitsToAmount(await this.getToken(),e.amount.toString())}async lockEnd(t){const e=await this.contract.locked__end(t);return parseInt(e.toString())}async totalSupply(){return await this.unitsToAmount(await this.getToken(),await this.contract.totalSupply())}async getToken(){return await this.contract.token()}}class Tt extends et{getDefaultAbi(){return y.abi}async claim(t){var e;const a=await this.contract.estimateGas.claim();return t?a:await Y(a.add(2e4),this.getSignerAccordingSdk(),null==(e=this.config)?void 0:e.gasFeeMultiplier,this.contract.claim)}async claimMany(t,e){var a;const i=await this.contract.estimateGas.claim_many(t);return e?i:await Y(i.add(2e4),this.getSignerAccordingSdk(),null==(a=this.config)?void 0:a.gasFeeMultiplier,this.contract.claim_many,t)}}class At extends et{getDefaultAbi(){return v.abi}async estimateClaim(t){const e=await this.contract.estimateClaim(t),a=new kt(await this.contract.voting_escrow(),this.signer);return await this.unitsToAmount(await a.getToken(),e)}}class St extends et{getDefaultAbi(){return k.abi}async setAllocation(t,e,a,i){var n;const r=await this.contract.estimateGas.setAllocation(t,e,a);return i?r:await Y(r.add(2e4),this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,this.contract.setAllocation,t,e,a)}async setBatchAllocation(t,e,a,i){var n;const r=await this.contract.estimateGas.setBatchAllocation(t,e,a);return i?r:await Y(r.add(2e4),this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,this.contract.setBatchAllocation,t,e,a)}async getTotalAllocation(t){return await this.contract.getTotalAllocation(t)}async getVeAllocation(t,e,a){return await this.contract.getveAllocation(t,e,a)}}class bt extends et{getDefaultAbi(){return T.abi}async getAvailableRewards(t,e){const a=await this.contract.claimable(t,e);return await this.unitsToAmount(e,a)}async claimRewards(t,e,a){var i;const n=await this.contract.estimateGas.claimFor(t,e);return a?n:await Y(n,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.claimFor,t,e)}async allocateRewards(t,e,a,i){var n;for(let t=0;t<e.length;t++)e[t]=await this.amountToUnits(a,e[t]);const r=await this.contract.estimateGas.allocate(t,e,a);return i?r:await Y(r,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,this.contract.allocate,t,e,a)}}class Ft extends et{getDefaultAbi(){return A.abi}async getMultipleAvailableRewards(t,e){const a=await this.contract.claimables(t,e),i=[];for(let t=0;t<a.length;t++)i.push(await this.unitsToAmount(e[t],a[t]));return i}async claimMultipleRewards(t,e,a){var i;const n=await this.contract.estimateGas.claimMultiple(t,e);return a?n:await Y(n,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.claimMultiple,t,e)}}class Et extends et{getDefaultAbi(){return S.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 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,n,r,s,o){const{provider:c}=this.contract;if(await c.getBalance(a.utils.getAddress(e))===i.from(0))return{isValid:!1,message:"Native token balance is 0. Please add funds"};const l=new mt(this.signer),d=await l.allowance(t,await this.signer.getAddress(),this.contract.address);i.from(await this.amountToUnits(t,d,18)).lt(i.from(r))&&await l.approve(a.utils.getAddress(t),a.utils.getAddress(this.contract.address),r);const u=await l.balance(t,await this.signer.getAddress());if(a.utils.parseEther(u)===i.from(0))return{isValid:!1,message:"Payment token balance is 0. Please add funds"};const h=await this.getAuthorizations(t,await this.signer.getAddress(),e),g=await this.getUserFunds(await this.signer.getAddress(),t);return i.from(g[0]).eq(i.from(0))&&(n&&a.utils.parseEther(u).lte(a.utils.parseEther(n))&&a.utils.parseEther(n)>i.from(r)?await this.deposit(t,n):a.utils.parseEther(u).lte(i.from(r))?await this.deposit(t,await this.unitsToAmount(t,r)):await this.deposit(t,u)),0===h.length&&await this.authorize(a.utils.getAddress(t),a.utils.getAddress(e),(Number(r)/2).toString(),s,o),{isValid:!0,message:""}}async deposit(t,e,a){var i;const n=K(null,null,e,18),r=await this.contract.estimateGas.deposit(t,n);return a?r:await Y(r,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.deposit,t,n)}async withdraw(t,e,a){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 n=t[a],c=i.from(e[a]),l=await this.getUserFunds(o,n),d=i.from(l[0]);c.gt(0)&&c.lte(d)?(r.push(n),s.push(e[a])):console.log(`Insufficient funds for token ${n}`)}const c=s.map(t=>K(null,null,t,18)),l=await this.contract.estimateGas.withdraw(t,c);return a?l:await Y(l,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,this.contract.withdraw,r,c)}async authorize(t,e,a,i,n,r){var s;if(0!==(await this.getAuthorizations(t,await this.signer.getAddress(),e)).length)return console.log(`Payee ${e} already authorized`),null;const o=K(null,null,a,18),c=K(null,null,i,18),l=K(null,null,n,18),d=await this.contract.estimateGas.authorize(t,e,o,c,l);return r?d:await Y(d,this.getSignerAccordingSdk(),null==(s=this.config)?void 0:s.gasFeeMultiplier,this.contract.authorize,t,e,o,c,l)}async cancelExpiredLocks(t,e,a,i,n){var r;const s=await this.contract.estimateGas.cancelExpiredLocks(t,e,a,i);return n?s:await Y(s,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,this.contract.cancelExpiredLocks,t,e,a,i)}}class Ct extends et{getDefaultAbi(){return b.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){const a=this.amountToUnits(t,e.toString()),i=await this.contract.calculateFee(t,a);return this.unitsToAmount(t,i)}}async function Dt(t){return new Promise(e=>{setTimeout(e,t)})}function xt(t){return null!=t}async function Mt(t,e){const i=a.utils.arrayify(e);let n=await t._legacySignMessage(i);n=n.substr(2);const r="0x"+n.slice(0,64),s="0x"+n.slice(64,128);let o="0x"+n.slice(128,130);return"0x00"===o&&(o="0x1b"),"0x01"===o&&(o="0x1c"),{v:o,r,s}}async function Ot(t,e){const i=a.utils.solidityKeccak256(["bytes"],[a.utils.hexlify(a.utils.toUtf8Bytes(e))]),n=a.utils.arrayify(i),r=await t.getChainId();try{return await t.signMessage(n)}catch(e){if(L.error("Sign message error: ",e),8996===r)return console.log("Signing message with _legacySignMessage"),await t._legacySignMessage(n)}}class Rt{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 F(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 L.error(t),new Error("HTTP request failed")}}async waitForIndexer(t,e,a,i=3e4,n=100,r){let s=0;n>500&&(L.warn("Max Limit exceeded, defaulting to 500 retries."),n=500);do{try{const i=this.aquariusURL+"/api/aquarius/assets/ddo/"+t,n=await F(i,{method:"GET",headers:{"Content-Type":"application/json",Authorization:r},signal:a});if(n.ok){const t=await n.json(),a=E.getDDOClass(t),{indexedMetadata:i}=a.getAssetFields();if(!e)return t;if(i.event&&i.event.txid===e)return t}}catch(t){}await Dt(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 F(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=a+l,u={ddo:t,publisherAddress:a,nonce:l,signature:await Ot(e,d)},h=await F(r,{method:"POST",body:JSON.stringify(u),headers:{"Content-Type":"application/octet-stream",Authorization:n},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){L.error("Metadata validation failed",t.message)}}async getAssetMetadata(t,e,a){const i=this.aquariusURL+"/api/aquarius/assets/metadata/"+t;try{const t=await F(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 L.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 F(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 L.error("Error querying metadata: ",t),new Error("Error querying metadata: "+t)}}}class Pt{async getConsumerAddress(t){return"string"==typeof t?function(t){try{return C.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 L.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 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 F(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 L.error(t),new Error(t.message)}}async signProviderRequest(t,e){const i=a.utils.solidityKeccak256(["bytes"],[a.utils.hexlify(a.utils.toUtf8Bytes(e))]),n=a.utils.arrayify(i);try{return await t.signMessage(n)}catch(e){if(8996===await t.getChainId())return await t._legacySignMessage(n)}}async encrypt(t,e,a,i){const n=await this.getEndpoints(a),r=await this.getServiceEndpoints(a,n),s=(this.getEndpointURL(r,"encrypt")?this.getEndpointURL(r,"encrypt").urlPath:null)+`?chainId=${e}`;if(!s)return null;try{const e=await F(s,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/octet-stream"},signal:i});return await e.text()}catch(t){throw L.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 F(d,{method:"POST",body:JSON.stringify(c),headers:{"Content-Type":"application/json"},signal:n})}catch(t){throw L.error("File info call failed: "),L.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 L.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=N({},t,{checksum:a}),c=[],l=this.getEndpointURL(s,"fileinfo")?this.getEndpointURL(s,"fileinfo").urlPath:null;if(!l)return null;let d;try{d=await F(l,{method:"POST",body:JSON.stringify(o),headers:{"Content-Type":"application/json"},signal:i})}catch(t){throw L.error("File info call failed: "),L.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 L.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 F(s,{method:"GET",headers:{"Content-Type":"application/json"},signal:e})}catch(t){throw L.error("Fetch compute env failed: "),L.error(t),new Error(t)}if(null!=(i=o)&&i.ok)return o.json();const c=await o.json();throw L.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 F(g,{method:"GET",headers:{"Content-Type":"application/json"},signal:r})}catch(t){throw L.error("Provider initialized failed: "),L.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 L.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 F(g,{method:"POST",body:JSON.stringify(h),headers:{"Content-Type":"application/json"},signal:c})}catch(t){throw L.error("Initialize compute failed: "),L.error(t),new Error("ComputeJob cannot be initialized")}if(null!=(l=w)&&l.ok)return await w.json();const p=await w.json();throw L.error("Initialize compute failed: ",w.status,w.statusText,p),L.error("Payload was:",JSON.stringify(h)),new Error(JSON.stringify(p))}async initializeCompute(t,e,a,i,n,r,s,o,c,l,d){var u,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,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:n,consumerAddress:m,signature:await this.getSignature(s,y)};let k;l&&(v.policyServer=l);try{if(console.log("Initialize compute url:",p),k=await F(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 L.error("Initialize compute failed: "),L.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 L.error("Initialize compute failed: ",k.status,k.statusText,T),L.error("Payload was:",JSON.stringify(v)),new Error(JSON.stringify(T))}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,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,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 this.signProviderRequest(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 F(u,{method:"POST",body:JSON.stringify(m),headers:{"Content-Type":"application/json"},signal:r})}catch(t){throw L.error("Compute start failed:"),L.error(t),L.error("Payload was:",m),new Error("HTTP request failed calling Provider")}return null!=(c=f)&&c.ok?await f.json():(L.error("Compute start failed: ",f.status,f.statusText,await f.json()),L.error("Payload was:",m),null)}async computeStart(t,e,a,i,n,r,s,o,c,l,d,u,h){var g,w;console.log("called new compute start method..."),console.log("datasets: ",i),console.log("algorithm: ",n);const p=await this.getEndpoints(t),m=await this.getServiceEndpoints(t,p),f=this.getEndpointURL(m,"computeStart")?this.getEndpointURL(m,"computeStart").urlPath:null;if(!f)return L.error("Compute start failed: Cannot get proper computeStart route (perhaps not implemented on provider?)"),null;const y=await this.getConsumerAddress(e),v=(await this.getNonce(t,y,h,p,m)+1).toString();let k=y;k+=null==(g=i[0])?void 0:g.documentId,k+=v;const T=await this.getSignature(e,k),A=Object();let S;A.consumerAddress=y,A.signature=T,A.nonce=v,A.environment=a,A.maxJobDuration=r,A.resources=o,A.dataset=i[0],A.datasets=i,A.algorithm=n,A.chainId=c,A.payment={chainId:c,token:s,maxJobDuration:r},o&&(A.payment.resources=o),l&&(A.metadata=l),d&&(A.output=d),u&&(A.policyServer=u);try{S=await F(f,{method:"POST",body:JSON.stringify(A),headers:{"Content-Type":"application/json",Authorization:this.getAuthorization(e)},signal:h})}catch(t){throw L.error("Compute start failed:"),L.error(t),L.error("Payload was:",A),new Error("HTTP request failed calling Provider")}return null!=(w=S)&&w.ok?await S.json():(L.error("Compute start failed: ",S.status,S.statusText,await S.json()),L.error("Payload was:",A),null)}async freeComputeStart(t,e,a,i,n,r,s,o,c,l){var d;console.log("called new free compute start method..."),console.log("datasets: ",i),console.log("algorithm: ",n);const u=await this.getEndpoints(t),h=await this.getServiceEndpoints(t,u),g=this.getEndpointURL(h,"freeCompute")?this.getEndpointURL(h,"freeCompute").urlPath:null;if(!g)return L.error("Compute start failed: Cannot get proper computeStart route (perhaps not implemented on provider?)"),null;const w=await this.getConsumerAddress(e),p=(await this.getNonce(t,w,l,u,h)+1).toString(),m=p;console.log("signatureMessage: ",m);const f=await this.getSignature(e,m),y=Object();let v;y.consumerAddress=w,y.signature=f,y.nonce=p,y.environment=a,y.resources=r,y.dataset=i[0],y.datasets=i,y.algorithm=n,s&&(y.metadata=s),y.output=o,c&&(y.policyServer=c);try{v=await F(g,{method:"POST",body:JSON.stringify(y),headers:{"Content-Type":"application/json",Authorization:this.getAuthorization(e)},signal:l})}catch(t){throw L.error("Compute start failed:"),L.error(t),L.error("Payload was:",y),new Error("HTTP request failed calling Provider")}return null!=(d=v)&&d.ok?await v.json():(L.error("Compute start failed: ",v.status,v.statusText,await v.json()),L.error("Payload was:",y),null)}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 L.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 F(l+g,{method:"GET",headers:{"Content-Type":"application/json",Authorization:this.getAuthorization(e)},signal:i}),console.log("Raw response:",h)}catch(t){throw L.error("computeStreamableLogs failed:"),L.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):(L.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=await this.getEndpoints(e),o=await this.getServiceEndpoints(e,s),c=this.getEndpointURL(o,"computeStop")?this.getEndpointURL(o,"computeStop").urlPath:null,l=await this.getConsumerAddress(a),d=(await this.getNonce(e,l,n,s,o)+1).toString(),u=l+(t||""),h=await this.getSignature(a,u),g=new URLSearchParams;g.set("consumerAddress",l),g.set("signature",h),g.set("nonce",d),g.set("jobId",t),i&&g.set("agreementId",i);const w=g.toString();if(!w)return null;let p;try{p=await F(c+"?"+w,{method:"PUT",headers:{"Content-Type":"application/json",Authorization:this.getAuthorization(a)},signal:n})}catch(t){throw L.error("Compute stop failed:"),L.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 L.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 F(d+h,{method:"GET",headers:{"Content-Type":"application/json",Authorization:r},signal:n})}catch(t){throw L.error("Get compute status failed"),L.error(t),new Error(t)}if(null!=(s=u)&&s.ok)return await u.json();if(L.error("Get compute status failed:",u.status,u.statusText),null!=(o=u)&&o.ok)return await u.json();const g=await u.json();throw L.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();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()}`,n||(h+=`&nonce=${l}`,h+=`&signature=${u}`),h}async computeDelete(t,e,a,i,n){var r;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,n,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 F(c,{method:"DELETE",body:JSON.stringify(g),headers:{"Content-Type":"application/json",Authorization:this.getAuthorization(e)},signal:n})}catch(t){throw L.error("Delete compute job failed:"),L.error(t),L.error("Payload was:",g),new Error("HTTP request failed calling Provider")}if(null!=(r=w)&&r.ok)return await w.json();const p=await w.json();throw L.error("Delete compute job failed:",w.status,w.statusText,p),L.error("Payload was:",g),new Error(JSON.stringify(p))}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=i+o,l=await this.signProviderRequest(t,c);try{const t=await F(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 L.error("Generate auth token failed:"),L.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 this.signProviderRequest(t,l);try{const t=await F(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 L.error("Generate auth token failed:"),L.error(t),new Error("HTTP request failed calling Provider")}}async isValidProvider(t,e){try{const a=await F(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 L.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 F(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 L.error("PolicyServerPassthrough failed: "),L.error(t),new Error(`PolicyServerPassthrough failed: ${t.message}.`)}if(null!=(i=o)&&i.ok)return await o.json();const c=await o.json();throw L.error("PolicyServerPassthrough failed: ",o.status,o.statusText,c),L.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 F(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 L.error("initializePSVerification failed: "),L.error(t),new Error(`initializePSVerification failed: ${t.message}.`)}if(null!=(i=o)&&i.ok)return await o.json();const c=await o.json();throw L.error("initializePSVerification failed: ",o.status,o.statusText,c),L.error("Payload was:",JSON.stringify(e)),new Error(JSON.stringify(c))}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 L.debug("Not input string:"),L.debug(t),new Error(`[${a}] Expected string, input type: ${typeof t}`);const i=t.match(e);return i?{valid:!0,output:i[1]}:(L.warn(`[${a}] Input transformation failed.`),{valid:!1,output:t})}async getData(t,e){return F(t,{method:"GET",headers:{"Content-type":"application/json",Authorization:e}})}}const Ut=new Pt;function Nt(t,e){return t=a.utils.getAddress(t),`did:op:${D(t+e.toString(10)).toString()}`}function It(t){return D(t).toString()}function Lt(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 jt(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 Gt(t,e,i,n,s,o,c=!1,l,d){const u=new a.Contract(n,B,t);if(!c){const e=await Bt(t,n,i,s);if(new r(e).greaterThanOrEqualTo(new r(o)))return new r(e).toNumber()}const h=await K(t,n,o,l),g=await u.estimateGas.approve(s,h);return d?new r(g.toString()):await Y(g,t,null==e?void 0:e.gasFeeMultiplier,u.approve,s,h)}async function _t(t,e,i,n,r,s,o=!1,c){const l=new a.Contract(n,B,t);if(!o){const e=await qt(t,n,i,r);if(a.BigNumber.from(e).gt(a.BigNumber.from(s)))return a.BigNumber.from(e)}let d=null;const u=await l.estimateGas.approve(r,s);if(c)return u;try{d=await Y(u,t,null==e?void 0:e.gasFeeMultiplier,l.approve,r,s)}catch(t){L.error(`ERROR: Failed to approve spender to spend tokens : ${t.message}`)}return d}async function $t(t,e,i,n,r,s){const o=new a.Contract(i,B,t),c=await K(t,i,r),l=await o.estimateGas.transfer(n,c);return s?l:await Y(l,t,null==e?void 0:e.gasFeeMultiplier,o.transfer,n,c)}async function Bt(t,e,i,n,r){const s=new a.Contract(e,B,t),o=await s.allowance(i,n);return await X(t,e,o,r)}async function zt(t,e,i,n){const r=new a.Contract(e,B,t),s=await r.balanceOf(i);return await X(t,e,s,n)}async function qt(t,e,i,n){const r=new a.Contract(e,B,t);return await r.allowance(i,n)}async function Jt(t,e){const i=new a.Contract(e,B,t);return await i.decimals()}const Wt={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=Wt[i])?void 0:e[t])||`Provider request failed: ${t}`}{const t=a[i];return`${a[Object.keys(a)[1]]} : ${t}`}}catch(e){return L.error("[getErrorMessage] error: ",e),t}}async function Ht(t,e,a,i,n,s,o,c,l="0",d=0,u=0,h=0){const g=E.getDDOClass(t),{datatokens:w}=g.getAssetFields(),{chainId:p,services:m}=g.getDDOFields();if(o||(o={consumeMarketFeeAddress:"0x0000000000000000000000000000000000000000",consumeMarketFeeAmount:"0",consumeMarketFeeToken:"0x0000000000000000000000000000000000000000"}),p!==(await e.provider.getNetwork()).chainId)throw new Error("Chain ID from DDO is different than the configured network.");if(!w[d].address)throw new Error(`The datatoken with index: ${d} does not exist for the asset with did: ${t.id}`);if(!m[u].id)throw new Error(`There is no service with index: ${u} defined for the asset with did: ${t.id}`);const f=await i.getId(w[d].address),y=await i.getFixedRates(w[d].address),v=await i.getDispensers(w[d].address),k=await i.getPublishingMarketFee(w[d].address),T=y.length>0?"fixed":v.length>0?"free":"NOT_ALLOWED",A=c||(await Ut.initialize(t.id,m[u].id,0,await e.getAddress(),n||a.oceanNodeUri)).providerFee;if(A&&A.providerFeeAddress!==it&&A.providerFeeAmount&&parseInt(A.providerFeeAmount)>0)try{await _t(e,a,await e.getAddress(),A.providerFeeToken,m[0].datatokenAddress,A.providerFeeAmount)}catch(t){throw new Error(`Failed to approve provider fee token ${A.providerFeeToken}`)}const S={consumer:s||await e.getAddress(),serviceIndex:u,_providerFee:A,_consumeMarketFee:o};switch(T){case"free":if(1===f){const t=new at(a.dispenserAddress,e),n=await t.dispense(w[d].address,"1",await e.getAddress());if(!n)throw new Error("Failed to dispense !");return await n.wait(),await i.startOrder(w[d].address,S.consumer,S.serviceIndex,S._providerFee,S._consumeMarketFee)}if(2===f||4===f)return await i.buyFromDispenserAndOrder(m[u].datatokenAddress,S,a.dispenserAddress);break;case"fixed":{const n=new ot(a.fixedRateExchangeAddress,e);if(!y[h].id)throw new Error(`There is no fixed rate exchange with index: ${u} for the asset with did: ${t.id}`);const s=await n.getFeesInfo(y[h].id),c=await n.getExchange(y[h].id),{baseTokenAmount:g}=await n.calcBaseInGivenDatatokensOut(s.exchangeId,"1",o.consumeMarketFeeAmount),p=new r(+g||0).add(new r(o.consumeMarketFeeAmount||0)).add(new r(+k.publishMarketFeeAmount||0)).toString(),m={exchangeContract:a.fixedRateExchangeAddress,exchangeId:s.exchangeId,maxBaseTokenAmount:p,baseTokenAddress:c.baseToken,baseTokenDecimals:parseInt(c.btDecimals)||18,swapMarketFee:l,marketFeeAddress:k.publishMarketFeeAddress};if(1===f){const t=await Gt(e,a,await e.getAddress(),c.baseToken,a.fixedRateExchangeAddress,p,!1);if(!("number"!=typeof t?await t.wait():t))throw new Error(`Failed to approve ${c.baseToken} !`);const r=await n.buyDatatokens(c.exchangeId,"1",p,k.publishMarketFeeAddress,l);if(!await r.wait())throw new Error("Failed to buy datatoken from fixed rate!");return await i.startOrder(w[d].address,S.consumer,S.serviceIndex,S._providerFee,S._consumeMarketFee)}if(2===f||4===f){const t=await Gt(e,a,await e.getAddress(),c.baseToken,w[d].address,p,!1);if(!t)throw new Error(`Failed to approve ${c.baseToken} !`);if(!("number"!=typeof t?await t.wait():t))throw new Error("Failed to confirm/mine approval transaction!");return await i.buyFromFreAndOrder(w[d].address,S,m)}break}default:throw new Error("Pricing schema not supported !")}}const Zt=8996;function Xt(t){const e=(new $).getConfig(t);return e&&"oasis"===e.sdk}async function Kt(t,e,i,n,r,s,o=!0,c,l,d,u,h,g){var p,m,f;const y=E.getDDOClass(s),{indexedMetadata:v}=y.getAssetFields(),k=(null==(p=y.getDDOData())||null==(p=p.stats)||null==(p=p.price)?void 0:p.value)||(null==v||null==(m=v.stats[0])||null==(m=m.prices[0])?void 0:m.price);let{chainId:T,nftAddress:A}=y.getDDOFields();const{services:S}=y.getDDOFields();if("string"!=typeof r&&"number"!=typeof r)throw new Error('Invalid template! Must be a "number" or a "string"');const b=(await i.provider.getNetwork()).chainId;if(T&&T!==b)throw new Error("Chain ID from DDO is different than the configured network.");const F=(new $).getConfig(parseInt(String(b)));let C=await wt(i,F.nftFactoryAddress,r,b);if(C<1){if(8996!==b)throw new Error(`Invalid template index: ${C}`);C=1}const D=new pt(i,b),R=new ut(F.nftFactoryAddress,i,b),P=await i.getAddress(),U={name:t,symbol:e,templateIndex:1,tokenURI:"aaa",transferable:!0,owner:P},N={templateIndex:C,cap:"100000",feeAmount:"0",paymentCollector:P,feeToken:l||F.oceanTokenAddress,minter:P,mpFeeAddress:it};let I;null!=n&&n.files[0].type&&[O.ARWEAVE,O.IPFS,O.URL].includes(null==n||null==(f=n.files[0])||null==(f=f.type)?void 0:f.toLowerCase())||(console.log('Missing or invalid files object type, defaulting to "url"'),n.type=O.URL),"oasis"===F.sdk&&(N.filesObject=n,N.accessListFactory=u||F.accessListFactory,N.allowAccessList=h,N.denyAccessList=g);try{if(k)if("0"===k.toString()){const t={dispenserAddress:F.dispenserAddress,maxTokens:"1",maxBalance:"100000000",withMint:!0,allowedSwapper:it};I=await R.createNftWithDatatokenWithDispenser(U,N,t)}else{const t={fixedRateAddress:F.fixedRateExchangeAddress,baseTokenAddress:F.oceanTokenAddress,owner:P,marketFeeCollector:P,baseTokenDecimals:18,datatokenDecimals:18,fixedRate:k.toString(),marketFee:"0",allowedConsumer:P,withMint:!0};I=await R.createNftWithDatatokenWithFixedRate(U,N,t)}else I=await R.createNftWithDatatoken(U,N)}catch(t){return console.log("ERROR creating NFT bundle",t),null}const L=await I.wait(),j=Q(L,"NFTCreated"),G=Q(L,"TokenCreated"),_=j.args.newTokenAddress,B=G.args.newTokenAddress;if(n.datatokenAddress=B,n.nftAddress=_,"oasis"===F.sdk){const t=new a.Contract(B,w.abi,i);try{const e=await t.setFilesObject(a.utils.toUtf8Bytes(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}}S[0].files="oasis"===F.sdk?"":await Ut.encrypt(n,b,c),S[0].datatokenAddress=B,S[0].serviceEndpoint=c,A=_;const z=y.makeDid(A,T.toString());let q,J,W;if(s=y.updateFields({id:z,nftAddress:A}),o)q=await Ut.encrypt(s,b,c),J=(await d.validate(s,i,c)).hash,W=2;else{const t=JSON.stringify(s),e=Buffer.from(t);q=x(e),J="0x"+M("sha256").update(q).digest("hex"),W=0}return await D.setMetadata(A,await i.getAddress(),0,c,"",a.utils.hexlify(W),q,J),s.id}async function Qt(t,e,i){const n=new a.Contract(t,m.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 Q(await t.wait(),"NewAccessList").args[0]}catch(t){console.log("ERROR createAccessListFactory(): ",t)}return null}export{yt as AccessListContract,vt as AccesslistFactory,Rt as Aquarius,U as Config,$ as ConfigHelper,Zt as DEVELOPMENT_CHAIN_ID,mt as Datatoken,ft as Datatoken4,bt as DfRewards,Ft as DfStrategyV1,at as Dispenser,R as EncryptMethod,Ct as EnterpriseFeeCollectorContract,Et as EscrowContract,st as FEE_HISTORY_NOT_SUPPORTED,O as FileObjectType,ot as FixedRateExchange,nt as GASLIMIT_DEFAULT,_ as KNOWN_CONFIDENTIAL_EVMS,P as LogLevel,I as Logger,L as LoggerInstance,rt as MAX_UINT_256,pt as Nft,ut as NftFactory,Pt as Provider,Ut as ProviderInstance,ct as Router,tt as SmartContract,et as SmartContractWithAddress,St as VeAllocate,Tt as VeFeeDistributor,At as VeFeeEstimate,kt as VeOcean,it as ZERO_ADDRESS,Bt as allowance,qt as allowanceWei,K as amountToUnits,Gt as approve,_t as approveWei,zt as balance,wt as calculateActiveTemplateIndex,G as configHelperNetworks,Qt as createAccessListFactory,Kt as createAsset,Jt as decimals,jt as downloadFile,Lt as downloadFileBrowser,Nt as generateDid,dt as generateDtName,Vt as getErrorMessage,Q as getEventFromTx,H as getFairGasPrice,It as getHash,ht as getOceanArtifactsAddresses,gt as getOceanArtifactsAddressesByChainId,Z as getTokenDecimals,xt as isDefined,B as minAbi,Ht as orderAsset,Y as sendTx,V as setContractDefaults,Mt as signHash,Ot as signRequest,Dt as sleep,$t as transfer,X as unitsToAmount,Xt as useOasisSDK};
|
|
2
2
|
//# sourceMappingURL=lib.modern.js.map
|