Skip to content

Commit

Permalink
Merge pull request #63 from Nuklai/update-hypersdk
Browse files Browse the repository at this point in the history
Update hypersdk
  • Loading branch information
kpachhai authored Oct 22, 2024
2 parents a0a6fb3 + 4b69fd2 commit 41483c3
Show file tree
Hide file tree
Showing 27 changed files with 3,683 additions and 13,774 deletions.
29 changes: 29 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
[workspace]
members = [
"x/contracts/sdk-macros",
"x/contracts/wasmlanche",
"x/contracts/examples/token",
"x/contracts/examples/counter",
"x/contracts/examples/counter-external",
"x/contracts/examples/automated-market-maker",
"x/contracts/wasmlanche/tests/test-crate",
"x/contracts/test/contracts/*",
"x/contracts/simulator",
"x/contracts/examples/tutorial",
"x/contracts/examples/multisig",
]
resolver = "2"

[profile.release]
opt-level = "s"
lto = true
codegen-units = 1
overflow-checks = true
panic = 'abort'
strip = true

[workspace.dependencies]
sdk-macros = { path = "x/contracts/sdk-macros" }
wasmlanche = { path = "x/contracts/wasmlanche" }
simulator = { path = "x/contracts/simulator" }
thiserror = "1.0.61"
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -427,6 +427,10 @@ Refer to [Datasets Demo](./docs/demos/datasets.md) to learn how to create a data
Refer to [Marketplace Demo](./docs/demos/marketplace.md) to learn how to create a publish your dataset up for sale on the Nuklai Marketplace and how to subscribe to a dataset.
### WASM smart contracts
Refer to [WASM Smart Contracts Demo](./docs/demos/wasm_smart_contracts.md) to learn how to deploy smart contracts and interact with them on NuklaiVM.
## Faucet
You can run the faucet by doing:
Expand Down
18 changes: 12 additions & 6 deletions actions/contract_call.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,10 @@ import (

var _ chain.Action = (*ContractCall)(nil)

const MaxCallDataSize = units.MiB
const (
MaxCallDataSize = units.MiB
MaxResultSizeLimit = units.MiB
)

type StateKeyPermission struct {
Key string
Expand Down Expand Up @@ -68,7 +71,7 @@ func (t *ContractCall) Execute(
actor codec.Address,
_ ids.ID,
) (codec.Typed, error) {
resutBytes, err := t.r.CallContract(ctx, &runtime.CallInfo{
callInfo := &runtime.CallInfo{
Contract: t.ContractAddress,
Actor: actor,
State: &storage.ContractStateManager{Mutable: mu},
Expand All @@ -77,11 +80,13 @@ func (t *ContractCall) Execute(
Timestamp: uint64(timestamp),
Fuel: t.Fuel,
Value: t.Value,
})
}
resultBytes, err := t.r.CallContract(ctx, callInfo)
if err != nil {
return nil, err
}
return &ContractCallResult{Value: resutBytes}, nil
consumedFuel := t.Fuel - callInfo.RemainingFuel()
return &ContractCallResult{Value: resultBytes, ConsumedFuel: consumedFuel}, nil
}

func (t *ContractCall) ComputeUnits(chain.Rules) uint64 {
Expand All @@ -96,7 +101,7 @@ func (*ContractCall) ValidRange(chain.Rules) (int64, int64) {
var _ chain.Marshaler = (*ContractCall)(nil)

func (t *ContractCall) Size() int {
return codec.AddressLen + 2*consts.Uint64Len + len(t.CallData) + len(t.Function) + len(t.SpecifiedStateKeys)
return codec.AddressLen + 2*consts.Uint64Len + codec.BytesLen(t.CallData) + codec.StringLen(t.Function) + len(t.SpecifiedStateKeys)
}

func (t *ContractCall) Marshal(p *codec.Packer) {
Expand Down Expand Up @@ -138,7 +143,8 @@ func UnmarshalCallContract(r *runtime.WasmRuntime) func(p *codec.Packer) (chain.
var _ codec.Typed = (*ContractCallResult)(nil)

type ContractCallResult struct {
Value []byte `serialize:"true" json:"value"`
Value []byte `serialize:"true" json:"value"`
ConsumedFuel uint64 `serialize:"true" json:"consumedfuel"`
}

func (*ContractCallResult) GetTypeID() uint8 {
Expand Down
4 changes: 2 additions & 2 deletions actions/contract_deploy.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ func (*ContractDeploy) ValidRange(chain.Rules) (int64, int64) {
var _ chain.Marshaler = (*ContractDeploy)(nil)

func (d *ContractDeploy) Size() int {
return len(d.CreationInfo) + len(d.ContractID)
return codec.BytesLen(d.CreationInfo) + codec.BytesLen(d.ContractID)
}

func (d *ContractDeploy) Marshal(p *codec.Packer) {
Expand All @@ -78,7 +78,7 @@ func (d *ContractDeploy) Marshal(p *codec.Packer) {

func UnmarshalDeployContract(p *codec.Packer) (chain.Action, error) {
var deployContract ContractDeploy
p.UnpackBytes(36, true, (*[]byte)(&deployContract.ContractID))
p.UnpackBytes(40, true, (*[]byte)(&deployContract.ContractID))
p.UnpackBytes(MAXCREATIONSIZE, false, &deployContract.CreationInfo)
deployContract.address = storage.GetAddressForDeploy(0, deployContract.CreationInfo)
if err := p.Err(); err != nil {
Expand Down
2 changes: 1 addition & 1 deletion actions/contract_publish.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ func (*ContractPublish) ValidRange(chain.Rules) (int64, int64) {
var _ chain.Marshaler = (*ContractPublish)(nil)

func (t *ContractPublish) Size() int {
return 4 + len(t.ContractBytes)
return codec.BytesLen(t.ContractBytes)
}

func (t *ContractPublish) Marshal(p *codec.Packer) {
Expand Down
5 changes: 2 additions & 3 deletions actions/register_validator_stake_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ import (

"github.com/ava-labs/hypersdk/auth"
"github.com/ava-labs/hypersdk/chain/chaintest"
"github.com/ava-labs/hypersdk/cli"
"github.com/ava-labs/hypersdk/codec"
"github.com/ava-labs/hypersdk/crypto/bls"
"github.com/ava-labs/hypersdk/state"
Expand Down Expand Up @@ -183,7 +182,7 @@ func BenchmarkRegisterValidatorStake(b *testing.B) {
registerValidatorStakeBenchmark.Run(ctx, b)
}

func generateStakeInfoAndSignature(nodeID ids.NodeID, stakeStartBlock, stakeEndBlock, stakedAmount, delegationFeeRate uint64) ([]byte, []byte, *cli.PrivateKey, []byte) {
func generateStakeInfoAndSignature(nodeID ids.NodeID, stakeStartBlock, stakeEndBlock, stakedAmount, delegationFeeRate uint64) ([]byte, []byte, *auth.PrivateKey, []byte) {
blsBase64Key, err := base64.StdEncoding.DecodeString("MdWjv5OOW/p/JKt673vYxwROsfTCO7iZ2jwWCnY18hw=")
if err != nil {
panic(err)
Expand All @@ -192,7 +191,7 @@ func generateStakeInfoAndSignature(nodeID ids.NodeID, stakeStartBlock, stakeEndB
if err != nil {
panic(err)
}
blsPrivateKey := &cli.PrivateKey{
blsPrivateKey := &auth.PrivateKey{
Address: auth.NewBLSAddress(bls.PublicFromPrivateKey(secretKey)),
Bytes: bls.PrivateKeyToBytes(secretKey),
}
Expand Down
2 changes: 1 addition & 1 deletion cmd/faucet/faucet.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Copyright (C) 2024, Ava Labs, Inc. All rights reserved.
// Copyright (C) 2024, Nuklai. All rights reserved.
// See the file LICENSE for licensing terms.

package main
Expand Down
108 changes: 63 additions & 45 deletions cmd/nuklai-cli/cmd/action.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import (
"github.com/nuklai/nuklaivm/actions"
"github.com/nuklai/nuklaivm/consts"
"github.com/nuklai/nuklaivm/storage"
"github.com/nuklai/nuklaivm/vm"
"github.com/spf13/cobra"
"github.com/status-im/keycard-go/hexutils"

Expand All @@ -32,6 +33,8 @@ import (
nutils "github.com/nuklai/nuklaivm/utils"
)

var errUnexpectedSimulateActionsOutput = errors.New("returned output from SimulateActions was not actions.Result")

var actionCmd = &cobra.Command{
Use: "action",
RunE: func(*cobra.Command, []string) error {
Expand Down Expand Up @@ -131,6 +134,43 @@ var publishFileCmd = &cobra.Command{
},
}

var deployCmd = &cobra.Command{
Use: "deploy",
RunE: func(*cobra.Command, []string) error {
ctx := context.Background()
_, _, factory, cli, bcli, ws, err := handler.DefaultActor()
if err != nil {
return err
}

contractID, err := prompt.Bytes("contract id")
if err != nil {
return err
}

creationInfo, err := prompt.Bytes("creation info")
if err != nil {
return err
}

// Confirm action
cont, err := prompt.Continue()
if !cont || err != nil {
return err
}

// Generate transaction
result, _, err := sendAndWait(ctx, []chain.Action{&actions.ContractDeploy{
ContractID: contractID,
CreationInfo: creationInfo,
}}, cli, bcli, ws, factory)
if err != nil {
return err
}
return processResult(result)
},
}

var callCmd = &cobra.Command{
Use: "call",
RunE: func(*cobra.Command, []string) error {
Expand All @@ -141,7 +181,7 @@ var callCmd = &cobra.Command{
}

// Get balance info
balance, err := handler.GetBalance(ctx, bcli, priv.Address, ids.Empty)
balance, err := handler.GetBalance(ctx, bcli, priv.Address)
if balance == 0 || err != nil {
return err
}
Expand All @@ -168,18 +208,34 @@ var callCmd = &cobra.Command{
ContractAddress: contractAddress,
Value: amount,
Function: function,
Fuel: uint64(1000000000),
}

specifiedStateKeysSet, fuel, err := bcli.Simulate(ctx, *action, priv.Address)
actionSimulationResults, err := cli.SimulateActions(ctx, chain.Actions{action}, priv.Address)
if err != nil {
return err
}
if len(actionSimulationResults) != 1 {
return fmt.Errorf("unexpected number of returned actions. One action expected, %d returned", len(actionSimulationResults))
}
actionSimulationResult := actionSimulationResults[0]

rtx := codec.NewReader(actionSimulationResult.Output, len(actionSimulationResult.Output))

action.SpecifiedStateKeys = make([]actions.StateKeyPermission, 0, len(specifiedStateKeysSet))
for key, value := range specifiedStateKeysSet {
simulationResultOutput, err := (*vm.OutputParser).Unmarshal(rtx)
if err != nil {
return err
}
simulationResult, ok := simulationResultOutput.(*actions.ContractCallResult)
if !ok {
return errUnexpectedSimulateActionsOutput
}

action.SpecifiedStateKeys = make([]actions.StateKeyPermission, 0, len(actionSimulationResult.StateKeys))
for key, value := range actionSimulationResult.StateKeys {
action.SpecifiedStateKeys = append(action.SpecifiedStateKeys, actions.StateKeyPermission{Key: key, Permission: value})
}
action.Fuel = fuel
action.Fuel = simulationResult.ConsumedFuel

// Confirm action
cont, err := prompt.Continue()
Expand All @@ -189,9 +245,8 @@ var callCmd = &cobra.Command{

// Generate transaction
result, _, err := sendAndWait(ctx, []chain.Action{action}, cli, bcli, ws, factory)
if result != nil && result.Success {
utils.Outf("{{green}}fee consumed:{{/}} %s\n", nutils.FormatBalance(result.Fee, consts.Decimals))

if result != nil && result.Success {
utils.Outf(hexutils.BytesToHex(result.Outputs[0]) + "\n")
switch function {
case "balance":
Expand All @@ -201,7 +256,7 @@ var callCmd = &cobra.Command{
if err != nil {
return err
}
utils.Outf("%s\n", nutils.FormatBalance(intValue, consts.Decimals))
utils.Outf("%s\n", utils.FormatBalance(intValue))
}
case "get_value":
{
Expand All @@ -218,43 +273,6 @@ var callCmd = &cobra.Command{
},
}

var deployCmd = &cobra.Command{
Use: "deploy",
RunE: func(*cobra.Command, []string) error {
ctx := context.Background()
_, _, factory, cli, bcli, ws, err := handler.DefaultActor()
if err != nil {
return err
}

contractID, err := prompt.Bytes("contract id")
if err != nil {
return err
}

creationInfo, err := prompt.Bytes("creation info")
if err != nil {
return err
}

// Confirm action
cont, err := prompt.Continue()
if !cont || err != nil {
return err
}

// Generate transaction
result, _, err := sendAndWait(ctx, []chain.Action{&actions.ContractDeploy{
ContractID: contractID,
CreationInfo: creationInfo,
}}, cli, bcli, ws, factory)
if err != nil {
return err
}
return processResult(result)
},
}

// Define the layout that matches the provided date string
// Note: the reference time is "Mon Jan 2 15:04:05 MST 2006" in Go
const (
Expand Down
9 changes: 4 additions & 5 deletions cmd/nuklai-cli/cmd/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ func (h *Handler) BalanceAsset(checkAllChains bool, isNFT bool, printBalance fun
}

func (h *Handler) DefaultActor() (
ids.ID, *cli.PrivateKey, chain.AuthFactory,
ids.ID, *auth.PrivateKey, chain.AuthFactory,
*jsonrpc.JSONRPCClient, *vm.JSONRPCClient, *ws.WebSocketClient, error,
) {
addr, priv, err := h.h.GetDefaultKey(true)
Expand Down Expand Up @@ -189,7 +189,7 @@ func (h *Handler) DefaultActor() (
return ids.Empty, nil, nil, nil, nil, nil, err
}
// For [defaultActor], we always send requests to the first returned URI.
return chainID, &cli.PrivateKey{
return chainID, &auth.PrivateKey{
Address: addr,
Bytes: priv,
}, factory, jcli,
Expand Down Expand Up @@ -218,9 +218,8 @@ func (*Handler) GetBalance(
ctx context.Context,
cli *vm.JSONRPCClient,
addr codec.Address,
asset ids.ID,
) (uint64, error) {
balance, err := cli.Balance(ctx, addr.String(), asset.String())
balance, err := cli.Balance(ctx, addr.String(), storage.NAIAddress.String())
if err != nil {
return 0, err
}
Expand Down Expand Up @@ -603,6 +602,6 @@ func (*Controller) HandleTx(tx *chain.Transaction, result *chain.Result) {

func (*Controller) LookupBalance(address codec.Address, uri string) (uint64, error) {
cli := vm.NewJSONRPCClient(uri)
balance, err := cli.Balance(context.TODO(), address.String(), ids.Empty.String())
balance, err := cli.Balance(context.TODO(), address.String(), storage.NAIAddress.String())
return balance, err
}
Loading

0 comments on commit 41483c3

Please sign in to comment.