Skip to content

Commit

Permalink
Brought nuklaivm to parity with hypersdk from 20241018
Browse files Browse the repository at this point in the history
  • Loading branch information
kpachhai committed Oct 21, 2024
1 parent a0a6fb3 commit a89ed82
Show file tree
Hide file tree
Showing 12 changed files with 77 additions and 162 deletions.
28 changes: 17 additions & 11 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 All @@ -30,20 +33,20 @@ type StateKeyPermission struct {

type ContractCall struct {
// contract is the address of the contract to be called
ContractAddress codec.Address `serialize:"true" json:"contractAddress"`
ContractAddress codec.Address `json:"contractAddress"`

// Amount are transferred to [To].
Value uint64 `serialize:"true" json:"value"`
Value uint64 `json:"value"`

// Function is the name of the function to call on the contract.
Function string `serialize:"true" json:"function"`
Function string `json:"function"`

// CallData are the serialized parameters to be passed to the contract.
CallData []byte `serialize:"true" json:"calldata"`
CallData []byte `json:"calldata"`

SpecifiedStateKeys []StateKeyPermission `serialize:"true" json:"statekeys"`
SpecifiedStateKeys []StateKeyPermission `json:"statekeys"`

Fuel uint64 `serialize:"true" json:"fuel"`
Fuel uint64 `json:"fuel"`

r *runtime.WasmRuntime
}
Expand All @@ -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 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 @@ -24,8 +24,8 @@ var _ chain.Action = (*ContractDeploy)(nil)
const MAXCREATIONSIZE = units.MiB

type ContractDeploy struct {
ContractID runtime.ContractID `serialize:"true" json:"contractID"`
CreationInfo []byte `serialize:"true" json:"creationInfo"`
ContractID runtime.ContractID `json:"contractID"`
CreationInfo []byte `json:"creationInfo"`
address codec.Address
}

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
32 changes: 25 additions & 7 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 @@ -168,18 +171,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 +208,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 +219,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 Down
4 changes: 2 additions & 2 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
27 changes: 13 additions & 14 deletions cmd/nuklai-cli/cmd/key.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ import (
"github.com/spf13/cobra"

"github.com/ava-labs/hypersdk/auth"
"github.com/ava-labs/hypersdk/cli"
"github.com/ava-labs/hypersdk/cli/prompt"
"github.com/ava-labs/hypersdk/codec"
"github.com/ava-labs/hypersdk/crypto/bls"
Expand Down Expand Up @@ -97,7 +96,7 @@ var importKeyCmd = &cobra.Command{
keyType := args[0]
keyInput := args[1]

var priv *cli.PrivateKey
var priv *auth.PrivateKey

// Check if the provided argument is a file path or an encoded string
if _, err := os.Stat(keyInput); err == nil {
Expand Down Expand Up @@ -274,14 +273,14 @@ func getKeyType(addr codec.Address) (string, error) {
}
}

func generatePrivateKey(k string) (*cli.PrivateKey, error) {
func generatePrivateKey(k string) (*auth.PrivateKey, error) {
switch k {
case ed25519Key:
p, err := ed25519.GeneratePrivateKey()
if err != nil {
return nil, err
}
return &cli.PrivateKey{
return &auth.PrivateKey{
Address: auth.NewED25519Address(p.PublicKey()),
Bytes: p[:],
}, nil
Expand All @@ -290,7 +289,7 @@ func generatePrivateKey(k string) (*cli.PrivateKey, error) {
if err != nil {
return nil, err
}
return &cli.PrivateKey{
return &auth.PrivateKey{
Address: auth.NewSECP256R1Address(p.PublicKey()),
Bytes: p[:],
}, nil
Expand All @@ -299,7 +298,7 @@ func generatePrivateKey(k string) (*cli.PrivateKey, error) {
if err != nil {
return nil, err
}
return &cli.PrivateKey{
return &auth.PrivateKey{
Address: auth.NewBLSAddress(bls.PublicFromPrivateKey(p)),
Bytes: bls.PrivateKeyToBytes(p),
}, nil
Expand All @@ -308,15 +307,15 @@ func generatePrivateKey(k string) (*cli.PrivateKey, error) {
}
}

func loadPrivateKeyFromPath(k string, path string) (*cli.PrivateKey, error) {
func loadPrivateKeyFromPath(k string, path string) (*auth.PrivateKey, error) {
switch k {
case ed25519Key:
p, err := utils.LoadBytes(path, ed25519.PrivateKeyLen)
if err != nil {
return nil, err
}
pk := ed25519.PrivateKey(p)
return &cli.PrivateKey{
return &auth.PrivateKey{
Address: auth.NewED25519Address(pk.PublicKey()),
Bytes: p,
}, nil
Expand All @@ -326,7 +325,7 @@ func loadPrivateKeyFromPath(k string, path string) (*cli.PrivateKey, error) {
return nil, err
}
pk := secp256r1.PrivateKey(p)
return &cli.PrivateKey{
return &auth.PrivateKey{
Address: auth.NewSECP256R1Address(pk.PublicKey()),
Bytes: p,
}, nil
Expand All @@ -340,7 +339,7 @@ func loadPrivateKeyFromPath(k string, path string) (*cli.PrivateKey, error) {
if err != nil {
return nil, err
}
return &cli.PrivateKey{
return &auth.PrivateKey{
Address: auth.NewBLSAddress(bls.PublicFromPrivateKey(privKey)),
Bytes: p,
}, nil
Expand All @@ -350,7 +349,7 @@ func loadPrivateKeyFromPath(k string, path string) (*cli.PrivateKey, error) {
}

// loadPrivateKeyFromString loads a private key from a base64 string.
func loadPrivateKeyFromString(k, keyStr string) (*cli.PrivateKey, error) {
func loadPrivateKeyFromString(k, keyStr string) (*auth.PrivateKey, error) {
var decodedKey []byte
var err error

Expand All @@ -364,13 +363,13 @@ func loadPrivateKeyFromString(k, keyStr string) (*cli.PrivateKey, error) {
switch k {
case ed25519Key:
pk := ed25519.PrivateKey(decodedKey)
return &cli.PrivateKey{
return &auth.PrivateKey{
Address: auth.NewED25519Address(pk.PublicKey()),
Bytes: decodedKey,
}, nil
case secp256r1Key:
pk := secp256r1.PrivateKey(decodedKey)
return &cli.PrivateKey{
return &auth.PrivateKey{
Address: auth.NewSECP256R1Address(pk.PublicKey()),
Bytes: decodedKey,
}, nil
Expand All @@ -379,7 +378,7 @@ func loadPrivateKeyFromString(k, keyStr string) (*cli.PrivateKey, error) {
if err != nil {
return nil, fmt.Errorf("failed to load BLS private key: %w", err)
}
return &cli.PrivateKey{
return &auth.PrivateKey{
Address: auth.NewBLSAddress(bls.PublicFromPrivateKey(pk)),
Bytes: bls.PrivateKeyToBytes(pk),
}, nil
Expand Down
Loading

0 comments on commit a89ed82

Please sign in to comment.