Coder Social home page Coder Social logo

potential-robot's Introduction

Hi there ๐Ÿ‘‹

I am Alex, a cybertramp, a founder of Tarax DAO and a co-founder of Intersect MBO.

  • ๐Ÿ’ป I've been coding since I was a kid, starting with BASIC and Pascal.
  • ๐ŸŒฑ Iโ€™m currently learning Software Verification, Contemporary Mathematical Thinking and Ontology of Money.
  • ๐Ÿคฏ Fun fact: Money is pre-eminently a political category.

potential-robot's People

Contributors

aleeusgr avatar

Stargazers

 avatar  avatar

Watchers

 avatar

potential-robot's Issues

helios testing harness example

<@930457726323138570> This is my full test file for a vault SC

import { describe, it, beforeAll, expect } from 'vitest'
import { Program, Address, NetworkEmulator, ConstrData } from "@hyperionbt/helios"
import fs from "fs";

let program;
let testContract;

describe('Raffle Vault works appropriately', () => {


    beforeAll(() => {

        const testSetup = {
            contract: './components/Contracts/vault.hl',
            fixtures: [
                './tests/vault_fixtures.hl'
            ],
            helpers: [
            ],
            // replacements: [
            //     []
            // ]
        }

        const contractSources: string[] = []

        contractSources.push(
            fs.readFileSync(testSetup.contract).toString()
        )

        testSetup.fixtures.forEach(fixture => contractSources.push(fs.readFileSync(fixture).toString()))

        const source = contractSources
            .join("\n")
            .replace('context.get_current_validator_hash()', 'ValidatorHash::new(#01234567890123456789012345678901234567890123456789000001)')

        program = Program.new(source);
        testContract = program.compile();
    })


    it(`should allow Admin to spend`, async () => {

        const args = ["datum", "admin", "sc_admin_signed"].map((p) => program.evalParam(p))
        return await testContract
            .runWithPrint(args)
            .then((res) => {
                console.log('res', JSON.stringify(res))
                expect(res[0].toString()).toBe("()");
            })
    })

    it(`should allow Winner to spend`, async () => {

        const args = ["datum", "winner", "sc_winner_signed"].map((p) => program.evalParam(p))
        return await testContract
            .runWithPrint(args)
            .then((res) => {
                console.log('res', JSON.stringify(res))
                expect(res[0].toString()).toBe("()");
            })
    })

    it(`should forbid admin to spend if signed as winner`, async () => {
        const args = ["datum", "admin", "sc_winner_signed"].map((p) => program.evalParam(p))
        return await testContract
            .runWithPrint(args)
            .then((res) => {
                expect(res[1]).toContain('TRACE_IS_ADMIN: false')
                expect(res[0].toString()).not.toBe("()")
            })
    })

    it(`should forbid winner to spend if signed as admin`, async () => {
        const args = ["datum", "winner", "sc_admin_signed"].map((p) => program.evalParam(p))
        return await testContract
            .runWithPrint(args)
            .then((res) => {
                expect(res[1]).toContain('TRACE_IS_WINNER: false')
                expect(res[0].toString()).not.toBe("()")
            })
    })

    it(`should forbid other to spend if signed as admin`, async () => {
        const args = ["datum", "admin", "sc_loser_signed"].map((p) => program.evalParam(p))
        return await testContract
            .runWithPrint(args)
            .then((res) => {
                expect(res[1]).toContain('TRACE_IS_ADMIN: false')
                expect(res[0].toString()).not.toBe("()")
            })
    })

    it(`should forbid other to spend if signed as winner`, async () => {
        const args = ["datum", "winner", "sc_loser_signed"].map((p) => program.evalParam(p))
        return await testContract
            .runWithPrint(args)
            .then((res) => {
                expect(res[1]).toContain('TRACE_IS_WINNER: false')
                expect(res[0].toString()).not.toBe("()")
            })
    })

})

https://discord.com/channels/997177025972424815/1092933893096755301/1093785314792845344

Formal Verification

  • format

CoQ, yices, Z3 and the whole world of tools and methods.
I think I have a good book in my old laptop, any heads up on tooling to look into?

Or contract model is all you need?

Thank you, ๐Ÿ™

CoQ is far from being automated ๐Ÿ˜… yices and z3 would need to do some development to translate from Plutus (or another programming language) to SMT lib and embedding the behavior of the ledger as well

https://discord.com/channels/1029837832350605343/1030116075532206101/1097197231909646447

Helios: wallet emulator

Suggestion by Lawrence Ley:

<@930457726323138570> I decided to create a quick example that uses a Helios network emulator as a node.js app and how this could be a starting point for unit/integration/automated testing. If combined with Vitest, I think this can be very helpful in certifying applications.
https://github.com/lley154/helios-examples/tree/main/emulator

https://www.hyperion-bt.org/helios-book/api/reference/networkemulator.html

https://gav.hashnode.dev/coinselection-part1

test Deno

nix-shell -p deno

Deno aims to be a productive and secure scripting environment for the modern programmer. Deno will always be distributed as a single executable. Given a URL to a Deno program, it is runnable with nothing more than the ~15 megabyte zipped executable. Deno explicitly takes on the role of both runtime and package manager. It uses a standard browser-compatible protocol for loading modules: URLs. Among other things, Deno is a great replacement for utility scripts that may have been historically written with bash or python.

