Skip to content

Commit

Permalink
[natives tokens] consolidation done
Browse files Browse the repository at this point in the history
  • Loading branch information
lambdina committed Nov 18, 2021
1 parent 3f97620 commit f506062
Show file tree
Hide file tree
Showing 9 changed files with 186 additions and 13 deletions.
4 changes: 2 additions & 2 deletions src/Tokenomia/Ada/Consolidate.hs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ import Shh.Internal
captureWords )

import Tokenomia.Adapter.Cardano.CLI.Wallet
import Tokenomia.Adapter.Cardano.CLI.UTxO.Query (queryUTxOsContainingStrictlyADAs)
import Tokenomia.Adapter.Cardano.CLI.UTxO.Query (queryUTxOsFilterBy)
import Tokenomia.Adapter.Cardano.CLI.Folder ( Folder(Transactions), getFolderPath )
import Tokenomia.Common.Error
import Tokenomia.Wallet.Collateral.Read
Expand Down Expand Up @@ -64,7 +64,7 @@ consolidate'
=> Wallet
-> m ()
consolidate' wallet@Wallet {..} = do
ada <- queryUTxOsContainingStrictlyADAs wallet --TODO check if ada is NonEmpty before call fromList
ada <- queryUTxOsFilterBy wallet containingStrictlyADAs
let amount = fold (value <$> ada)
(txFolder, rawTx ) <- (\a-> (a,a <> "tx.raw")) <$> getFolderPath Transactions
aGivenTxOutRef <- txOutRef <$> (selectBiggestStrictlyADAsNotCollateral wallet >>= whenNothingThrow NoADAInWallet)
Expand Down
4 changes: 2 additions & 2 deletions src/Tokenomia/Adapter/Cardano/CLI/Transaction.hs
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ import Shh.Internal
Stream(Truncate),
captureWords )

import Ledger ( TxOutRef (..),Value,Slot (..) )
import Ledger ( TxOutRef (..),Value,Slot (..), CurrencySymbol )

import Tokenomia.Common.Shell.Console (printLn)
import Tokenomia.Adapter.Cardano.CLI.Environment
Expand All @@ -76,7 +76,6 @@ import Tokenomia.Wallet.Collateral.Read
import Tokenomia.Adapter.Cardano.CLI.Wallet
import Tokenomia.Common.Error
import Tokenomia.Wallet.CLI
import Plutus.V1.Ledger.Ada (lovelaceValueOf)

