Skip to content

Commit

Permalink
UI fixes and fix oscillation in fee balancing
Browse files Browse the repository at this point in the history
  • Loading branch information
Sudip Bhattarai committed Feb 20, 2023
1 parent e456782 commit 9dd1251
Show file tree
Hide file tree
Showing 6 changed files with 94 additions and 68 deletions.
2 changes: 2 additions & 0 deletions .dockerignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
*
!./dist-newstyle/build/docker
140 changes: 83 additions & 57 deletions playground/src/components/Editor.vue
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
<script setup lang="ts">
import { Buffer } from "buffer";
import { callKuber,getPolicyIdOfScriptFromKuber,listProviders, signTx, submitTx } from "kuber-client"
import {
callKuber,
getPolicyIdOfScriptFromKuber,
listProviders,
signTx,
submitTx,
} from "kuber-client";
</script>

<template>
Expand Down Expand Up @@ -348,10 +353,14 @@ import { callKuber,getPolicyIdOfScriptFromKuber,listProviders, signTx, submitTx
v-if="language === LanguageEnums.Haskell"
class="flex flex-col h-5/6 overflow-y-auto"
>
<pre v-for="output in haskellOutputs" class="text-gray-800 py-1">{{ output }}</pre>
<pre v-for="output in haskellOutputs" class="text-gray-800 py-1">{{
output
}}</pre>
</div>
<div id="kuber-output" v-else class="flex flex-col h-5/6 overflow-y-auto">
<pre v-for="output in kuberOutputs" class="text-gray-800 py-1">{{ output }}</pre>
<pre v-for="output in kuberOutputs" class="text-gray-800 py-1">{{
output
}}</pre>
</div>
</div>

Expand Down Expand Up @@ -711,6 +720,7 @@ import {
BaseAddress,
Ed25519KeyHash,
EnterpriseAddress,
hash_transaction,
PointerAddress,
} from "@emurgo/cardano-serialization-lib-asmjs";
import { SchemaKuber } from "./schemas";
Expand Down Expand Up @@ -742,7 +752,7 @@ import type { CIP30Instace, CIP30Provider } from "kuber-client/types";
const notification = _notification.useNotificationStore();
export default {
components: {AddressUtil},
components: { AddressUtil },
editor: null,
mounted() {
let counter = 5;
Expand All @@ -759,11 +769,14 @@ export default {
this.timeout = setTimeout(refreshProvider, 1000);
},
data() {
const autoApi= {
const autoApi = {
text: "text-[#60A5FA]",
name: "Auto",
border: "border-[#60A5FA]",
display: import.meta.env.VITE_API_URL === undefined ? "Mainnet/PreProd based on wallet NetworkId": "Same server's API backend",
display:
import.meta.env.VITE_API_URL === undefined
? "Mainnet/PreProd based on wallet NetworkId"
: "Same server's API backend",
url: import.meta.env.VITE_API_URL,
};
const providers: Array<CIP30Provider> = [];
Expand Down Expand Up @@ -812,7 +825,7 @@ export default {
NetworkEnums.PreviewTestnet,
],
apis: {
auto:autoApi,
auto: autoApi,
"preview testnet": {
text: "text-blue-400",
border: "border-blue-400",
Expand Down Expand Up @@ -1024,12 +1037,11 @@ export default {
},
loadHaskellCode(tab: HaskellTabEnums) {
this.$options.editor.setValue(HaskellCodes[tab]);
this.$options.editor.updateOptions({
lineNumbers: true,
readOnly: true,
});
this.$options.editor.setValue(HaskellCodes[tab]);
this.$options.editor.updateOptions({
lineNumbers: true,
readOnly: true,
});
},
loadKuberCode(tab: KuberTabEnums) {
Expand Down Expand Up @@ -1166,20 +1178,19 @@ export default {
var code = this.$options.editor.getValue();
code = code.trim();
localStorage.setItem(LanguageEnums.Haskell, code);
APIService.compileCode(code).then((response:any) => {
APIService.compileCode(code).then((response: any) => {
this.showOutputTerminal(true);
this.isCompiling = false;
if (response) {
if(response.result){
response.result.hash
const script=response.result.script
this.setHaskellOutput("ScriptHash:" + response.result.hash);
const jsonContent=JSON.stringify(script, null, 5).split('\n')
jsonContent[0] ="Script :" + jsonContent[0]
this.haskellOutputs.push(...jsonContent)
}
else {
console.error(response)
if (response.result) {
response.result.hash;
const script = response.result.script;
this.setHaskellOutput("ScriptHash:" + response.result.hash);
const jsonContent = JSON.stringify(script, null, 5).split("\n");
jsonContent[0] = "Script :" + jsonContent[0];
this.haskellOutputs.push(...jsonContent);
} else {
console.error(response);
this.setHaskellOutput(response.output + response.error);
}
}
Expand Down Expand Up @@ -1212,7 +1223,7 @@ export default {
this.isCompiling = false;
return;
}
console.log("Using provider",provider)
console.log("Using provider", provider);
return provider
.enable()
Expand All @@ -1232,53 +1243,68 @@ export default {
availableUtxos.forEach((v) => {
request.selections.push(v);
});
}else{
} else {
availableUtxos.push(request.selections);
request.selections=availableUtxos
request.selections = availableUtxos;
}
} else {
request.selections = availableUtxos;
}
}
let url =this.activeApi.url
if(!url && this.activeApi.name=='Auto'){
const network=await instance.getNetworkId()
if(network){
url = this.apis.mainnet.url
}else{
url = this.apis["preprod testnet"].url
}
let url = this.activeApi.url;
if (!url && this.activeApi.name == "Auto") {
const network = await instance.getNetworkId();
if (network) {
url = this.apis.mainnet.url;
} else {
url = this.apis["preprod testnet"].url;
}
const transactionResponse = await callKuber(
url,
JSON.stringify(request)
);
this.kuberOutputs.push("Fee : " + transactionResponse.fee + " lovelace")
this.kuberOutputs.push("TransactionHash : " + transactionResponse.txHash)
this.kuberOutputs.push("Unsigned Tx : ["+(transactionResponse.tx.length /2) +" bytes] " + transactionResponse.tx)
const signedTx= await signTx (instance,transactionResponse.tx)
const signedTxHex=signedTx.to_hex()
this.kuberOutputs.push("Signed Tx : ["+(signedTxHex.length /2) +" bytes] " + signedTxHex)
return submitTx(instance,signedTx).then(()=>{
this.kuberOutputs.push("Tx Submitted ✓✓")
}).catch(e=>{
this.kuberOutputs.push("❌ Tx submission Failed: " +((e && (e.message || e.info)) || e))
}
const transactionResponse = await callKuber(url, JSON.stringify(request));
this.kuberOutputs.push(
"Fee : " + transactionResponse.fee + " lovelace"
);
this.kuberOutputs.push("Unsigned txHash : " + transactionResponse.txHash);
this.kuberOutputs.push(
"Unsigned Tx : [" +
transactionResponse.tx.length / 2 +
" bytes] " +
transactionResponse.tx
);
const signedTx = await signTx(instance, transactionResponse.tx);
const signedTxHex = signedTx.to_hex();
this.kuberOutputs.push(
"Signed Tx : [" + signedTxHex.length / 2 + " bytes] " + signedTxHex
);
this.kuberOutputs.push(
"Signed txHash : "+hash_transaction(signedTx.body()).to_hex()
);
return submitTx(instance, signedTx)
.then(() => {
this.kuberOutputs.push("✅ Tx Submitted");
})
.catch((e) => {
this.kuberOutputs.push(
"❌ Tx submission Failed: " + ((e && (e.message || e.info)) || e)
);
notification.setNotification({
type: "error",
message: ((e && (e.message || e.info)) ) || "Oopsie, Nobody knows what happened",
message:
(e && (e.message || e.info)) || "Oopsie, Nobody knows what happened",
});
})
});
})
.catch((e: any) => {
console.error("SubmitTx", e);
let msg=(e && (e.message || e.info)) || "Oopsie, Nobody knows what happened"
notification.setNotification({
type: "alert",
message: e.message || "Oopsie, Nobody knows what happened",
message:msg
});
this.kuberOutputs.push(e.message || "Oopsie, Nobody knows what happened");
}).finally(()=>{
this.isCompiling=false;
this.kuberOutputs.push(""+msg);
})
.finally(() => {
this.isCompiling = false;
});
}
},
Expand Down
2 changes: 2 additions & 0 deletions server/app/Main.hs
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,11 @@ import Data.Typeable (Typeable)
import System.Console.CmdArgs
import Text.Read (readMaybe)
import Data.String (IsString(..))
import System.IO

main :: IO ()
main = do
hSetBuffering stdout LineBuffering
dcinfo <- chainInfoFromEnv >>= withDetails
Modes port hostStr <- cmdArgs $ modes [
Modes {
Expand Down
16 changes: 7 additions & 9 deletions src/Cardano/Kuber/Core/TxFramework.hs
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ import Cardano.Binary (ToCBOR(toCBOR))
import qualified Cardano.Binary as Cborg
import Cardano.Kuber.Utility.ScriptUtil
import Cardano.Kuber.Utility.QueryHelper (queryUtxos, queryTxins)
import Cardano.Kuber.Console.ConsoleWritable (ConsoleWritable(toConsoleTextNoPrefix))
import Cardano.Kuber.Console.ConsoleWritable (ConsoleWritable(toConsoleTextNoPrefix, toConsoleText))
import Cardano.Kuber.Utility.DataTransformation (skeyToPaymentKeyHash, pkhToPaymentKeyHash)
import Data.Foldable (foldlM)
import Data.Bifunctor (first)
Expand All @@ -79,6 +79,7 @@ import Cardano.Slotting.EpochInfo (hoistEpochInfo, epochInfoSlotToUTCTime)
import Ouroboros.Consensus.HardFork.History.EpochInfo (interpreterToEpochInfo)
import Control.Monad.Trans.Except(runExcept)
import Data.Time.Clock.POSIX (utcTimeToPOSIXSeconds)
import qualified Data.Aeson.KeyMap as Mpa

type BoolChange = Bool
type BoolFee = Bool
Expand Down Expand Up @@ -123,8 +124,6 @@ txBuilderToTxBodyIO' cInfo builder = do
Left fe -> pure $ Left fe
Right (UTxO txInUtxos) ->do
-- Compute Txbody and return
putStrLn $ (show builder)
putStrLn $ toConsoleTextNoPrefix $ UTxO (combinedUtxos <> txInUtxos)
pure $ txBuilderToTxBody' dcInfo (UTxO $ combinedUtxos <> txInUtxos) builder
where

Expand Down Expand Up @@ -228,11 +227,11 @@ txBuilderToTxBody' dCinfo@(DetailedChainInfo cpw conn pParam ledgerPParam syste
(finalBody,finalSignatories,finalFee) <- (
if not requiresExUnitCalculation && null unresolvedMints
then (
let iteratedBalancing 0 _ = Left $ FrameworkError LibraryError "Transaction not balanced even in 7 iterations"
iteratedBalancing n lastFee= do
let
iteratedBalancing n lastFee= Debug.trace (show n ++ " -> lastfee:" ++ show lastFee) $ do
case calculator (txMintValue' mempty) fixedInputs lastFee of
Right v@(txBody',signatories',fee') ->
if fee' == lastFee
if (if n>0 then (==) else (<=) ) fee' lastFee
then pure v
else iteratedBalancing (n-1) fee'
Left e -> Left e
Expand All @@ -241,14 +240,13 @@ txBuilderToTxBody' dCinfo@(DetailedChainInfo cpw conn pParam ledgerPParam syste
else iteratedBalancing 7 fee1
)
else (
let iteratedBalancing 0 _ _ = Left $ FrameworkError LibraryError "Transaction not balanced even in 10 iterations"
iteratedBalancing n lastBody lastFee=do
let iteratedBalancing n lastBody lastFee=do
(inputExmap,mintExmap) <- evaluateExUnitMap dCinfo ( UTxO availableUtxo) lastBody
inputs' <- usedInputs (Map.map Right inputExmap ) (Right defaultExunits) resolvedInputs
exUnitAppliedMints <- applyMintExUnits mintExmap (\p -> Left $ FrameworkError BalancingError ("Missing Exunits for minting" ++ show p)) unresolvedMints
case calculator (txMintValue' exUnitAppliedMints) inputs' lastFee of
Right v@(txBody',signatories',fee') ->
if fee' == lastFee
if (if n>0 then (==) else (<=) ) fee' lastFee
then pure v
else iteratedBalancing (n-1) txBody' fee'
Left e -> Left e
Expand Down
1 change: 0 additions & 1 deletion src/Cardano/Kuber/Data/Parsers.hs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,6 @@ import Data.Text.Conversions (Base16 (Base16, unBase16),
import Data.Text.Encoding (encodeUtf8)
import qualified Data.Text.Encoding as T
import qualified Data.Text.Encoding as TSE
import Debug.Trace (traceM)
import GHC.IO.Exception (IOErrorType (UserError),
IOException (IOError))
import Text.Read (readMaybe)
Expand Down
1 change: 0 additions & 1 deletion src/Cardano/Kuber/Data/TxBuilderAeson.hs
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,6 @@ import qualified Data.ByteString.Short as SBS
import qualified Data.ByteString.Lazy as LBS
import qualified Data.Text.Lazy.Encoding as TL
import qualified Data.Text.Lazy as TL
import Debug.Trace (trace, traceM)
import qualified Data.HashMap.Strict as HM
import Data.String (IsString(fromString))
import qualified Debug.Trace as Debug
Expand Down

0 comments on commit 9dd1251

Please sign in to comment.