diff --git a/bun.lockb b/bun.lockb index 687864c..c666dea 100755 Binary files a/bun.lockb and b/bun.lockb differ diff --git a/package.json b/package.json index f0e71e0..7c4859e 100644 --- a/package.json +++ b/package.json @@ -1,11 +1,9 @@ { "name": "translucent-cardano", "module": "index.ts", + "main": "index.ts", "type": "module", "version": "0.0.2", - "scripts": { - "build:wasm": "cd ./uplc && ./build.sh && rm pkg-node/.gitignore && rm pkg-web/.gitignore && cd .. && npm i" - }, "devDependencies": { "@types/jest": "^29.5.5", "@types/sha256": "^0.2.2", @@ -13,24 +11,24 @@ "eslint": "^8.50.0", "jest": "^29.7.0", "ts-jest": "^29.1.1", - "typescript": "^5.3.3", - "@cardano-ogmios/schema": "^6.0.0-rc6" + "typescript": "^5.3.3" }, "dependencies": { + "@aws-crypto/sha256-browser": "^5.2.0", "@dcspark/cardano-multiplatform-lib-browser": "^3.1.2", "@dcspark/cardano-multiplatform-lib-nodejs": "^3.1.2", "@emurgo/cardano-message-signing-browser": "^1.0.1", "@emurgo/cardano-message-signing-nodejs": "^1.0.1", "@sinclair/typebox": "^0.31.28", "fast-check": "^3.14.0", - "mathjs": "^12.2.1", "prettier": "^3.1.1", - "sha256": "^0.2.0", - "uplc-node": "^0.0.2", - "uplc-web": "^0.0.2" + "uplc-node": "^0.0.3", + "uplc-web": "^0.0.3" }, "browser": { - "./core/core.ts": "./core/core-browser.ts" + "@dcspark/cardano-multiplatform-lib-nodejs": "@dcspark/cardano-multiplatform-lib-browser", + "@emurgo/cardano-message-signing-nodejs": "@emurgo/cardano-message-signing-browser", + "uplc-node": "uplc-web" }, "peerDependencies": { "typescript": "^5.0.0" diff --git a/src/core/core-browser.ts b/src/core/core-browser.ts deleted file mode 100644 index b016fd7..0000000 --- a/src/core/core-browser.ts +++ /dev/null @@ -1,5 +0,0 @@ -import * as C from "@dcspark/cardano-multiplatform-lib-browser"; -import * as U from "uplc-web"; -import * as M from "@emurgo/cardano-message-signing-browser"; - -export { C, U, M }; diff --git a/src/misc/bip39.ts b/src/misc/bip39.ts index bb667d6..9707767 100644 --- a/src/misc/bip39.ts +++ b/src/misc/bip39.ts @@ -1,7 +1,7 @@ // This is a partial reimplementation of BIP39 in Deno: https://github.com/bitcoinjs/bip39 // We only use the default Wordlist (english) import { toHex } from "../utils/mod.ts"; -import sha256 from "sha256"; +import {Sha256} from '@aws-crypto/sha256-browser' const INVALID_MNEMONIC = "Invalid mnemonic"; const INVALID_ENTROPY = "Invalid entropy"; @@ -10,10 +10,10 @@ const WORDLIST_REQUIRED = "A wordlist is required but a default could not be found.\n" + "Please pass a 2048 word array explicitly."; -export function mnemonicToEntropy( +export async function mnemonicToEntropy( mnemonic: string, wordlist?: Array, -): string { +): Promise { wordlist = wordlist || DEFAULT_WORDLIST; if (!wordlist) { throw new Error(WORDLIST_REQUIRED); @@ -48,7 +48,7 @@ export function mnemonicToEntropy( throw new Error(INVALID_ENTROPY); } const entropy = new Uint8Array(entropyBytes); - const newChecksum = deriveChecksumBits(entropy); + const newChecksum = await deriveChecksumBits(entropy); if (newChecksum !== checksumBits) { throw new Error(INVALID_CHECKSUM); } @@ -83,24 +83,24 @@ function randomBytes(size: number): Uint8Array { return bytes; } -export function generateMnemonic( +export async function generateMnemonic( strength: number, rng?: (size: number) => Uint8Array, wordlist?: Array, -): string { +): Promise { strength = strength || 128; if (strength % 32 !== 0) { throw new TypeError(INVALID_ENTROPY); } rng = rng || randomBytes; - return entropyToMnemonic(rng(strength / 8), wordlist); + return await entropyToMnemonic(rng(strength / 8), wordlist); } -function entropyToMnemonic( +async function entropyToMnemonic( entropy: Uint8Array, wordlist?: Array, -): string { +): Promise { wordlist = wordlist || DEFAULT_WORDLIST; if (!wordlist) { throw new Error(WORDLIST_REQUIRED); @@ -116,7 +116,7 @@ function entropyToMnemonic( throw new TypeError(INVALID_ENTROPY); } const entropyBits = bytesToBinary(Array.from(entropy)); - const checksumBits = deriveChecksumBits(entropy); + const checksumBits = await deriveChecksumBits(entropy); const bits = entropyBits + checksumBits; const chunks = bits.match(/(.{1,11})/g); const words = chunks!.map((binary) => { @@ -128,10 +128,14 @@ function entropyToMnemonic( : words.join(" "); } -function deriveChecksumBits(entropyBuffer: Uint8Array): string { +async function deriveChecksumBits(entropyBuffer: Uint8Array): Promise { const ENT = entropyBuffer.length * 8; const CS = ENT / 32; - const hash = sha256(Array.from(entropyBuffer), { asBytes: true }); + const hasher = new Sha256(); + hasher.update(entropyBuffer); + const hash = await hasher.digest(); + + //const hash = sha256(Array.from(entropyBuffer), { asBytes: true }); return bytesToBinary(Array.from(hash)).slice(0, CS); } diff --git a/src/provider/blockfrost.ts b/src/provider/blockfrost.ts deleted file mode 100644 index e8aed1d..0000000 --- a/src/provider/blockfrost.ts +++ /dev/null @@ -1,357 +0,0 @@ -import { C } from "../core/mod.ts"; -import * as mathjs from "mathjs"; - -import { applyDoubleCborEncoding, fromHex, toHex } from "../utils/mod.ts"; -import { - Address, - Credential, - Datum, - DatumHash, - Delegation, - OutRef, - ProtocolParameters, - Provider, - RewardAddress, - Transaction, - TxHash, - Unit, - UTxO, -} from "../types/mod.ts"; -import packageJson from "../../package.json" assert { type: "json" }; -import { M } from "translucent-cardano"; - -export class Blockfrost implements Provider { - url: string; - projectId: string; - - constructor(url: string, projectId?: string) { - this.url = url; - this.projectId = projectId || ""; - } - - async getProtocolParameters(): Promise { - const result: Response | unknown = await fetch( - `${this.url}/epochs/latest/parameters`, - { - headers: { project_id: this.projectId, translucent }, - }, - ).then((res) => res.json()); - - const fraction = (str: string): [bigint, bigint] => { - const fr = mathjs.fraction(str); - return [BigInt(fr.n), BigInt(fr.d)]; - }; - return { - minFeeA: parseInt(result.min_fee_a), - minFeeB: parseInt(result.min_fee_b), - maxTxSize: parseInt(result.max_tx_size), - maxValSize: parseInt(result.max_val_size), - keyDeposit: BigInt(result.key_deposit), - poolDeposit: BigInt(result.pool_deposit), - priceMem: fraction(result.price_mem), - priceStep: fraction(result.price_step), - maxTxExMem: BigInt(result.max_tx_ex_mem), - maxTxExSteps: BigInt(result.max_tx_ex_steps), - coinsPerUtxoByte: BigInt(result.coins_per_utxo_size), - collateralPercentage: parseInt(result.collateral_percent), - maxCollateralInputs: parseInt(result.max_collateral_inputs), - costModels: result.cost_models, - }; - } - - async getUtxos(addressOrCredential: Address | Credential): Promise { - const queryPredicate = (() => { - if (typeof addressOrCredential === "string") return addressOrCredential; - const credentialBech32 = - addressOrCredential.type === "Key" - ? C.Ed25519KeyHash.from_hex(addressOrCredential.hash).to_bech32( - "addr_vkh", - ) - : C.ScriptHash.from_hex(addressOrCredential.hash).to_bech32( - "addr_vkh", - ); // should be 'script' (CIP-0005) - return credentialBech32; - })(); - let result: BlockfrostUtxoResult = []; - let page = 1; - while (true) { - const pageResult: BlockfrostUtxoResult | BlockfrostUtxoError = - await fetch( - `${this.url}/addresses/${queryPredicate}/utxos?page=${page}`, - { headers: { project_id: this.projectId, translucent } }, - ).then((res) => res.json()); - if ((pageResult as BlockfrostUtxoError).error) { - if ((pageResult as BlockfrostUtxoError).status_code === 404) { - return []; - } else { - throw new Error("Could not fetch UTxOs from Blockfrost. Try again."); - } - } - result = result.concat(pageResult as BlockfrostUtxoResult); - if ((pageResult as BlockfrostUtxoResult).length <= 0) break; - page++; - } - - return this.blockfrostUtxosToUtxos(result); - } - - async getUtxosWithUnit( - addressOrCredential: Address | Credential, - unit: Unit, - ): Promise { - const queryPredicate = (() => { - if (typeof addressOrCredential === "string") return addressOrCredential; - const credentialBech32 = - addressOrCredential.type === "Key" - ? C.Ed25519KeyHash.from_hex(addressOrCredential.hash).to_bech32( - "addr_vkh", - ) - : C.ScriptHash.from_hex(addressOrCredential.hash).to_bech32( - "addr_vkh", - ); // should be 'script' (CIP-0005) - return credentialBech32; - })(); - let result: BlockfrostUtxoResult = []; - let page = 1; - while (true) { - const pageResult: BlockfrostUtxoResult | BlockfrostUtxoError = - await fetch( - `${this.url}/addresses/${queryPredicate}/utxos/${unit}?page=${page}`, - { headers: { project_id: this.projectId, translucent } }, - ).then((res) => res.json()); - if ((pageResult as BlockfrostUtxoError).error) { - if ((pageResult as BlockfrostUtxoError).status_code === 404) { - return []; - } else { - throw new Error("Could not fetch UTxOs from Blockfrost. Try again."); - } - } - result = result.concat(pageResult as BlockfrostUtxoResult); - if ((pageResult as BlockfrostUtxoResult).length <= 0) break; - page++; - } - - return this.blockfrostUtxosToUtxos(result); - } - - async getUtxoByUnit(unit: Unit): Promise { - const addresses = await fetch( - `${this.url}/assets/${unit}/addresses?count=2`, - { headers: { project_id: this.projectId, translucent } }, - ).then((res) => res.json()); - - if (!addresses || addresses.error) { - throw new Error("Unit not found."); - } - if (addresses.length > 1) { - throw new Error("Unit needs to be an NFT or only held by one address."); - } - - const address = addresses[0].address; - - const utxos = await this.getUtxosWithUnit(address, unit); - - if (utxos.length > 1) { - throw new Error("Unit needs to be an NFT or only held by one address."); - } - - return utxos[0]; - } - - async getUtxosByOutRef(outRefs: OutRef[]): Promise { - // TODO: Make sure old already spent UTxOs are not retrievable. - const queryHashes = [...new Set(outRefs.map((outRef) => outRef.txHash))]; - const utxos = await Promise.all( - queryHashes.map(async (txHash) => { - const result = await fetch(`${this.url}/txs/${txHash}/utxos`, { - headers: { project_id: this.projectId, translucent }, - }).then((res) => res.json()); - if (!result || result.error) { - return []; - } - const utxosResult: BlockfrostUtxoResult = result.outputs.map( - ( - // deno-lint-ignore no-explicit-any - r: any, - ) => ({ - ...r, - tx_hash: txHash, - }), - ); - return this.blockfrostUtxosToUtxos(utxosResult); - }), - ); - - return utxos - .reduce((acc, utxos) => acc.concat(utxos), []) - .filter((utxo) => - outRefs.some( - (outRef) => - utxo.txHash === outRef.txHash && - utxo.outputIndex === outRef.outputIndex, - ), - ); - } - - async getDelegation(rewardAddress: RewardAddress): Promise { - const result = await fetch(`${this.url}/accounts/${rewardAddress}`, { - headers: { project_id: this.projectId, translucent }, - }).then((res) => res.json()); - if (!result || result.error) { - return { poolId: null, rewards: 0n }; - } - return { - poolId: result.pool_id || null, - rewards: BigInt(result.withdrawable_amount), - }; - } - - async getDatum(datumHash: DatumHash): Promise { - const datum = await fetch(`${this.url}/scripts/datum/${datumHash}/cbor`, { - headers: { project_id: this.projectId, translucent }, - }) - .then((res) => res.json()) - .then((res) => res.cbor); - if (!datum || datum.error) { - throw new Error(`No datum found for datum hash: ${datumHash}`); - } - return datum; - } - - awaitTx(txHash: TxHash, checkInterval = 3000): Promise { - return new Promise((res) => { - const confirmation = setInterval(async () => { - const isConfirmed = await fetch(`${this.url}/txs/${txHash}`, { - headers: { project_id: this.projectId, translucent }, - }).then((res) => res.json()); - if (isConfirmed && !isConfirmed.error) { - clearInterval(confirmation); - await new Promise((res) => setTimeout(() => res(1), 1000)); - return res(true); - } - }, checkInterval); - }); - } - - async submitTx(tx: Transaction): Promise { - const result = await fetch(`${this.url}/tx/submit`, { - method: "POST", - headers: { - "Content-Type": "application/cbor", - project_id: this.projectId, - translucent, - }, - body: fromHex(tx), - }).then((res) => res.json()); - if (!result || result.error) { - if (result?.status_code === 400) throw new Error(result.message); - else throw new Error("Could not submit transaction."); - } - return result; - } - - private async blockfrostUtxosToUtxos( - result: BlockfrostUtxoResult, - ): Promise { - return (await Promise.all( - result.map(async (r) => ({ - txHash: r.tx_hash, - outputIndex: r.output_index, - assets: Object.fromEntries( - r.amount.map(({ unit, quantity }) => [unit, BigInt(quantity)]), - ), - address: r.address, - datumHash: (!r.inline_datum && r.data_hash) || undefined, - datum: r.inline_datum || undefined, - scriptRef: r.reference_script_hash - ? await (async () => { - const { type } = await fetch( - `${this.url}/scripts/${r.reference_script_hash}`, - { - headers: { project_id: this.projectId, translucent }, - }, - ).then((res) => res.json()); - // TODO: support native scripts - if (type === "Native" || type === "native") { - throw new Error("Native script ref not implemented!"); - } - const { cbor: script } = await fetch( - `${this.url}/scripts/${r.reference_script_hash}/cbor`, - { headers: { project_id: this.projectId, translucent } }, - ).then((res) => res.json()); - return { - type: type === "plutusV1" ? "PlutusV1" : "PlutusV2", - script: applyDoubleCborEncoding(script), - }; - })() - : undefined, - })), - )) as UTxO[]; - } -} - -/** - * This function is temporarily needed only, until Blockfrost returns the datum natively in Cbor. - * The conversion is ambigious, that's why it's better to get the datum directly in Cbor. - */ -export function datumJsonToCbor(json: DatumJson): Datum { - const convert = (json: DatumJson): C.PlutusData => { - if (!isNaN(json.int!)) { - return C.PlutusData.new_integer(C.BigInt.from_str(json.int!.toString())); - } else if (json.bytes || !isNaN(Number(json.bytes))) { - return C.PlutusData.new_bytes(fromHex(json.bytes!)); - } else if (json.map) { - const m = C.PlutusMap.new(); - json.map.forEach(({ k, v }: { k: unknown; v: unknown }) => { - m.insert(convert(k as DatumJson), convert(v as DatumJson)); - }); - return C.PlutusData.new_map(m); - } else if (json.list) { - const l = C.PlutusList.new(); - json.list.forEach((v: DatumJson) => { - l.add(convert(v)); - }); - return C.PlutusData.new_list(l); - } else if (!isNaN(json.constructor! as unknown as number)) { - const l = C.PlutusList.new(); - json.fields!.forEach((v: DatumJson) => { - l.add(convert(v)); - }); - return C.PlutusData.new_constr_plutus_data( - C.ConstrPlutusData.new( - C.BigNum.from_str(json.constructor!.toString()), - l, - ), - ); - } - throw new Error("Unsupported type"); - }; - - return toHex(convert(json).to_bytes()); -} - -type DatumJson = { - int?: number; - bytes?: string; - list?: Array; - map?: Array<{ k: unknown; v: unknown }>; - fields?: Array; - [constructor: string]: unknown; // number; constructor needs to be simulated like this as optional argument -}; - -type BlockfrostUtxoResult = Array<{ - tx_hash: string; - output_index: number; - address: Address; - amount: Array<{ unit: string; quantity: string }>; - data_hash?: string; - inline_datum?: string; - reference_script_hash?: string; -}>; - -type BlockfrostUtxoError = { - status_code: number; - error: unknown; -}; - -const translucent = packageJson.version; // Translucent version diff --git a/src/provider/kupmios.ts b/src/provider/kupmios.ts index 21e533e..4c9637c 100644 --- a/src/provider/kupmios.ts +++ b/src/provider/kupmios.ts @@ -17,7 +17,7 @@ import { } from "../types/mod.ts"; import { C } from "../core/mod.ts"; import { costModelKeys, fromUnit } from "../utils/mod.ts"; -import * as ogmios from "@cardano-ogmios/schema"; +import * as ogmios from "./ogmios.ts"; function fromMaybeBuffer(x: string | Buffer) { if (typeof x === "string") { diff --git a/src/provider/mod.ts b/src/provider/mod.ts index 9a22548..0764b0e 100644 --- a/src/provider/mod.ts +++ b/src/provider/mod.ts @@ -1,4 +1,3 @@ -export * from "./blockfrost.ts"; export * from "./kupmios.ts"; export * from "./kupmiosv5.ts"; export * from "./maestro.ts"; diff --git a/src/provider/ogmios.ts b/src/provider/ogmios.ts new file mode 100644 index 0000000..cdb10d4 --- /dev/null +++ b/src/provider/ogmios.ts @@ -0,0 +1,1934 @@ +export type PointOrOrigin = Point | Origin; +export type Slot = number; +export type DigestBlake2B256 = string; +export type Origin = "origin"; +export type TipOrOrigin = Tip | Origin; +export type BlockHeight = number; +export type Block = BlockEBB | BlockBFT | BlockPraos; +export type Int64 = number; +export type TransactionId = string; +export type UInt32 = number; +export type Address = string; +export type AssetQuantity = bigint; +export type Datum = string; +export type Script = Native | Plutus; +export type ScriptNative = ClauseSignature | ClauseAny | ClauseAll | ClauseSome | ClauseBefore | ClauseAfter; +export type DigestBlake2B224 = string; +export type Certificate = StakeDelegation | StakeCredentialRegistration | StakeCredentialDeregistration | StakePoolRegistration | StakePoolRetirement | GenesisDelegation | ConstitutionalCommitteeHotKeyRegistration | ConstitutionalCommitteeRetirement | DelegateRepresentativeRegistration | DelegateRepresentativeUpdate | DelegateRepresentativeRetirement; +export type StakePoolId = string; +export type DelegateRepresentative = DelegateRepresentativeRegistered | DelegateRepresentativeNoConfidence | DelegateRepresentativeAbstain; +export type Ratio = string; +export type RewardAccount = string; +export type DigestAny = string; +export type Relay = RelayByAddress | RelayByName; +export type Epoch = number; +export type None = null; +export type Network = "mainnet" | "testnet"; +export type UInt64 = number; +export type Nonce = Neutral | DigestBlake2B256; +export type Neutral = "neutral"; +export type CostModel = Int64[]; +export type Metadatum = Integer | String | ArrayMetadatum | ObjectMetadatum; +export type Integer = bigint; +export type String = string; +export type ArrayMetadatum = Metadatum[]; +export type VerificationKey = string; +export type Signature = string; +export type ChainCode = string; +export type AddressAttributes = string; +export type RedeemerData = string; +export type BootstrapProtocolId = number; +export type ExtendedVerificationKey = string; +export type GenesisHash = "genesis"; +export type VrfProof = string; +export type VrfOutput = string; +export type KesVerificationKey = string; +export type SubmitTransactionFailure = SubmitTransactionFailureEraMismatch | SubmitTransactionFailureInvalidSignatories | SubmitTransactionFailureMissingSignatories | SubmitTransactionFailureMissingScripts | SubmitTransactionFailureFailingNativeScript | SubmitTransactionFailureExtraneousScripts | SubmitTransactionFailureMissingMetadataHash | SubmitTransactionFailureMissingMetadata | SubmitTransactionFailureMetadataHashMismatch | SubmitTransactionFailureInvalidMetadata | SubmitTransactionFailureMissingRedeemers | SubmitTransactionFailureExtraneousRedeemers | SubmitTransactionFailureMissingDatums | SubmitTransactionFailureExtraneousDatums | SubmitTransactionFailureScriptIntegrityHashMismatch | SubmitTransactionFailureOrphanScriptInputs | SubmitTransactionFailureMissingCostModels | SubmitTransactionFailureMalformedScripts | SubmitTransactionFailureUnknownOutputReferences | SubmitTransactionFailureOutsideOfValidityInterval | SubmitTransactionFailureTransactionTooLarge | SubmitTransactionFailureValueTooLarge | SubmitTransactionFailureEmptyInputSet | SubmitTransactionFailureTransactionFeeTooSmall | SubmitTransactionFailureValueNotConserved | SubmitTransactionFailureNetworkMismatch | SubmitTransactionFailureInsufficientlyFundedOutputs | SubmitTransactionFailureBootstrapAttributesTooLarge | SubmitTransactionFailureMintingOrBurningAda | SubmitTransactionFailureInsufficientCollateral | SubmitTransactionFailureCollateralLockedByScript | SubmitTransactionFailureUnforeseeableSlot | SubmitTransactionFailureTooManyCollateralInputs | SubmitTransactionFailureMissingCollateralInputs | SubmitTransactionFailureNonAdaCollateral | SubmitTransactionFailureExecutionUnitsTooLarge | SubmitTransactionFailureTotalCollateralMismatch | SubmitTransactionFailureSpendsMismatch | SubmitTransactionFailureUnauthorizedVotes | SubmitTransactionFailureUnknownGovernanceProposals | SubmitTransactionFailureInvalidProtocolParametersUpdate | SubmitTransactionFailureUnknownStakePool | SubmitTransactionFailureIncompleteWithdrawals | SubmitTransactionFailureRetirementTooLate | SubmitTransactionFailureStakePoolCostTooLow | SubmitTransactionFailureMetadataHashTooLarge | SubmitTransactionFailureCredentialAlreadyRegistered | SubmitTransactionFailureUnknownCredential | SubmitTransactionFailureNonEmptyRewardAccount | SubmitTransactionFailureInvalidGenesisDelegation | SubmitTransactionFailureInvalidMIRTransfer | SubmitTransactionFailureForbiddenWithdrawal | SubmitTransactionFailureCredentialDepositMismatch | SubmitTransactionFailureDRepAlreadyRegistered | SubmitTransactionFailureDRepNotRegistered | SubmitTransactionFailureUnknownConstitutionalCommitteeMember | SubmitTransactionFailureGovernanceProposalDepositMismatch | SubmitTransactionFailureConflictingCommitteeUpdate | SubmitTransactionFailureInvalidCommitteeUpdate | SubmitTransactionFailureTreasuryWithdrawalMismatch | SubmitTransactionFailureInvalidOrMissingPreviousProposals | SubmitTransactionFailureUnrecognizedCertificateType | SubmitTransactionFailureInternalLedgerTypeConversionError; +export type Era = "byron" | "shelley" | "allegra" | "mary" | "alonzo" | "babbage" | "conway"; +export type ScriptPurpose = ScriptPurposeSpend | ScriptPurposeMint | ScriptPurposePublish | ScriptPurposeWithdraw; +export type PolicyId = string; +export type RedeemerPointer = string; +export type Language = "plutus:v1" | "plutus:v2" | "plutus:v3"; +export type Utxo = { + transaction: { + id: TransactionId; + }; + index: UInt32; + address: Address; + value: Value; + datumHash?: DigestBlake2B256; + datum?: Datum; + script?: Script; +}[]; +export type EvaluateTransactionFailure = EvaluateTransactionFailureIncompatibleEra | EvaluateTransactionFailureUnsupportedEra | EvaluateTransactionFailureOverlappingAdditionalUtxo | EvaluateTransactionFailureNodeTipTooOld | EvaluateTransactionFailureCannotCreateEvaluationContext | EvaluateTransactionFailureScriptExecutionFailure; +export type ScriptExecutionFailure = ScriptExecutionFailureMissingScripts | ScriptExecutionFailureValidationFailure | ScriptExecutionFailureUnsuitableOutputReference | SubmitTransactionFailureExtraneousRedeemers | SubmitTransactionFailureMissingDatums | SubmitTransactionFailureUnknownOutputReferences | SubmitTransactionFailureMissingCostModels | SubmitTransactionFailureInternalLedgerTypeConversionError; +export type SafeZone = number; +export type AnyStakeCredential = Base16 | Bech32 | StakeAddress; +export type Base16 = string; +export type Bech32 = string; +export type StakeAddress = string; +export type EraWithGenesis = "byron" | "shelley" | "alonzo" | "conway"; +export type UtcTime = string; +export type NetworkMagic = number; +export type InitialDelegates = { + issuer: { + id: DigestBlake2B224; + }; + delegate: GenesisDelegate; +}[]; +export interface Ogmios { + FindIntersection: FindIntersection; + FindIntersectionResponse: IntersectionFound | IntersectionNotFound | IntersectionInterleaved; + NextBlock: NextBlock; + NextBlockResponse: NextBlockResponse; + SubmitTransaction: SubmitTransaction; + SubmitTransactionResponse: SubmitTransactionSuccess | SubmitTransactionError | SubmitTransactionDeserialisationError; + EvaluateTransaction: EvaluateTransaction; + EvaluateTransactionResponse: EvaluateTransactionSuccess | EvaluateTransactionError | EvaluateTransactionDeserialisationError; + AcquireLedgerState: AcquireLedgerState; + AcquireLedgerStateFailure?: AcquireLedgerStateFailure; + AcquireLedgerStateResponse: AcquireLedgerStateSuccess | AcquireLedgerStateFailure; + ReleaseLedgerState: ReleaseLedgerState; + ReleaseLedgerStateResponse: ReleaseLedgerStateResponse; + QueryLedgerStateEraMismatch?: QueryLedgerStateEraMismatch; + QueryLedgerStateUnavailableInCurrentEra?: QueryLedgerStateUnavailableInCurrentEra; + QueryLedgerStateAcquiredExpire?: QueryLedgerStateAcquiredExpired; + QueryLedgerStateEpoch: QueryLedgerStateEpoch; + QueryLedgerStateEpochResponse: QueryLedgerStateEpochResponse | QueryLedgerStateEraMismatch | QueryLedgerStateUnavailableInCurrentEra | QueryLedgerStateAcquiredExpired; + QueryLedgerStateEraStart: QueryLedgerStateEraStart; + QueryLedgerStateEraStartResponse: QueryLedgerStateEraStartResponse | QueryLedgerStateEraMismatch | QueryLedgerStateUnavailableInCurrentEra | QueryLedgerStateAcquiredExpired; + QueryLedgerStateEraSummaries: QueryLedgerStateEraSummaries; + QueryLedgerStateEraSummariesResponse: QueryLedgerStateEraSummariesResponse | QueryLedgerStateEraMismatch | QueryLedgerStateUnavailableInCurrentEra | QueryLedgerStateAcquiredExpired; + QueryLedgerStateLiveStakeDistribution: QueryLedgerStateLiveStakeDistribution; + QueryLedgerStateLiveStakeDistributionResponse: QueryLedgerStateLiveStakeDistributionResponse | QueryLedgerStateEraMismatch | QueryLedgerStateUnavailableInCurrentEra | QueryLedgerStateAcquiredExpired; + QueryLedgerStateProjectedRewards: QueryLedgerStateProjectedRewards; + QueryLedgerStateProjectedRewardsResponse: QueryLedgerStateProjectedRewardsResponse | QueryLedgerStateEraMismatch | QueryLedgerStateUnavailableInCurrentEra | QueryLedgerStateAcquiredExpired; + QueryLedgerStateProposedProtocolParameters: QueryLedgerStateProposedProtocolParameters; + QueryLedgerStateProposedProtocolParametersResponse: QueryLedgerStateProposedProtocolParametersResponse | QueryLedgerStateEraMismatch | QueryLedgerStateUnavailableInCurrentEra | QueryLedgerStateAcquiredExpired; + QueryLedgerStateProtocolParameters: QueryLedgerStateProtocolParameters; + QueryLedgerStateProtocolParametersResponse: QueryLedgerStateProtocolParametersResponse | QueryLedgerStateEraMismatch | QueryLedgerStateUnavailableInCurrentEra | QueryLedgerStateAcquiredExpired; + QueryLedgerStateRewardAccountSummaries: QueryLedgerStateRewardAccountSummaries; + QueryLedgerStateRewardAccountSummariesResponse: QueryLedgerStateRewardAccountSummariesResponse | QueryLedgerStateEraMismatch | QueryLedgerStateUnavailableInCurrentEra | QueryLedgerStateAcquiredExpired; + QueryLedgerStateRewardsProvenance: QueryLedgerStateRewardsProvenance; + QueryLedgerStateRewardsProvenanceResponse: QueryLedgerStateRewardsProvenanceResponse | QueryLedgerStateEraMismatch | QueryLedgerStateUnavailableInCurrentEra | QueryLedgerStateAcquiredExpired; + QueryLedgerStateStakePools: QueryLedgerStateStakePools; + QueryLedgerStateStakePoolsResponse: QueryLedgerStateStakePoolsResponse | QueryLedgerStateEraMismatch | QueryLedgerStateUnavailableInCurrentEra | QueryLedgerStateAcquiredExpired; + QueryLedgerStateTip: QueryLedgerStateTip; + QueryLedgerStateTipResponse: QueryLedgerStateTipResponse | QueryLedgerStateEraMismatch | QueryLedgerStateUnavailableInCurrentEra | QueryLedgerStateAcquiredExpired; + QueryLedgerStateUtxo: QueryLedgerStateUtxo; + QueryLedgerStateUtxoResponse: QueryLedgerStateUtxoResponse | QueryLedgerStateEraMismatch | QueryLedgerStateUnavailableInCurrentEra | QueryLedgerStateAcquiredExpired; + QueryNetworkBlockHeight: QueryNetworkBlockHeight; + QueryNetworkBlockHeightResponse: QueryNetworkBlockHeightResponse; + QueryNetworkGenesisConfiguration: QueryNetworkGenesisConfiguration; + QueryNetworkGenesisConfigurationResponse: QueryNetworkGenesisConfigurationResponse; + QueryNetworkStartTime: QueryNetworkStartTime; + QueryNetworkStartTimeResponse: QueryNetworkStartTimeResponse; + QueryNetworkTip: QueryNetworkTip; + QueryNetworkTipResponse: QueryNetworkTipResponse; + AcquireMempool: AcquireMempool; + AcquireMempoolResponse: AcquireMempoolResponse; + NextTransaction: NextTransaction; + MustAcquireMempoolFirst?: MustAcquireMempoolFirst; + NextTransactionResponse: NextTransactionResponse | MustAcquireMempoolFirst; + HasTransaction: HasTransaction; + HasTransactionResponse: HasTransactionResponse | MustAcquireMempoolFirst; + SizeOfMempool: SizeOfMempool; + SizeOfMempoolResponse?: SizeOfMempoolResponse | MustAcquireMempoolFirst; + ReleaseMempool: ReleaseMempool; + ReleaseMempoolResponse: ReleaseMempoolResponse | MustAcquireMempoolFirst; + RpcError: RpcError; +} +export interface FindIntersection { + jsonrpc: "2.0"; + method: "findIntersection"; + params: { + points?: PointOrOrigin[]; + }; + id?: unknown; +} +export interface Point { + slot: Slot; + id: DigestBlake2B256; +} +export interface IntersectionFound { + jsonrpc: "2.0"; + method: "findIntersection"; + result: { + intersection: PointOrOrigin; + tip: TipOrOrigin; + }; + id?: unknown; +} +export interface Tip { + slot: Slot; + id: DigestBlake2B256; + height: BlockHeight; +} +export interface IntersectionNotFound { + jsonrpc: "2.0"; + method: "findIntersection"; + error: { + code: 1000; + message: string; + data: { + tip: TipOrOrigin; + }; + }; + id?: unknown; +} +export interface IntersectionInterleaved { + jsonrpc: "2.0"; + method: "findIntersection"; + error: { + code: 1001; + message: string; + }; + id?: unknown; +} +export interface NextBlock { + jsonrpc: "2.0"; + method: "nextBlock"; + id?: unknown; +} +export interface NextBlockResponse { + jsonrpc: "2.0"; + method: "nextBlock"; + result: RollForward | RollBackward; + id?: unknown; +} +export interface RollForward { + direction: "forward"; + tip: Tip; + block: Block; +} +export interface BlockEBB { + type: "ebb"; + era: "byron"; + id: DigestBlake2B256; + ancestor: DigestBlake2B256; + height: BlockHeight; +} +export interface BlockBFT { + type: "bft"; + era: "byron"; + id: DigestBlake2B256; + ancestor: DigestBlake2B256; + height: BlockHeight; + slot: Slot; + size: { + bytes: Int64; + }; + transactions?: Transaction[]; + operationalCertificates?: BootstrapOperationalCertificate[]; + protocol: { + id: BootstrapProtocolId; + version: ProtocolVersion; + software: SoftwareVersion; + update?: BootstrapProtocolUpdate; + }; + issuer: { + verificationKey: ExtendedVerificationKey; + }; + delegate: { + verificationKey: ExtendedVerificationKey; + }; +} +export interface Transaction { + id: DigestBlake2B256; + spends: "inputs" | "collaterals"; + inputs: TransactionOutputReference[]; + references?: TransactionOutputReference[]; + collaterals?: TransactionOutputReference[]; + totalCollateral?: Lovelace; + collateralReturn?: TransactionOutput; + outputs: TransactionOutput[]; + certificates?: Certificate[]; + withdrawals?: Withdrawals; + fee?: Lovelace; + validityInterval?: ValidityInterval; + mint?: Assets; + network?: Network; + scriptIntegrityHash?: DigestBlake2B256; + requiredExtraSignatories?: DigestBlake2B224[]; + requiredExtraScripts?: DigestBlake2B224[]; + proposals?: GovernanceProposal[]; + votes?: GovernanceVote[]; + metadata?: Metadata; + signatories: Signatory[]; + scripts?: { + [k: string]: Script; + }; + datums?: { + [k: string]: Datum; + }; + redeemers?: { + [k: string]: Redeemer; + }; + cbor?: string; +} +export interface TransactionOutputReference { + transaction: { + id: TransactionId; + }; + index: UInt32; +} +export interface Lovelace { + lovelace: bigint; +} +export interface TransactionOutput { + address: Address; + value: Value; + datumHash?: DigestBlake2B256; + datum?: Datum; + script?: Script; +} +export interface Value { + ada: { + lovelace: bigint; + }; + [k: string]: { + [k: string]: AssetQuantity; + }; +} +export interface Native { + language: "native"; + json: ScriptNative; + cbor?: string; +} +export interface ClauseSignature { + clause: "signature"; + from: DigestBlake2B224; +} +export interface ClauseAny { + clause: "any"; + from: ScriptNative[]; +} +export interface ClauseAll { + clause: "all"; + from: ScriptNative[]; +} +export interface ClauseSome { + clause: "some"; + atLeast: bigint; + from: ScriptNative[]; +} +export interface ClauseBefore { + clause: "before"; + slot: Slot; +} +export interface ClauseAfter { + clause: "after"; + slot: Slot; +} +export interface Plutus { + language: "plutus:v1" | "plutus:v2" | "plutus:v3"; + cbor: string; +} +export interface StakeDelegation { + type: "stakeDelegation"; + credential: DigestBlake2B224; + stakePool?: { + id: StakePoolId; + }; + delegateRepresentative?: DelegateRepresentative; +} +export interface DelegateRepresentativeRegistered { + id: DigestBlake2B224; + type: "registered"; +} +export interface DelegateRepresentativeNoConfidence { + type: "noConfidence"; +} +export interface DelegateRepresentativeAbstain { + type: "abstain"; +} +export interface StakeCredentialRegistration { + type: "stakeCredentialRegistration"; + credential: DigestBlake2B224; + deposit?: Lovelace; +} +export interface StakeCredentialDeregistration { + type: "stakeCredentialDeregistration"; + credential: DigestBlake2B224; + deposit?: Lovelace; +} +export interface StakePoolRegistration { + type: "stakePoolRegistration"; + stakePool: StakePool; +} +export interface StakePool { + id: StakePoolId; + vrfVerificationKeyHash: DigestBlake2B256; + owners: DigestBlake2B224[]; + cost: Lovelace; + margin: Ratio; + pledge: Lovelace; + rewardAccount: RewardAccount; + metadata?: Anchor; + relays: Relay[]; +} +export interface Anchor { + hash: DigestAny; + url: string; +} +export interface RelayByAddress { + type: "ipAddress"; + ipv4?: string; + ipv6?: string; + port?: number; +} +export interface RelayByName { + type: "hostname"; + hostname: string; + port?: number; +} +export interface StakePoolRetirement { + type: "stakePoolRetirement"; + stakePool: { + retirementEpoch: Epoch; + id: StakePoolId; + }; +} +export interface GenesisDelegation { + type: "genesisDelegation"; + delegate: { + id: DigestBlake2B224; + }; + issuer: { + id: DigestBlake2B224; + vrfVerificationKeyHash: DigestBlake2B256; + }; +} +export interface ConstitutionalCommitteeHotKeyRegistration { + type: "constitutionalCommitteeHotKeyRegistration"; + member: { + id: DigestBlake2B224; + }; + hotKey: DigestBlake2B224; +} +export interface ConstitutionalCommitteeRetirement { + type: "constitutionalCommitteeRetirement"; + member: { + id: DigestBlake2B224; + }; + anchor?: Anchor; +} +export interface DelegateRepresentativeRegistration { + type: "delegateRepresentativeRegistration"; + delegateRepresentative: DelegateRepresentative; + deposit: Lovelace; + anchor?: Anchor; +} +export interface DelegateRepresentativeUpdate { + type: "delegateRepresentativeUpdate"; + delegateRepresentative: DelegateRepresentative; + anchor: None | Anchor; +} +export interface DelegateRepresentativeRetirement { + type: "delegateRepresentativeRetirement"; + delegateRepresentative: DelegateRepresentative; + deposit: Lovelace; +} +export interface Withdrawals { + [k: string]: Lovelace; +} +export interface ValidityInterval { + invalidBefore?: Slot; + invalidAfter?: Slot; +} +export interface Assets { + [k: string]: { + [k: string]: AssetQuantity; + }; +} +export interface GovernanceProposal { + deposit?: Lovelace; + returnAccount?: RewardAccount; + anchor?: Anchor; + action: GovernanceActionProtocolParametersUpdate | GovernanceActionHardForkInitiation | GovernanceActionTreasuryTransfer | GovernanceActionTreasuryWithdrawals | GovernanceActionConstitutionalCommittee | GovernanceActionConstitution | GovernanceActionNoConfidence | GovernanceActionInformation; +} +export interface GovernanceActionProtocolParametersUpdate { + type: "protocolParametersUpdate"; + parameters: ProposedProtocolParameters; +} +export interface ProposedProtocolParameters { + minFeeCoefficient?: UInt64; + minFeeConstant?: Lovelace; + minUtxoDepositCoefficient?: UInt64; + minUtxoDepositConstant?: Lovelace; + maxBlockBodySize?: { + bytes: Int64; + }; + maxBlockHeaderSize?: { + bytes: Int64; + }; + maxTransactionSize?: { + bytes: Int64; + }; + maxValueSize?: { + bytes: Int64; + }; + extraEntropy?: Nonce; + stakeCredentialDeposit?: Lovelace; + stakePoolDeposit?: Lovelace; + stakePoolRetirementEpochBound?: UInt64; + stakePoolPledgeInfluence?: Ratio; + minStakePoolCost?: Lovelace; + desiredNumberOfStakePools?: UInt64; + federatedBlockProductionRatio?: Ratio; + monetaryExpansion?: Ratio; + treasuryExpansion?: Ratio; + collateralPercentage?: UInt64; + maxCollateralInputs?: UInt64; + plutusCostModels?: CostModels; + scriptExecutionPrices?: ScriptExecutionPrices; + maxExecutionUnitsPerTransaction?: ExecutionUnits; + maxExecutionUnitsPerBlock?: ExecutionUnits; + stakePoolVotingThresholds?: StakePoolVotingThresholds; + constitutionalCommitteeMinSize?: UInt64; + constitutionalCommitteeMaxTermLength?: UInt64; + governanceActionLifetime?: Epoch; + governanceActionDeposit?: Lovelace; + delegateRepresentativeVotingThresholds?: DelegateRepresentativeVotingThresholds; + delegateRepresentativeDeposit?: Lovelace; + delegateRepresentativeMaxIdleTime?: Epoch; + version?: ProtocolVersion; +} +export interface CostModels { + [k: string]: CostModel; +} +export interface ScriptExecutionPrices { + memory: Ratio; + cpu: Ratio; +} +export interface ExecutionUnits { + memory: UInt64; + cpu: UInt64; +} +export interface StakePoolVotingThresholds { + noConfidence: Ratio; + constitutionalCommittee: { + default: Ratio; + stateOfNoConfidence: Ratio; + }; + hardForkInitiation: Ratio; +} +export interface DelegateRepresentativeVotingThresholds { + noConfidence: Ratio; + constitution: Ratio; + constitutionalCommittee: { + default: Ratio; + stateOfNoConfidence: Ratio; + }; + hardForkInitiation: Ratio; + protocolParametersUpdate: { + network: Ratio; + economic: Ratio; + technical: Ratio; + governance: Ratio; + }; + treasuryWithdrawals: Ratio; +} +export interface ProtocolVersion { + major: UInt32; + minor: UInt32; + patch?: UInt32; +} +export interface GovernanceActionHardForkInitiation { + type: "hardForkInitiation"; + version: ProtocolVersion; +} +export interface GovernanceActionTreasuryTransfer { + type: "treasuryTransfer"; + source: "reserves" | "treasury"; + target: "reserves" | "treasury"; + value: Lovelace; +} +export interface GovernanceActionTreasuryWithdrawals { + type: "treasuryWithdrawals"; + withdrawals: RewardTransfer; +} +export interface RewardTransfer { + [k: string]: LovelaceDelta; +} +export interface LovelaceDelta { + lovelace: number; +} +export interface GovernanceActionConstitutionalCommittee { + type: "constitutionalCommittee"; + members: { + added: ConstitutionalCommitteeMember[]; + removed: { + id: DigestBlake2B224; + }[]; + }; + quorum: Ratio; +} +export interface ConstitutionalCommitteeMember { + id: DigestBlake2B224; + mandate: { + epoch: Epoch; + }; +} +export interface GovernanceActionConstitution { + type: "constitution"; + hash?: DigestBlake2B224; + anchor: Anchor; +} +export interface GovernanceActionNoConfidence { + type: "noConfidence"; +} +export interface GovernanceActionInformation { + type: "information"; +} +export interface GovernanceVote { + issuer: VoterGenesisDelegate | VoterConstitutionalCommittee | VoterDelegateRepresentative | VoterStakePoolOperator; + anchor?: Anchor; + vote: "yes" | "no" | "abstain"; + proposal?: GovernanceProposalReference; +} +export interface VoterGenesisDelegate { + role: "genesisDelegate"; + id: DigestBlake2B224; +} +export interface VoterConstitutionalCommittee { + role: "constitutionalCommittee"; + id: DigestBlake2B224; +} +export interface VoterDelegateRepresentative { + role: "delegateRepresentative"; + id: DigestBlake2B224; +} +export interface VoterStakePoolOperator { + role: "stakePoolOperator"; + id: StakePoolId; +} +export interface GovernanceProposalReference { + transaction: { + id: TransactionId; + }; + index: UInt32; +} +export interface Metadata { + hash: DigestBlake2B256; + labels: MetadataLabels; +} +export interface MetadataLabels { + [k: string]: { + cbor?: string; + json?: Metadatum; + }; +} +export interface ObjectMetadatum { + [k: string]: Metadatum; +} +export interface Signatory { + key: VerificationKey; + signature: Signature; + chainCode?: ChainCode; + addressAttributes?: AddressAttributes; +} +export interface Redeemer { + redeemer: RedeemerData; + executionUnits: ExecutionUnits; +} +export interface BootstrapOperationalCertificate { + issuer: { + verificationKey: VerificationKey; + }; + delegate: { + verificationKey: VerificationKey; + }; +} +export interface SoftwareVersion { + appName: string; + number: UInt32; +} +export interface BootstrapProtocolUpdate { + proposal?: { + version: ProtocolVersion; + software: SoftwareVersion; + parameters: BootstrapProtocolParameters; + metadata: { + [k: string]: string; + }; + }; + votes: BootstrapVote[]; +} +export interface BootstrapProtocolParameters { + heavyDelegationThreshold?: Ratio; + maxBlockBodySize?: { + bytes: Int64; + }; + maxBlockHeaderSize?: { + bytes: Int64; + }; + maxUpdateProposalSize?: { + bytes: Int64; + }; + maxTransactionSize?: { + bytes: Int64; + }; + multiPartyComputationThreshold?: Ratio; + scriptVersion?: UInt64; + slotDuration?: UInt64; + unlockStakeEpoch?: UInt64; + updateProposalThreshold?: Ratio; + updateProposalTimeToLive?: UInt64; + updateVoteThreshold?: Ratio; + softForkInitThreshold?: Ratio; + softForkMinThreshold?: Ratio; + softForkDecrementThreshold?: Ratio; + minFeeCoefficient?: UInt64; + minFeeConstant?: Lovelace; +} +export interface BootstrapVote { + voter: { + verificationKey: VerificationKey; + }; + proposal: { + id: DigestBlake2B256; + }; +} +export interface BlockPraos { + type: "praos"; + era: "shelley" | "allegra" | "mary" | "alonzo" | "babbage"; + id: DigestBlake2B256; + ancestor: DigestBlake2B256 | GenesisHash; + nonce?: CertifiedVrf; + height: BlockHeight; + size: { + bytes: Int64; + }; + slot: Slot; + transactions?: Transaction[]; + protocol: { + version: ProtocolVersion; + }; + issuer: { + verificationKey: VerificationKey; + vrfVerificationKey: VerificationKey; + operationalCertificate: OperationalCertificate; + leaderValue: CertifiedVrf; + }; +} +export interface CertifiedVrf { + proof?: VrfProof; + output?: VrfOutput; +} +export interface OperationalCertificate { + count: UInt64; + kes: { + period: UInt64; + verificationKey: KesVerificationKey; + }; +} +export interface RollBackward { + direction: "backward"; + tip: TipOrOrigin; + point: PointOrOrigin; +} +export interface SubmitTransaction { + jsonrpc: "2.0"; + method: "submitTransaction"; + params: { + transaction: { + cbor: string; + }; + }; + id?: unknown; +} +export interface SubmitTransactionSuccess { + jsonrpc: "2.0"; + method: "submitTransaction"; + result: { + transaction: { + id: TransactionId; + }; + }; + id?: unknown; +} +export interface SubmitTransactionError { + jsonrpc: "2.0"; + method: "submitTransaction"; + error: SubmitTransactionFailure; + id?: unknown; +} +export interface SubmitTransactionFailureEraMismatch { + code: 3005; + message: string; + data: EraMismatch; +} +export interface EraMismatch { + queryEra: Era; + ledgerEra: Era; +} +export interface SubmitTransactionFailureInvalidSignatories { + code: 3100; + message: string; + data: { + invalidSignatories: VerificationKey[]; + }; +} +export interface SubmitTransactionFailureMissingSignatories { + code: 3101; + message: string; + data: { + missingSignatories: DigestBlake2B224[]; + }; +} +export interface SubmitTransactionFailureMissingScripts { + code: 3102; + message: string; + data: { + missingScripts: DigestBlake2B224[]; + }; +} +export interface SubmitTransactionFailureFailingNativeScript { + code: 3103; + message: string; + data: { + failingNativeScripts: DigestBlake2B224[]; + }; +} +export interface SubmitTransactionFailureExtraneousScripts { + code: 3104; + message: string; + data: { + extraneousScripts: DigestBlake2B224[]; + }; +} +export interface SubmitTransactionFailureMissingMetadataHash { + code: 3105; + message: string; + data: { + metadata: { + hash: DigestBlake2B256; + }; + }; +} +export interface SubmitTransactionFailureMissingMetadata { + code: 3106; + message: string; + data: { + metadata: { + hash: DigestBlake2B256; + }; + }; +} +export interface SubmitTransactionFailureMetadataHashMismatch { + code: 3107; + message: string; + data: { + provided: { + hash: DigestBlake2B256; + }; + computed: { + hash: DigestBlake2B256; + }; + }; +} +export interface SubmitTransactionFailureInvalidMetadata { + code: 3108; + message: string; +} +export interface SubmitTransactionFailureMissingRedeemers { + code: 3109; + message: string; + data: { + missingRedeemers: ScriptPurpose[]; + }; +} +export interface ScriptPurposeSpend { + purpose: "spend"; + outputReference: TransactionOutputReference; +} +export interface ScriptPurposeMint { + purpose: "mint"; + policy: PolicyId; +} +export interface ScriptPurposePublish { + purpose: "publish"; + certificate: Certificate; +} +export interface ScriptPurposeWithdraw { + purpose: "withdraw"; + rewardAccount: RewardAccount; +} +export interface SubmitTransactionFailureExtraneousRedeemers { + code: 3110; + message: string; + data: { + extraneousRedeemers: RedeemerPointer[]; + }; +} +export interface SubmitTransactionFailureMissingDatums { + code: 3111; + message: string; + data: { + missingDatums: DigestBlake2B256[]; + }; +} +export interface SubmitTransactionFailureExtraneousDatums { + code: 3112; + message: string; + data: { + extraneousDatums: DigestBlake2B256[]; + }; +} +export interface SubmitTransactionFailureScriptIntegrityHashMismatch { + code: 3113; + message: string; + data: { + providedScriptIntegrity: DigestBlake2B256 | null; + computedScriptIntegrity: DigestBlake2B256 | null; + }; +} +export interface SubmitTransactionFailureOrphanScriptInputs { + code: 3114; + message: string; + data: { + orphanInputs?: TransactionOutputReference[]; + }; +} +export interface SubmitTransactionFailureMissingCostModels { + code: 3115; + message: string; + data: { + missingCostModels: Language[]; + }; +} +export interface SubmitTransactionFailureMalformedScripts { + code: 3116; + message: string; + data: { + malformedScripts: DigestBlake2B224[]; + }; +} +export interface SubmitTransactionFailureUnknownOutputReferences { + code: 3117; + message: string; + data: { + unknownOutputReferences: TransactionOutputReference[]; + }; +} +export interface SubmitTransactionFailureOutsideOfValidityInterval { + code: 3118; + message: string; + data: { + validityInterval: ValidityInterval; + currentSlot: Slot; + }; +} +export interface SubmitTransactionFailureTransactionTooLarge { + code: 3119; + message: string; + data: { + measuredTransactionSize: { + bytes: Int64; + }; + maximumTransactionSize: { + bytes: Int64; + }; + }; +} +export interface SubmitTransactionFailureValueTooLarge { + code: 3120; + message: string; + data: { + excessivelyLargeOutputs: TransactionOutput[]; + }; +} +export interface SubmitTransactionFailureEmptyInputSet { + code: 3121; + message: string; +} +export interface SubmitTransactionFailureTransactionFeeTooSmall { + code: 3122; + message: string; + data: { + minimumRequiredFee: Lovelace; + providedFee: Lovelace; + }; +} +export interface SubmitTransactionFailureValueNotConserved { + code: 3123; + message: string; + data: { + valueConsumed: Value; + valueProduced: Value; + }; +} +export interface SubmitTransactionFailureNetworkMismatch { + code: 3124; + message: string; + data: { + expectedNetwork: Network; + discriminatedType: "address"; + invalidEntities: Address[]; + } | { + expectedNetwork: Network; + discriminatedType: "rewardAccount"; + invalidEntities: RewardAccount[]; + } | { + expectedNetwork: Network; + discriminatedType: "stakePoolCertificate"; + invalidEntities: StakePoolId[]; + } | { + expectedNetwork: Network; + discriminatedType: "transaction"; + }; +} +export interface SubmitTransactionFailureInsufficientlyFundedOutputs { + code: 3125; + message: string; + data: { + insufficientlyFundedOutputs: { + output: TransactionOutput; + minimumRequiredValue?: Lovelace; + }[]; + }; +} +export interface SubmitTransactionFailureBootstrapAttributesTooLarge { + code: 3126; + message: string; + data: { + bootstrapOutputs: TransactionOutput[]; + }; +} +export interface SubmitTransactionFailureMintingOrBurningAda { + code: 3127; + message: string; +} +export interface SubmitTransactionFailureInsufficientCollateral { + code: 3128; + message: string; + data: { + providedCollateral: Lovelace; + minimumRequiredCollateral: Lovelace; + }; +} +export interface SubmitTransactionFailureCollateralLockedByScript { + code: 3129; + message: string; + data: { + unsuitableCollateralInputs: TransactionOutputReference[]; + }; +} +export interface SubmitTransactionFailureUnforeseeableSlot { + code: 3130; + message: string; + data: { + unforeseeableSlot: Slot; + }; +} +export interface SubmitTransactionFailureTooManyCollateralInputs { + code: 3131; + message: string; + data: { + maximumCollateralInputs: UInt32; + countedCollateralInputs: UInt32; + }; +} +export interface SubmitTransactionFailureMissingCollateralInputs { + code: 3132; + message: string; +} +export interface SubmitTransactionFailureNonAdaCollateral { + code: 3133; + message: string; + data: { + unsuitableCollateralValue: Value; + }; +} +export interface SubmitTransactionFailureExecutionUnitsTooLarge { + code: 3134; + message: string; + data: { + providedExecutionUnits: ExecutionUnits; + maximumExecutionUnits: ExecutionUnits; + }; +} +export interface SubmitTransactionFailureTotalCollateralMismatch { + code: 3135; + message: string; + data: { + declaredTotalCollateral: Lovelace; + computedTotalCollateral: Lovelace; + }; +} +export interface SubmitTransactionFailureSpendsMismatch { + code: 3136; + message: string; + data: { + declaredSpending?: "inputs" | "collaterals"; + mismatchReason: string; + }; +} +export interface SubmitTransactionFailureUnauthorizedVotes { + code: 3137; + message: string; + data: { + unauthorizedVotes: { + proposal: GovernanceProposalReference; + voter: VoterGenesisDelegate | VoterConstitutionalCommittee | VoterDelegateRepresentative | VoterStakePoolOperator; + }[]; + }; +} +export interface SubmitTransactionFailureUnknownGovernanceProposals { + code: 3138; + message: string; + data: { + unknownProposals: GovernanceProposalReference[]; + }; +} +export interface SubmitTransactionFailureInvalidProtocolParametersUpdate { + code: 3139; + message: string; +} +export interface SubmitTransactionFailureUnknownStakePool { + code: 3140; + message: string; + data: { + unknownStakePool: StakePoolId; + }; +} +export interface SubmitTransactionFailureIncompleteWithdrawals { + code: 3141; + message: string; + data: { + incompleteWithdrawals: Withdrawals; + }; +} +export interface SubmitTransactionFailureRetirementTooLate { + code: 3142; + message: string; + data: { + currentEpoch: Epoch; + declaredEpoch: Epoch; + firstInvalidEpoch: Epoch; + }; +} +export interface SubmitTransactionFailureStakePoolCostTooLow { + code: 3143; + message: string; + data: { + minimumStakePoolCost: Lovelace; + declaredStakePoolCost: Lovelace; + }; +} +export interface SubmitTransactionFailureMetadataHashTooLarge { + code: 3144; + message: string; + data: { + infringingStakePool: { + id: StakePoolId; + }; + computedMetadataHashSize: { + bytes: Int64; + }; + }; +} +export interface SubmitTransactionFailureCredentialAlreadyRegistered { + code: 3145; + message: string; + data: { + knownCredential: DigestBlake2B224; + }; +} +export interface SubmitTransactionFailureUnknownCredential { + code: 3146; + message: string; + data: { + unknownCredential: DigestBlake2B224; + }; +} +export interface SubmitTransactionFailureNonEmptyRewardAccount { + code: 3147; + message: string; + data: { + nonEmptyRewardAccountBalance: Lovelace; + }; +} +export interface SubmitTransactionFailureInvalidGenesisDelegation { + code: 3148; + message: string; +} +export interface SubmitTransactionFailureInvalidMIRTransfer { + code: 3149; + message: string; +} +export interface SubmitTransactionFailureForbiddenWithdrawal { + code: 3150; + message: string; + data: { + marginalizedCredentials: DigestBlake2B224[]; + }; +} +export interface SubmitTransactionFailureCredentialDepositMismatch { + code: 3151; + message: string; + data: { + providedDeposit: Lovelace; + expectedDeposit?: Lovelace; + }; +} +export interface SubmitTransactionFailureDRepAlreadyRegistered { + code: 3152; + message: string; + data: { + knownDelegateRepresentative: DelegateRepresentative; + }; +} +export interface SubmitTransactionFailureDRepNotRegistered { + code: 3153; + message: string; + data: { + unknownDelegateRepresentative: DelegateRepresentative; + }; +} +export interface SubmitTransactionFailureUnknownConstitutionalCommitteeMember { + code: 3154; + message: string; + data: { + unknownConstitutionalCommitteeMember: { + id: DigestBlake2B224; + }; + }; +} +export interface SubmitTransactionFailureGovernanceProposalDepositMismatch { + code: 3155; + message: string; + data: { + providedDeposit: Lovelace; + expectedDeposit: Lovelace; + }; +} +export interface SubmitTransactionFailureConflictingCommitteeUpdate { + code: 3156; + message: string; + data: { + conflictingMembers: { + id: DigestBlake2B224; + }[]; + }; +} +export interface SubmitTransactionFailureInvalidCommitteeUpdate { + code: 3157; + message: string; + data: { + alreadyRetiredMembers: { + id: DigestBlake2B224; + }; + }; +} +export interface SubmitTransactionFailureTreasuryWithdrawalMismatch { + code: 3158; + message: string; + data: { + providedWithdrawal: Lovelace; + expectedWithdrawal?: Lovelace; + }; +} +export interface SubmitTransactionFailureInvalidOrMissingPreviousProposals { + code: 3159; + message: string; + data: { + invalidOrMissingPreviousProposals: { + anchor: Anchor; + type: "hardForkInitiation" | "protocolParametersUpdate" | "constitutionalCommittee" | "constitution"; + invalidPreviousProposal?: GovernanceProposalReference; + }[]; + }; +} +export interface SubmitTransactionFailureUnrecognizedCertificateType { + code: 3998; + message: string; +} +export interface SubmitTransactionFailureInternalLedgerTypeConversionError { + code: 3999; + message: string; +} +export interface SubmitTransactionDeserialisationError { + jsonrpc: "2.0"; + method: "submitTransaction"; + error: DeserialisationFailure; + id?: unknown; +} +export interface DeserialisationFailure { + code: -32602; + message: string; + data: { + shelley: string; + allegra: string; + mary: string; + alonzo: string; + babbage: string; + conway: string; + }; +} +export interface EvaluateTransaction { + jsonrpc: "2.0"; + method: "evaluateTransaction"; + params: { + transaction: { + cbor: string; + }; + additionalUtxo?: Utxo; + }; + id?: unknown; +} +export interface EvaluateTransactionSuccess { + jsonrpc: "2.0"; + method: "evaluateTransaction"; + result: { + validator: RedeemerPointer; + budget: ExecutionUnits; + }[]; + id?: unknown; +} +export interface EvaluateTransactionError { + jsonrpc: "2.0"; + method: "evaluateTransaction"; + error: EvaluateTransactionFailure; + id?: unknown; +} +export interface EvaluateTransactionFailureIncompatibleEra { + code: 3000; + message: string; + data: { + incompatibleEra: Era; + }; +} +export interface EvaluateTransactionFailureUnsupportedEra { + code: 3001; + message: string; + data: { + unsupportedEra: Era; + }; +} +export interface EvaluateTransactionFailureOverlappingAdditionalUtxo { + code: 3002; + message: string; + data: { + overlappingOutputReferences: TransactionOutputReference[]; + }; +} +export interface EvaluateTransactionFailureNodeTipTooOld { + code: 3003; + message: string; + data: { + minimumRequiredEra: Era; + currentNodeEra: Era; + }; +} +export interface EvaluateTransactionFailureCannotCreateEvaluationContext { + code: 3004; + message: string; + data: { + reason: string; + }; +} +export interface EvaluateTransactionFailureScriptExecutionFailure { + code: 3010; + message: string; + data: { + validator: RedeemerPointer; + error: ScriptExecutionFailure; + }[]; +} +export interface ScriptExecutionFailureMissingScripts { + code: 3011; + message: string; + data: { + missingScripts: RedeemerPointer[]; + }; +} +export interface ScriptExecutionFailureValidationFailure { + code: 3012; + message: string; + data: { + validationError: string; + traces: string[]; + }; +} +export interface ScriptExecutionFailureUnsuitableOutputReference { + code: 3013; + message: string; + data: { + unsuitableOutputReference: TransactionOutputReference; + }; +} +export interface EvaluateTransactionDeserialisationError { + jsonrpc: "2.0"; + method: "evaluateTransaction"; + error: DeserialisationFailure; + id?: unknown; +} +export interface AcquireLedgerState { + jsonrpc: "2.0"; + method: "acquireLedgerState"; + params: { + point: PointOrOrigin; + }; + id?: unknown; +} +export interface AcquireLedgerStateFailure { + jsonrpc: "2.0"; + method: "acquireLedgerState"; + error: { + code: 2000; + message: string; + data: string; + }; + id?: unknown; +} +export interface AcquireLedgerStateSuccess { + jsonrpc: "2.0"; + method: "acquireLedgerState"; + result: { + acquired: "ledgerState"; + point: PointOrOrigin; + }; + id?: unknown; +} +export interface ReleaseLedgerState { + jsonrpc: "2.0"; + method: "releaseLedgerState"; + id?: unknown; +} +export interface ReleaseLedgerStateResponse { + jsonrpc: "2.0"; + method: "releaseLedgerState"; + result: { + released: "ledgerState"; + }; + id?: unknown; +} +export interface QueryLedgerStateEraMismatch { + jsonrpc: "2.0"; + method: "queryLedgerState/epoch" | "queryLedgerState/eraStart" | "queryLedgerState/eraSummaries" | "queryLedgerState/liveStakeDistribution" | "queryLedgerState/projectedRewards" | "queryLedgerState/protocolParameters" | "queryLedgerState/proposedProtocolParameters" | "queryLedgerState/rewardAccountSummaries" | "queryLedgerState/rewardsProvenance" | "queryLedgerState/stakePools" | "queryLedgerState/utxo" | "queryLedgerState/tip"; + error: { + code: 2001; + message: string; + data: EraMismatch; + }; + id?: unknown; +} +export interface QueryLedgerStateUnavailableInCurrentEra { + jsonrpc: "2.0"; + method: "queryLedgerState/epoch" | "queryLedgerState/eraStart" | "queryLedgerState/eraSummaries" | "queryLedgerState/liveStakeDistribution" | "queryLedgerState/projectedRewards" | "queryLedgerState/protocolParameters" | "queryLedgerState/proposedProtocolParameters" | "queryLedgerState/rewardAccountSummaries" | "queryLedgerState/rewardsProvenance" | "queryLedgerState/stakePools" | "queryLedgerState/utxo" | "queryLedgerState/tip"; + error: { + code: 2002; + message: string; + }; + id?: unknown; +} +export interface QueryLedgerStateAcquiredExpired { + jsonrpc: "2.0"; + method: "queryLedgerState/epoch" | "queryLedgerState/eraStart" | "queryLedgerState/eraSummaries" | "queryLedgerState/liveStakeDistribution" | "queryLedgerState/projectedRewards" | "queryLedgerState/protocolParameters" | "queryLedgerState/proposedProtocolParameters" | "queryLedgerState/rewardAccountSummaries" | "queryLedgerState/rewardsProvenance" | "queryLedgerState/stakePools" | "queryLedgerState/utxo" | "queryLedgerState/tip"; + error: { + code: 2003; + message: string; + data: string; + }; + id?: unknown; +} +export interface QueryLedgerStateEpoch { + jsonrpc: "2.0"; + method: "queryLedgerState/epoch"; + id?: unknown; +} +export interface QueryLedgerStateEpochResponse { + jsonrpc: "2.0"; + method: "queryLedgerState/epoch"; + result: Epoch; + id?: unknown; +} +export interface QueryLedgerStateEraStart { + jsonrpc: "2.0"; + method: "queryLedgerState/eraStart"; + id?: unknown; +} +export interface QueryLedgerStateEraStartResponse { + jsonrpc: "2.0"; + method: "queryLedgerState/eraStart"; + result: Bound; + id?: unknown; +} +export interface Bound { + time: RelativeTime; + slot: Slot; + epoch: Epoch; +} +export interface RelativeTime { + seconds: bigint; +} +export interface QueryLedgerStateEraSummaries { + jsonrpc: "2.0"; + method: "queryLedgerState/eraSummaries"; + id?: unknown; +} +export interface QueryLedgerStateEraSummariesResponse { + jsonrpc: "2.0"; + method: "queryLedgerState/eraSummaries"; + result: EraSummary[]; + id?: unknown; +} +export interface EraSummary { + start: Bound; + end?: Bound; + parameters: EraParameters; +} +export interface EraParameters { + epochLength: Epoch; + slotLength: SlotLength; + safeZone: SafeZone | null; +} +export interface SlotLength { + milliseconds: bigint; +} +export interface QueryLedgerStateLiveStakeDistribution { + jsonrpc: "2.0"; + method: "queryLedgerState/liveStakeDistribution"; + id?: unknown; +} +export interface QueryLedgerStateLiveStakeDistributionResponse { + jsonrpc: "2.0"; + method: "queryLedgerState/liveStakeDistribution"; + result: LiveStakeDistribution; + id?: unknown; +} +export interface LiveStakeDistribution { + [k: string]: { + stake: Ratio; + vrf: DigestBlake2B256; + }; +} +export interface QueryLedgerStateProjectedRewards { + jsonrpc: "2.0"; + method: "queryLedgerState/projectedRewards"; + params: { + stake?: Lovelace[]; + scripts?: AnyStakeCredential[]; + keys?: AnyStakeCredential[]; + }; + id?: unknown; +} +export interface QueryLedgerStateProjectedRewardsResponse { + jsonrpc: "2.0"; + method: "queryLedgerState/projectedRewards"; + result: ProjectedRewards; + id?: unknown; +} +export interface ProjectedRewards { + [k: string]: { + [k: string]: Lovelace; + }; +} +export interface QueryLedgerStateProposedProtocolParameters { + jsonrpc: "2.0"; + method: "queryLedgerState/proposedProtocolParameters"; + id?: unknown; +} +export interface QueryLedgerStateProposedProtocolParametersResponse { + jsonrpc: "2.0"; + method: "queryLedgerState/proposedProtocolParameters"; + result: ProposedProtocolParameters[]; + id?: unknown; +} +export interface QueryLedgerStateProtocolParameters { + jsonrpc: "2.0"; + method: "queryLedgerState/protocolParameters"; + id?: unknown; +} +export interface QueryLedgerStateProtocolParametersResponse { + jsonrpc: "2.0"; + method: "queryLedgerState/protocolParameters"; + result: ProtocolParameters; + id?: unknown; +} +export interface ProtocolParameters { + minFeeCoefficient: UInt64; + minFeeConstant: Lovelace; + minUtxoDepositCoefficient: UInt64; + minUtxoDepositConstant: Lovelace; + maxBlockBodySize: { + bytes: Int64; + }; + maxBlockHeaderSize: { + bytes: Int64; + }; + maxTransactionSize?: { + bytes: Int64; + }; + maxValueSize?: { + bytes: Int64; + }; + extraEntropy?: Nonce; + stakeCredentialDeposit: Lovelace; + stakePoolDeposit: Lovelace; + stakePoolRetirementEpochBound: UInt64; + stakePoolPledgeInfluence: Ratio; + minStakePoolCost: Lovelace; + desiredNumberOfStakePools: UInt64; + federatedBlockProductionRatio?: Ratio; + monetaryExpansion: Ratio; + treasuryExpansion: Ratio; + collateralPercentage?: UInt64; + maxCollateralInputs?: UInt64; + plutusCostModels?: CostModels; + scriptExecutionPrices?: ScriptExecutionPrices; + maxExecutionUnitsPerTransaction?: ExecutionUnits; + maxExecutionUnitsPerBlock?: ExecutionUnits; + stakePoolVotingThresholds?: StakePoolVotingThresholds; + constitutionalCommitteeMinSize?: UInt64; + constitutionalCommitteeMaxTermLength?: UInt64; + governanceActionLifetime?: Epoch; + governanceActionDeposit?: Lovelace; + delegateRepresentativeVotingThresholds?: DelegateRepresentativeVotingThresholds; + delegateRepresentativeDeposit?: Lovelace; + delegateRepresentativeMaxIdleTime?: Epoch; + version: ProtocolVersion; +} +export interface QueryLedgerStateRewardAccountSummaries { + jsonrpc: "2.0"; + method: "queryLedgerState/rewardAccountSummaries"; + params: { + scripts?: AnyStakeCredential[]; + keys?: AnyStakeCredential[]; + }; + id?: unknown; +} +export interface QueryLedgerStateRewardAccountSummariesResponse { + jsonrpc: "2.0"; + method: "queryLedgerState/rewardAccountSummaries"; + result: RewardAccountSummaries; + id?: unknown; +} +export interface RewardAccountSummaries { + [k: string]: RewardAccountSummary; +} +export interface RewardAccountSummary { + delegate?: { + id: StakePoolId; + }; + rewards?: Lovelace; +} +export interface QueryLedgerStateRewardsProvenance { + jsonrpc: "2.0"; + method: "queryLedgerState/rewardsProvenance"; + id?: unknown; +} +export interface QueryLedgerStateRewardsProvenanceResponse { + jsonrpc: "2.0"; + method: "queryLedgerState/rewardsProvenance"; + result: RewardsProvenance; + id?: unknown; +} +export interface RewardsProvenance { + desiredNumberOfStakePools: number; + stakePoolPledgeInfluence: string; + totalRewardsInEpoch: { + lovelace: bigint; + }; + activeStakeInEpoch: { + lovelace: bigint; + }; + stakePools: { + [k: string]: StakePoolSummary; + }; +} +export interface StakePoolSummary { + id: StakePoolId; + stake: Lovelace; + ownerStake: Lovelace; + approximatePerformance: number; + parameters: { + cost: Lovelace; + margin: Ratio; + pledge: Lovelace; + }; +} +export interface QueryLedgerStateStakePools { + jsonrpc: "2.0"; + method: "queryLedgerState/stakePools"; + params?: { + stakePools: { + id: StakePoolId; + }[]; + }; + id?: unknown; +} +export interface QueryLedgerStateStakePoolsResponse { + jsonrpc: "2.0"; + method: "queryLedgerState/stakePools"; + result: { + [k: string]: StakePool; + }; + id?: unknown; +} +export interface QueryLedgerStateTip { + jsonrpc: "2.0"; + method: "queryLedgerState/tip"; + id?: unknown; +} +export interface QueryLedgerStateTipResponse { + jsonrpc: "2.0"; + method: "queryLedgerState/tip"; + result: PointOrOrigin; + id?: unknown; +} +export interface QueryLedgerStateUtxo { + jsonrpc: "2.0"; + method: "queryLedgerState/utxo"; + params?: UtxoByOutputReferences | UtxoByAddresses | WholeUtxo; + id?: unknown; +} +export interface UtxoByOutputReferences { + outputReferences: TransactionOutputReference[]; +} +export interface UtxoByAddresses { + addresses: Address[]; +} +export interface WholeUtxo { +} +export interface QueryLedgerStateUtxoResponse { + jsonrpc: "2.0"; + method: "queryLedgerState/utxo"; + result: Utxo; + id?: unknown; +} +export interface QueryNetworkBlockHeight { + jsonrpc: "2.0"; + method: "queryNetwork/blockHeight"; + id?: unknown; +} +export interface QueryNetworkBlockHeightResponse { + jsonrpc: "2.0"; + method: "queryNetwork/blockHeight"; + result: BlockHeight | Origin; + id?: unknown; +} +export interface QueryNetworkGenesisConfiguration { + jsonrpc: "2.0"; + method: "queryNetwork/genesisConfiguration"; + params: { + era: EraWithGenesis; + }; + id?: unknown; +} +export interface QueryNetworkGenesisConfigurationResponse { + jsonrpc: "2.0"; + method: "queryNetwork/genesisConfiguration"; + result: GenesisByron | GenesisShelley | GenesisAlonzo | GenesisConway; + id?: unknown; +} +export interface GenesisByron { + era: "byron"; + genesisKeyHashes: DigestBlake2B224[]; + genesisDelegations: { + [k: string]: BootstrapOperationalCertificate; + }; + startTime: UtcTime; + initialFunds: { + [k: string]: Lovelace; + }; + initialVouchers: { + [k: string]: Lovelace; + }; + securityParameter: UInt64; + networkMagic: NetworkMagic; + updatableParameters?: ProtocolParameters; +} +export interface GenesisShelley { + era: "shelley"; + startTime: UtcTime; + networkMagic: NetworkMagic; + network: Network; + activeSlotsCoefficient: Ratio; + securityParameter: UInt64; + epochLength: Epoch; + slotsPerKesPeriod: UInt64; + maxKesEvolutions: UInt64; + slotLength: SlotLength; + updateQuorum: UInt64; + maxLovelaceSupply: UInt64; + initialParameters: ProtocolParameters; + initialDelegates: InitialDelegates; + initialFunds: InitialFunds; + initialStakePools: GenesisStakePools; +} +export interface GenesisDelegate { + id: DigestBlake2B224; + vrfVerificationKeyHash: DigestBlake2B256; +} +export interface InitialFunds { + [k: string]: Lovelace; +} +export interface GenesisStakePools { + stakePools: { + [k: string]: StakePool; + }; + delegators: { + [k: string]: StakePoolId; + }; +} +export interface GenesisAlonzo { + era: "alonzo"; + updatableParameters: { + minUtxoDepositCoefficient: UInt64; + collateralPercentage: UInt64; + plutusCostModels: CostModels; + maxCollateralInputs: UInt64; + maxExecutionUnitsPerBlock: ExecutionUnits; + maxExecutionUnitsPerTransaction: ExecutionUnits; + maxValueSize: { + bytes: Int64; + }; + scriptExecutionPrices: ScriptExecutionPrices; + }; +} +export interface GenesisConway { + era: "conway"; + constitution: { + hash?: DigestBlake2B224; + anchor: Anchor; + }; + constitutionalCommittee: { + members: ConstitutionalCommitteeMember[]; + quorum: Ratio; + }; + updatableParameters: { + stakePoolVotingThresholds: StakePoolVotingThresholds; + constitutionalCommitteeMinSize: UInt64; + constitutionalCommitteeMaxTermLength: UInt64; + governanceActionLifetime: Epoch; + governanceActionDeposit: Lovelace; + delegateRepresentativeVotingThresholds: DelegateRepresentativeVotingThresholds; + delegateRepresentativeDeposit: Lovelace; + delegateRepresentativeMaxIdleTime: Epoch; + }; +} +export interface QueryNetworkStartTime { + jsonrpc: "2.0"; + method: "queryNetwork/startTime"; + id?: unknown; +} +export interface QueryNetworkStartTimeResponse { + jsonrpc: "2.0"; + method: "queryNetwork/startTime"; + result: UtcTime; + id?: unknown; +} +export interface QueryNetworkTip { + jsonrpc: "2.0"; + method: "queryNetwork/tip"; + id?: unknown; +} +export interface QueryNetworkTipResponse { + jsonrpc: "2.0"; + method: "queryNetwork/tip"; + result: PointOrOrigin; + id?: unknown; +} +export interface AcquireMempool { + jsonrpc: "2.0"; + method: "acquireMempool"; + id?: unknown; +} +export interface AcquireMempoolResponse { + jsonrpc: "2.0"; + method: "acquireMempool"; + result: { + acquired: "mempool"; + slot: Slot; + }; + id?: unknown; +} +export interface NextTransaction { + jsonrpc: "2.0"; + method: "nextTransaction"; + params?: { + fields?: "all"; + }; + id?: unknown; +} +export interface MustAcquireMempoolFirst { + jsonrpc: "2.0"; + method: "hasTransaction" | "nextTransaction" | "sizeOfMempool" | "releaseMempool"; + error: { + code: 4000; + message: string; + }; + id?: unknown; +} +export interface NextTransactionResponse { + jsonrpc: "2.0"; + method: "nextTransaction"; + result: { + transaction: { + id: TransactionId; + } | Transaction | null; + }; + id?: unknown; +} +export interface HasTransaction { + jsonrpc: "2.0"; + method: "hasTransaction"; + params: { + id: TransactionId; + }; + id?: unknown; +} +export interface HasTransactionResponse { + jsonrpc: "2.0"; + method: "hasTransaction"; + result: boolean; + id?: unknown; +} +export interface SizeOfMempool { + jsonrpc: "2.0"; + method: "sizeOfMempool"; + id?: unknown; +} +export interface SizeOfMempoolResponse { + jsonrpc: "2.0"; + method: "sizeOfMempool"; + result: MempoolSizeAndCapacity; + id?: unknown; +} +export interface MempoolSizeAndCapacity { + maxCapacity: { + bytes: Int64; + }; + currentSize: { + bytes: Int64; + }; + transactions: { + count: UInt32; + }; +} +export interface ReleaseMempool { + jsonrpc: "2.0"; + method: "releaseMempool"; + id?: unknown; +} +export interface ReleaseMempoolResponse { + jsonrpc: "2.0"; + method: "releaseMempool"; + result: { + released: "mempool"; + }; + id?: unknown; +} +export interface RpcError { + jsonrpc: "2.0"; + error: { + code: number; + message?: string; + data?: unknown; + }; + id?: unknown; +} +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/src/translucent/translucent.ts b/src/translucent/translucent.ts index 6cbaf58..3e2c605 100644 --- a/src/translucent/translucent.ts +++ b/src/translucent/translucent.ts @@ -18,6 +18,7 @@ import { OutRef, Payload, PrivateKey, + ProtocolParameters, Provider, RewardAddress, SignedMessage, @@ -47,6 +48,7 @@ export class Translucent { txBuilderConfig!: C.TransactionBuilderConfig; wallet!: AbstractWallet; provider!: Provider; + protocolParams: ProtocolParameters | null = null network: Network = "Mainnet"; utils!: Utils; @@ -109,6 +111,13 @@ export class Translucent { return translucent; } + async getProtocolParameters(): Promise { + if (this.protocolParams === null) { + this.protocolParams = await this.provider.getProtocolParameters(); + } + return this.protocolParams; + } + /** * Switch provider and/or network. * If provider or network unset, no overwriting happens. Provider or network from current instance are taken then. diff --git a/src/translucent/tx.ts b/src/translucent/tx.ts index de9e531..7214410 100644 --- a/src/translucent/tx.ts +++ b/src/translucent/tx.ts @@ -33,7 +33,7 @@ import { toScriptRef, utxoToCore, } from "../utils/mod.ts"; -import { applyDoubleCborEncoding } from "../utils/utils.ts"; +import { applyDoubleCborEncoding, coreToUtxo, toHex } from "../utils/utils.ts"; import { Translucent } from "./translucent.ts"; import { TxComplete } from "./tx_complete.ts"; import { SLOT_CONFIG_NETWORK } from "../plutus/time.ts"; @@ -43,6 +43,216 @@ type ScriptOrRef = | { inlineScript: C.PlutusScript } | { referenceScript: C.PlutusV2Script }; +function utxosEqual(a: C.TransactionUnspentOutput, b: C.TransactionUnspentOutput){ + return a.input().transaction_id().to_hex() == b.input().transaction_id().to_hex() + && a.input().index().to_str() == b.input().index().to_str() +} + +function valueJSToAssets(v: C.ValueJSON): Assets { + const assets: Assets = {} + assets.lovelace = BigInt(v.coin) + if (v.multiasset){ + for (const policy of Object.keys(v.multiasset)){ + for (const assetname of Object.keys(v.multiasset[policy])){ + assets[policy + assetname] = BigInt(v.multiasset[policy][assetname]) + } + } + } + return assets +} + +function assetsToValueJS(v: Assets): C.ValueJSON { + const ret: C.ValueJSON = {coin: (v.lovelace || 0n).toString()} + for (const key of Object.keys(v)){ + if (key!="lovelace"){ + if (!ret.multiasset) { + ret.multiasset = {} + } + if (!ret.multiasset[key.slice(0,56)]) { + ret.multiasset[key.slice(0,56)] = {} + } + ret.multiasset[key.slice(0,56)][key.slice(56)] = v[key].toString() + } + } + + return ret +} + +function assetSub(a: Assets, b: Assets): Assets{ + const ret: Assets = {} + for (const key of Object.keys(a)){ + ret[key] = a[key] + } + for (const key of Object.keys(b)){ + if (!ret[key]){ + ret[key] = 0n + } + ret[key] -= b[key] + } + return ret +} + +function assetAdd(a: Assets, b: Assets): Assets{ + const ret: Assets = {} + for (const key of Object.keys(a)){ + ret[key] = a[key] + } + for (const key of Object.keys(b)){ + if (!(key in ret)){ + ret[key] = 0n + } + ret[key] += b[key] + } + return ret +} + + +function assetPositives(assets: Assets){ + const ret: Assets = {} + for (const key of Object.keys(assets)){ + if (assets[key] > 0) { + ret[key] = assets[key] + } + } + return ret +} + +function assetIntersect(a: Assets, b: Assets): number{ + let ret = 0 + for (const key of Object.keys(a)){ + if (key in b){ + ret+=1 + } + } + return ret +} + +function balance(collateralInput: C.TransactionUnspentOutput, availableInputs: C.TransactionUnspentOutput[], outputValue: C.ValueJSON): {selectedInputs: C.TransactionUnspentOutput[], excess: C.ValueJSON} { + let availableValues = availableInputs.map((x)=>valueJSToAssets(x.output().amount().to_js_value())) + let targetValue = valueJSToAssets(outputValue) + let currentValue = valueJSToAssets(C.Value.zero().to_js_value()) + let selectedInputs = new Set([] as number[]) + { + const collateralIdx = availableInputs.findIndex((x)=>x.input().to_json()==collateralInput.input().to_json()) + if (collateralIdx>0){ + selectedInputs.add(collateralIdx) + currentValue = assetAdd(currentValue, availableValues[collateralIdx]) + } + } + + for (let j=0; j<30; j++){ + let diff = assetSub(targetValue, currentValue) + let targetIncrease = assetPositives(diff) + if (Object.keys(targetIncrease).length <= 1){ + break + }else{ + let bestImprovement: [number, Assets, number] = [0, {}, -1] + for (let i = 0; i bestImprovement[0]){ + bestImprovement = [optVal, potentialValue, i] + } + } + } + if (bestImprovement[2] == -1) { + throw new Error("UTxO Balance Insufficient (1)") + } + selectedInputs.add(bestImprovement[2]) + currentValue = assetAdd(currentValue, bestImprovement[1]) + } + } + for (let j=0; j<30; j++){ + let diff = assetSub(targetValue, currentValue) + let targetIncrease = assetPositives(diff) + if (Object.keys(targetIncrease).length==0){ + break + } + let searchAsset = Object.keys(targetIncrease)[0] + + let bestImprovement: [bigint, Assets, number] = [0n, {}, -1] + for (let i = 0; i bestImprovement[0]) { + bestImprovement = [potentialValue[searchAsset], potentialValue, i] + } + } + } + if (bestImprovement[2] == -1) { + throw new Error("UTxO Balance Insufficient (2)") + } + selectedInputs.add(bestImprovement[2]) + currentValue = assetAdd(currentValue, bestImprovement[1]) + } + let finalInputs = [] as C.TransactionUnspentOutput[] + selectedInputs.forEach((x)=>finalInputs.push(availableInputs[x])) + return {selectedInputs: finalInputs, excess: assetsToValueJS(assetSub(currentValue, targetValue))} +} + +function txCollectFrom(txBuilder: C.TransactionBuilder, scripts: Record, native_scripts: Record, coreUtxo: C.TransactionUnspentOutput, redeemer?: string) { + let inputBuilder = C.SingleInputBuilder.new( + coreUtxo.input(), + coreUtxo.output(), + ); + let mr: C.InputBuilderResult; + let address = coreUtxo.output().address(); + let paymentCredential = address.payment_cred(); + if (redeemer && paymentCredential?.to_scripthash()) { + let paymentCredential = address.payment_cred(); + if (!paymentCredential) { + throw "Address has no payment credential"; + } + if (!paymentCredential.to_scripthash()) { + throw "Address isn't a scripthash but has a redeemer"; + } + let scriptHash = paymentCredential.to_scripthash()!.to_hex(); + let script = scripts[scriptHash]; + if (!script) { + throw "Script was not attached for UTxO spend"; + } + let datum = coreUtxo.output().datum()?.as_inline_data(); + if ("inlineScript" in script) { + mr = inputBuilder.plutus_script( + C.PartialPlutusWitness.new( + C.PlutusScriptWitness.from_script(script.inlineScript), + C.PlutusData.from_bytes(fromHex(redeemer)), + ), + C.Ed25519KeyHashes.new(), + datum!, + ); + } else { + mr = inputBuilder.plutus_script( + C.PartialPlutusWitness.new( + C.PlutusScriptWitness.from_ref(script.referenceScript.hash()), + C.PlutusData.from_bytes(fromHex(redeemer)), + ), + C.Ed25519KeyHashes.new(), + datum!, + ); + } + } else { + let payCred = coreUtxo.output().address().payment_cred(); + if (payCred?.kind() == 0) { + mr = inputBuilder.payment_key(); + } else { + let scriptHash = payCred?.to_scripthash()?.to_hex().toString()!; + let ns = native_scripts[scriptHash]; + if (!ns) { + throw "No native script was found for your mint without redeemer!"; + } + mr = inputBuilder.native_script( + ns, + C.NativeScriptWitnessInfo.assume_signature_count(), + ); + } + } + txBuilder.add_input(mr); +} + export class Tx { txBuilder: C.TransactionBuilder; @@ -53,6 +263,7 @@ export class Tx { private earlyTasks: ((that: Tx) => unknown)[]; private translucent: Translucent; + private spendRedeemers: Record = {} private UTxOs: C.TransactionUnspentOutput[] = []; private referencedUTxOs: C.TransactionUnspentOutput[] = []; @@ -108,63 +319,9 @@ export class Tx { } const coreUtxo = utxoToCore(utxo); this.UTxOs.push(coreUtxo); - let inputBuilder = C.SingleInputBuilder.new( - coreUtxo.input(), - coreUtxo.output(), - ); - let mr: C.InputBuilderResult; - let address = coreUtxo.output().address(); - let paymentCredential = address.payment_cred(); - if (redeemer && paymentCredential?.to_scripthash()) { - let paymentCredential = address.payment_cred(); - if (!paymentCredential) { - throw "Address has no payment credential"; - } - if (!paymentCredential.to_scripthash()) { - throw "Address isn't a scripthash but has a redeemer"; - } - let scriptHash = paymentCredential.to_scripthash()!.to_hex(); - let script = this.scripts[scriptHash]; - if (!script) { - throw "Script was not attached for UTxO spend"; - } - let datum = coreUtxo.output().datum()?.as_inline_data(); - if ("inlineScript" in script) { - mr = inputBuilder.plutus_script( - C.PartialPlutusWitness.new( - C.PlutusScriptWitness.from_script(script.inlineScript), - C.PlutusData.from_bytes(fromHex(redeemer)), - ), - C.Ed25519KeyHashes.new(), - datum!, - ); - } else { - mr = inputBuilder.plutus_script( - C.PartialPlutusWitness.new( - C.PlutusScriptWitness.from_ref(script.referenceScript.hash()), - C.PlutusData.from_bytes(fromHex(redeemer)), - ), - C.Ed25519KeyHashes.new(), - datum!, - ); - } - } else { - let payCred = coreUtxo.output().address().payment_cred(); - if (payCred?.kind() == 0) { - mr = inputBuilder.payment_key(); - } else { - let scriptHash = payCred?.to_scripthash()?.to_hex().toString()!; - let ns = this.native_scripts[scriptHash]; - if (!ns) { - throw "No native script was found for your mint without redeemer!"; - } - mr = inputBuilder.native_script( - ns, - C.NativeScriptWitnessInfo.assume_signature_count(), - ); - } + if (redeemer){ + this.spendRedeemers[toHex(coreUtxo.input().to_bytes())] = redeemer } - that.txBuilder.add_input(mr); } }); return this; @@ -246,7 +403,7 @@ export class Tx { let valueBuilder = outputBuilder.next(); let assetsC = assetsToValue(assets); let params = this.translucent.provider - ? await this.translucent.provider.getProtocolParameters() + ? await this.translucent.getProtocolParameters() : PROTOCOL_PARAMETERS_DEFAULT; { let masset = assetsC.multiasset() || C.MultiAsset.new(); @@ -312,7 +469,7 @@ export class Tx { let valueBuilder = outputBuilder.next(); let assetsC = assetsToValue(assets); let params = this.translucent.provider - ? await this.translucent.provider.getProtocolParameters() + ? await this.translucent.getProtocolParameters() : PROTOCOL_PARAMETERS_DEFAULT; { let masset = assetsC.multiasset() || C.MultiAsset.new(); @@ -787,6 +944,8 @@ export class Tx { async complete(options?: { change?: { address?: Address; outputData?: OutputData }; coinSelection?: boolean; + overEstimateMem?: number; + overEstimateSteps?: number; }): Promise { if ( [ @@ -833,22 +992,21 @@ export class Tx { options?.change?.address || (await this.translucent.wallet.address()), this.translucent, ); - for (const utxo of walletUTxOs) { - this.txBuilder.add_utxo( - C.SingleInputBuilder.new(utxo.input(), utxo.output()).payment_key(), - ); - } - this.txBuilder.select_utxos(2); + + let collateralInput: C.TransactionUnspentOutput { - let foundUtxo = walletUTxOs.find( + let foundUtxoLucid = walletUTxOs.filter( (x) => BigInt(x.output().amount().coin().to_str()) >= - BigInt(Math.pow(10, 7)), - ); + BigInt(5*Math.pow(10, 6)), + ).map(coreToUtxo).sort((a,b)=>Number(a.assets.length - b.assets.length))[0] + let foundUtxo = foundUtxoLucid ? utxoToCore(foundUtxoLucid) : undefined; + //console.log("BEST COLLATERAL UTXO", foundUtxoLucid) if (foundUtxo == undefined) { throw "Could not find a suitable collateral UTxO."; } else { + collateralInput = foundUtxo let collateralUTxO = C.SingleInputBuilder.new( foundUtxo.input(), foundUtxo.output(), @@ -861,7 +1019,7 @@ export class Tx { ); let amtBuilder = minCollateralOutput.next(); let params = this.translucent.provider - ? await this.translucent.provider.getProtocolParameters() + ? await this.translucent.getProtocolParameters() : PROTOCOL_PARAMETERS_DEFAULT; let multiAsset = foundUtxo.output().amount().multiasset(); amtBuilder = amtBuilder.with_asset_and_min_required_coin( @@ -873,6 +1031,31 @@ export class Tx { this.txBuilder.set_collateral_return(collateralReturn); } } + for (const utxo of this.UTxOs){ + if (utxo.input().to_bytes() != collateralInput.input().to_bytes()){ + txCollectFrom(this.txBuilder, this.scripts, this.native_scripts, utxo, this.spendRedeemers[toHex(utxo.input().to_bytes())]) + } + } + + + let rawOutputValue = this.txBuilder.get_explicit_output() + { + rawOutputValue = rawOutputValue.clamped_sub(collateralInput.output().amount()) + } + if (this.txBuilder.get_mint()){ + rawOutputValue = rawOutputValue.clamped_sub(C.Value.new_from_assets(this.txBuilder.get_mint()!.as_positive_multiasset())) + rawOutputValue = rawOutputValue.checked_add(C.Value.new_from_assets(this.txBuilder.get_mint()!.as_negative_multiasset())) + } + { + rawOutputValue = rawOutputValue.clamped_sub(this.txBuilder.get_explicit_input()) + } + const outputValue = rawOutputValue.to_js_value() + outputValue.coin = (BigInt(outputValue.coin)+(5n*(10n**6n))).toString() + const {selectedInputs, excess} = balance(collateralInput, walletUTxOs, outputValue) + + for (const inp of selectedInputs){ + this.txBuilder.add_input(C.SingleInputBuilder.new(inp.input(), inp.output()).payment_key()) + } let txRedeemerBuilder = this.txBuilder.build_for_evaluation( 0, changeAddress, @@ -880,7 +1063,7 @@ export class Tx { let protocolParameters: ProtocolParameters; try { protocolParameters = - await this.translucent.provider.getProtocolParameters(); + await this.translucent.getProtocolParameters(); } catch { protocolParameters = PROTOCOL_PARAMETERS_DEFAULT; } @@ -918,8 +1101,8 @@ export class Tx { allUtxos.map((x) => x.input().to_bytes()), allUtxos.map((x) => x.output().to_bytes()), costMdls.to_bytes(), - protocolParameters.maxTxExSteps, - protocolParameters.maxTxExMem, + BigInt(Math.floor(Number(protocolParameters.maxTxExSteps) / (options?.overEstimateSteps ?? 1))), + BigInt(Math.floor(Number(protocolParameters.maxTxExMem) / (options?.overEstimateMem ?? 1))), BigInt(slotConfig.zeroTime), BigInt(slotConfig.zeroSlot), slotConfig.slotLength, @@ -927,10 +1110,24 @@ export class Tx { const redeemers = C.Redeemers.new() for (const redeemerBytes of uplcResults) { let redeemer: C.Redeemer = C.Redeemer.from_bytes(redeemerBytes); + const exUnits = C.ExUnits.new( + C.BigNum.from_str( + Math.floor( + parseInt(redeemer.ex_units().mem().to_str()) * + (options?.overEstimateMem ?? 1), + ).toString(), + ), + C.BigNum.from_str( + Math.floor( + parseInt(redeemer.ex_units().steps().to_str()) * + (options?.overEstimateSteps ?? 1), + ).toString(), + ), + ) this.txBuilder.set_exunits( C.RedeemerWitnessKey.new(redeemer.tag(), redeemer.index()), - redeemer.ex_units(), - ); + exUnits, + ) redeemers.add(redeemer) } let builtTx = this.txBuilder.build(0, changeAddress).build_unchecked(); @@ -963,11 +1160,13 @@ export class Tx { } const languages = C.Languages.new() languages.add(C.Language.new_plutus_v2()) - const sdh = C.calc_script_data_hash(redeemers, datums, costMdls, languages) - if (sdh){ - const bodyWithDataHash = builtTx.body() - bodyWithDataHash.set_script_data_hash(sdh) - builtTx = C.Transaction.new(bodyWithDataHash, builtTx.witness_set(), builtTx.auxiliary_data()) + if (builtTx.witness_set().redeemers()) { + const sdh = C.calc_script_data_hash(builtTx.witness_set().redeemers()!, datums, costMdls, languages) + if (sdh){ + const bodyWithDataHash = builtTx.body() + bodyWithDataHash.set_script_data_hash(sdh) + builtTx = C.Transaction.new(bodyWithDataHash, builtTx.witness_set(), builtTx.auxiliary_data()) + } } } return new TxComplete(this.translucent, builtTx);