{-# ANN module "HLINT: ignore Use camelCase" #-}

Expand All @@ -91,6 +90,7 @@ data BuildingTxError
| AlreadyACollateral UTxO
| NoADAInWallet
| NoUTxOWithOnlyOneToken
| NoUTxOWithSuchCurrency CurrencySymbol
| TryingToBurnTokenWithoutScriptRegistered
| NoVestingInProgress
| NoFundsToBeRetrieved
Expand Down
4 changes: 3 additions & 1 deletion src/Tokenomia/Adapter/Cardano/CLI/UTxO.hs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@ import Data.Foldable ( Foldable(fold) )
import Plutus.V1.Ledger.Ada
import Ledger.Value


getTokenFrom :: UTxO -> (CurrencySymbol,TokenName,Integer)
getTokenFrom UTxO {..} = (head . filter (\(c,_,_) -> c /= adaSymbol ) .flattenValue) value -- should contains only one native token (filtering ADAs)

Expand Down Expand Up @@ -71,6 +70,9 @@ instance Show UTxO where
instance DisplayMenuItem UTxO where
displayMenuItem UTxO {..} = showTxOutRef txOutRef <> " : " <> showValue value

instance DisplayMenuItem CurrencySymbol where
displayMenuItem (CurrencySymbol a) = show a

instance ToCLI TxOutRef where
toCLI = T.pack . showTxOutRef

Expand Down
43 changes: 36 additions & 7 deletions src/Tokenomia/Adapter/Cardano/CLI/UTxO/Query.hs
Original file line number Diff line number Diff line change
Expand Up @@ -18,31 +18,34 @@

module Tokenomia.Adapter.Cardano.CLI.UTxO.Query
( query
<<<<<<< HEAD
, queryUTxOsFilterBy
=======
, queryUTxOsContainingStrictlyADAs
>>>>>>> 12f4d10 ([ada] consolidation done)
, getCurrency
, askSelectUTxOByType
) where


import qualified Data.Text.Lazy as TL
import Data.Text.Lazy.Encoding as TLE ( decodeUtf8 )


import Control.Monad.Reader ( MonadReader, MonadIO(..), asks )
import Shh.Internal
import Ledger.Value

import Tokenomia.Adapter.Cardano.CLI.Wallet
import Tokenomia.Adapter.Cardano.CLI.Serialise
import Tokenomia.Adapter.Data.List (short, rmdups)
import Tokenomia.Adapter.Cardano.CLI.Environment
import Tokenomia.Adapter.Cardano.CLI.Value ()
import Tokenomia.Adapter.Cardano.CLI.UTxO
import Tokenomia.Adapter.Cardano.Types
import Tokenomia.Adapter.Cardano.Types
import Data.List.NonEmpty (fromList)
import Tokenomia.Common.Shell.InteractiveMenu (askMenu, DisplayMenuItem, displayMenuItem)


load SearchPath ["cardano-cli"]

query ::
query ::
( MonadIO m
, MonadReader Environment m )
=> Address
Expand All @@ -58,4 +61,30 @@ queryUTxOsFilterBy ::
=> Wallet
-> (UTxO -> Bool)
-> m [UTxO]
queryUTxOsFilterBy Wallet {..} f = filter f <$> query paymentAddress
queryUTxOsFilterBy Wallet{..} f = filter f <$> query paymentAddress

getCurrency :: UTxO -> (CurrencySymbol, TokenName)
getCurrency utxo = (currency, _tokenName)
where (currency, _tokenName, _) = getTokenFrom utxo

queryTokensList :: (MonadIO m, MonadReader Environment m) => Wallet -> m [(CurrencySymbol, TokenName)]
queryTokensList wallet = do
utxos <- queryUTxOsFilterBy wallet (not . containingStrictlyADAs)
if null utxos then return [] else do
let currencyList = map getCurrency utxos
return $ rmdups currencyList

askSelectUTxOByType :: (MonadIO m, MonadReader Environment m) => Wallet -> m (Maybe [UTxO])
askSelectUTxOByType wallet = do
tokensList <- queryTokensList wallet
case tokensList of
[] -> return Nothing
tokenList -> do
(currency, _) <- askMenu $ fromList tokenList --displayMenuItem
queryUTxOsFilterBy wallet (containingGivenNativeToken currency) >>=
\case
[] -> return Nothing
utxos -> return $ Just utxos

instance DisplayMenuItem (CurrencySymbol, TokenName) where
displayMenuItem (currency, _tokenName) = toString _tokenName <> " - " <> short (show currency)
1 change: 0 additions & 1 deletion src/Tokenomia/Adapter/Cardano/Types.hs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
{-# LANGUAGE DerivingStrategies #-}
{-# LANGUAGE DerivingVia #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Tokenomia.Adapter.Cardano.Types (Address (..), Hash(..)) where
Expand Down
13 changes: 13 additions & 0 deletions src/Tokenomia/Adapter/Data/List.hs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
module Tokenomia.Adapter.Data.List where
import qualified Data.Set as Set

rmdups :: Ord a => [a] -> [a]
rmdups = rmdups' Set.empty where
rmdups' _ [] = []
rmdups' a (b : c) = if Set.member b a
then rmdups' a c
else b : rmdups' (Set.insert b a) c

short :: Ord a => a -> a
short [] = []
short x = take (length x `div` 2) x
6 changes: 6 additions & 0 deletions src/Tokenomia/CLI.hs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ import qualified Tokenomia.Wallet.Collateral.Write as Wallet
import qualified Tokenomia.Token.CLAPStyle.Mint as Token
import qualified Tokenomia.Token.CLAPStyle.Burn as Token
import qualified Tokenomia.Token.Transfer as Token
import qualified Tokenomia.Token.Consolidate as Token

import qualified Tokenomia.Ada.Transfer as Ada
import qualified Tokenomia.Ada.Consolidate as Ada
Expand Down Expand Up @@ -115,6 +116,7 @@ recursiveMenu = do
AlreadyACollateral utxo -> printLn ("Collateral Already Created..." <> show utxo)
NoADAInWallet -> printLn "Please, add ADAs to your wallet..."
NoUTxOWithOnlyOneToken -> printLn "Please, add tokens to your wallet..."
NoUTxOWithSuchCurrency c -> printLn ("No UTxO found with " <> show c <> " currency.")
TryingToBurnTokenWithoutScriptRegistered
-> printLn "You can't burn tokens without the monetary script registered in Tokenomia"
NoVestingInProgress -> printLn "No vesting in progress"
Expand All @@ -141,6 +143,7 @@ runAction = \case
TokenMint -> Token.mint
TokenBurn -> Token.burn
TokenTransfer -> Token.transfer
TokenConsolidate -> Token.consolidate
AdaTransfer -> Ada.transfer
AdaConsolidate -> Ada.consolidate
VestingVestFunds -> Vesting.vestFunds
Expand All @@ -157,6 +160,7 @@ actions = NonEmpty.fromList [
TokenMint,
TokenBurn,
TokenTransfer,
TokenConsolidate,
AdaTransfer,
AdaConsolidate,
VestingVestFunds,
Expand All @@ -174,6 +178,7 @@ data Action
| TokenMint
| TokenBurn
| TokenTransfer
| TokenConsolidate
| AdaTransfer
| AdaConsolidate
| VestingVestFunds
Expand All @@ -191,6 +196,7 @@ instance DisplayMenuItem Action where
TokenMint -> " [Token] - Mint with CLAP type policy (Fix Total Supply | one-time Minting and open Burning Policy)"
TokenBurn -> " [Token] - Burn Tokens with CLAP type policy"
TokenTransfer -> " [Token] - Transfer Tokens"
TokenConsolidate -> "[Token] - Consolidate Tokens"
AdaTransfer -> " [Ada] - Transfer ADAs"
AdaConsolidate -> " [Ada] - Consolidate ADAs"
VestingVestFunds -> "[Vesting] - Vest Funds"
Expand Down
122 changes: 122 additions & 0 deletions src/Tokenomia/Token/Consolidate.hs
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE ExtendedDefaultRules #-}
{-# LANGUAGE FlexibleContexts #-}
{-# OPTIONS_GHC -fno-warn-missing-signatures #-}
{-# OPTIONS_GHC -fno-warn-unused-top-binds #-}
{-# LANGUAGE RecordWildCards #-}

module Tokenomia.Token.Consolidate where


import Data.List.NonEmpty
import qualified Data.ByteString.Lazy.Char8 as C
import Control.Monad.Reader hiding (ask)
import Control.Monad.Except
import Ledger.Ada ( lovelaceValueOf )
import Data.Foldable
import Ledger (Slot(Slot))

import Tokenomia.Adapter.Cardano.CLI.Node

import Tokenomia.Adapter.Cardano.CLI.Environment
import Tokenomia.Adapter.Cardano.CLI.UTxO
import Tokenomia.Adapter.Cardano.CLI.Transaction hiding (value)
import Shh.Internal
( load,
(|>),
ExecArg(asArg),
ExecReference(SearchPath),
captureWords )

import Tokenomia.Adapter.Cardano.CLI.Wallet
import Tokenomia.Adapter.Cardano.CLI.UTxO.Query (askSelectUTxOByType)
import Tokenomia.Adapter.Cardano.CLI.Folder ( Folder(Transactions), getFolderPath )
import Tokenomia.Common.Error
import Tokenomia.Wallet.Collateral.Read
import Tokenomia.Wallet.CLI
( selectBiggestStrictlyADAsNotCollateral,
askToChooseAmongGivenWallets )
import Tokenomia.Common.Shell.Console (printLn)
import PlutusTx.Prelude (AdditiveGroup((-)))


load SearchPath ["cardano-cli", "md5sum", "mv", "echo"]


consolidate
:: ( MonadIO m
, MonadReader Environment m
, MonadError BuildingTxError m)
=> m ()
consolidate = do
wallet@Wallet{..} <- fetchWalletsWithCollateral >>= whenNullThrow NoWalletWithCollateral
>>= \wallets -> do
printLn "Select the minter wallet : "
askToChooseAmongGivenWallets wallets
tokensChoosen <- askSelectUTxOByType wallet >>= whenNothingThrow NoFundsToBeRetrieved
consolidate' wallet tokensChoosen

consolidate'
:: ( MonadIO m
, MonadReader Environment m
, MonadError BuildingTxError m)
=> Wallet
-> [UTxO]
-> m ()
consolidate' wallet@Wallet {..} utxos = do
let amount = fold (value <$> utxos)
(txFolder, rawTx ) <- (\a-> (a,a <> "tx.raw")) <$> getFolderPath Transactions
aGivenTxOutRef <- txOutRef <$> (selectBiggestStrictlyADAsNotCollateral wallet >>= whenNothingThrow NoADAInWallet)

buildRaw "0" (toCardanoCLIOptions TxBuild
{ wallet = wallet
, txIns = fromList (fmap (FromWallet . txOutRef) utxos)
, txOuts = ToWallet paymentAddress (lovelaceValueOf 1) :| []
, metadataMaybe = Nothing
, validitySlotRangeMaybe = Nothing
, tokenSupplyChangesMaybe = Nothing
, ..})
fees <- computeFees (Prelude.length utxos) 1
Slot synSlotAsInt <- getCurrentSlotSynced
buildRaw (show fees) (toCardanoCLIOptions TxBuild
{ wallet = wallet
, txIns = fromList (fmap (FromWallet . txOutRef) utxos)
, txOuts = ToWallet paymentAddress (amount PlutusTx.Prelude.- lovelaceValueOf fees) :| []
, metadataMaybe = Nothing
, validitySlotRangeMaybe = Nothing
, tokenSupplyChangesMaybe = Nothing
, ..}
<> ["--invalid-hereafter", show (synSlotAsInt + 600)])
-- Hashing the tx.raw and getting its hash x for renaming the tx.raw into x.raw
(rawHashTx,signedHashTx) <- (\txHash -> ( txFolder <> txHash <> ".raw"
, txFolder <> txHash <> ".signed" ) )
. C.unpack . Prelude.head <$> liftIO (md5sum rawTx |> captureWords )
liftIO $ mv rawTx rawHashTx

printLn "Signing Tx" >> sign_tx rawHashTx signedHashTx paymentSigningKeyPath
printLn "Submitting Tx" >> submit_tx signedHashTx
printLn "Waiting for confirmation..."
awaitTxCommitted aGivenTxOutRef 0
printLn "\nTx committed into ledger"


buildRaw
:: ( ExecArg a, MonadIO m, MonadReader Environment m)
=> String
-> a
-> m ()
buildRaw fee buildTxBody = do
(_, rawTx ) <- (\a-> (a,a <> "tx.raw")) <$> getFolderPath Transactions

liftIO $ cardano_cli
"transaction"
"build-raw"
(asArg buildTxBody)
"--fee" fee
"--out-file" rawTx
liftIO $ echo "transaction"
"build-raw"
(asArg buildTxBody)
"--fee" fee
"--out-file" rawTx

2 changes: 2 additions & 0 deletions tokenomia.cabal
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ library
Tokenomia.Ada.Consolidate
Tokenomia.Common.Error
Tokenomia.Token.Transfer
Tokenomia.Token.Consolidate
Tokenomia.Vesting.Contract
Tokenomia.Vesting.Repository
Tokenomia.Vesting.Vest
Expand All @@ -71,6 +72,7 @@ library
Tokenomia.Adapter.Cardano.CLI.Folder
Tokenomia.Adapter.Cardano.CLI.Scripts
Tokenomia.Adapter.Cardano.CLI.Wallet
Tokenomia.Adapter.Data.List
Tokenomia.Common.Shell.InteractiveMenu
Tokenomia.Common.Shell.Console
Tokenomia.Adapter.Cardano.CLI.Environment
Expand Down

0 comments on commit f506062

Please sign in to comment.