instantiate the emulator

// https://github.com/spacebudz/lucid/blob/main/tests/emulator.test.ts
async function generateAccount(assets: Assets) {
const seedPhrase = generateSeedPhrase();
return {
seedPhrase,
address: await (await Lucid.new(undefined, "Custom"))
.selectWalletFromSeed(seedPhrase).wallet.address(),
assets,
};
}
const lender = await generateAccount({ lovelace: 75000000000n });
const borrower = await generateAccount({ lovelace: 100000000n });
const emulator = new Emulator([lender, borrower]);
const lucid = await Lucid.new(emulator);

submit a transaction

lucid.selectWalletFromSeed(lender.seedPhrase);
const recipient =
"addr_test1qrupyvhe20s0hxcusrzlwp868c985dl8ukyr44gfvpqg4ek3vp92wfpentxz4f853t70plkp3vvkzggjxknd93v59uysvc54h7";
// this needs to change.
const datum = Data.to(123n);
const lovelace = 3000000n;

const tx = await lucid.newTx().payToAddressWithData(recipient, {
inline: datum,
}, { lovelace }).complete();
const signedTx = await tx.sign().complete();
const txHash = await signedTx.submit();
await lucid.awaitTx(txHash);

review

  • what would be the simplest test?
  • src/mint.mjs
  • tests/mint-onchain...

contract execution example

  • comment
{-# LANGUAGE DerivingStrategies #-}
{-# LANGUAGE ImportQualifiedPost #-}
{-# LANGUAGE NumericUnderscores #-}

module Main (main) where

import Control.Monad.IO.Class (liftIO)
import Control.Monad.Reader (ReaderT (ReaderT), ask)
import Data.Default (def)
import Data.Monoid (Last (getLast))
import Data.Text.Lazy qualified as T
import ExampleContracts (ownValueToState)
import Test.Plutip.Config (
  PlutipConfig (extraConfig),
 )
import Test.Plutip.Contract (runContract)
import Test.Plutip.Internal.BotPlutusInterface.Wallet (
  BpiWallet,
  addSomeWallet,
  mkMainnetAddress,
  walletPkh,
 )
import Test.Plutip.Internal.Cluster.Extra.Types (
  ExtraConfig (ecSlotLength),
 )
import Test.Plutip.Internal.LocalCluster (
  startCluster,
  stopCluster,
 )
import Test.Plutip.Internal.Types (
  ClusterEnv,
  ExecutionResult (contractState, outcome),
  nodeSocket,
 )
import Test.Plutip.Tools.ChainIndex qualified as CI
import Text.Pretty.Simple (pShow)

main :: IO ()
main = do
  let slotLen = 1
      extraConf = def {ecSlotLength = slotLen}
      plutipConfig = def {extraConfig = extraConf}

      addSomeWalletWithCollateral funds =
        addSomeWallet (toAda 10 : funds)

  putStrLn "Starting cluster..."
  (st, _) <- startCluster plutipConfig $ do
    w <- addSomeWalletWithCollateral [toAda 100]
    liftIO $ putStrLn "Waiting for wallets to be funded..."
    CI.awaitWalletFunded w slotLen

    separate
    printWallet (w, 1)
    printNodeRelatedInfo

    separate
    res <- executeContract w ownValueToState
    printResult res

    separate

  putStrLn "Stopping cluster"

  stopCluster st
  where
    printNodeRelatedInfo = ReaderT $ \cEnv -> do
      putStrLn $ "Node socket: " <> show (nodeSocket cEnv)

    separate = liftIO $ putStrLn "\n------------\n"

    printWallet :: (BpiWallet, Int) -> ReaderT ClusterEnv IO ()
    printWallet (w, n) = liftIO $ do
      putStrLn $ "Wallet " ++ show n ++ " PKH: " ++ show (walletPkh w)
      putStrLn $ "Wallet " ++ show n ++ " mainnet address: " ++ show (mkMainnetAddress w)

    toAda = (* 1_000_000)

    executeContract wallet contract =
      ask >>= \cEnv -> runContract cEnv wallet contract

    printResult res = do
      liftIO . putStrLn $ "Execution outcome:\n" <> pShow' (outcome res)
      liftIO . putStrLn $
        "Contract state:\n"
          <> pShow' (getLast $ contractState res)

    pShow' :: Show a => a -> String
    pShow' = T.unpack . pShow

https://github.com/mlabs-haskell/plutip/blob/7f2d59abd911dd11310404863cdedb2886902ebf/contract-execution/Main.hs

Datum

Each UTxO locked at a script address will also have an associated datum. The script can choose to use the datum as part of the spending validation, or it can choose to ignore the datum if it is irrelevant.

Helios: get uplc

  • comment 61 62
  • test
    // NFT minting script
    const nftScript = await fs.readFile('./src/nft.hl', 'utf8');
    const nftProgram = Program.new(nftScript);
    nftProgram.parameters = {["TX_ID"] : utxos[0].txId.hex};
    nftProgram.parameters = {["TX_IDX"] : utxos[0].utxoIdx};
    const nftCompiledProgram = nftProgram.compile(optimize);
    const nftMPH = nftCompiledProgram.mintingPolicyHash;
Alternative

littercoin minting module

when called via cli, passing parameters (see here), it returns a Json object with a status message and a cborHex (L142)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.