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